context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Serialization; using System.Diagnostics; using Microsoft.Win32; using NPanday.Plugin; using NPanday.Model.Pom; using NPanday.Artifact; using System.Reflection; namespace NPanday.Plugin.SysRef { /// <summary> /// C# Plugin that will generate the required system reference .dlls /// </summary> [ClassAttribute(Phase = "SysRef", Goal = "prepare")] public sealed class SysRefMojo : AbstractMojo { public SysRefMojo() { } [FieldAttribute("repository", Expression = "${settings.localRepository}", Type = "java.lang.String")] public String localRepository; [FieldAttribute("mavenProject", Expression = "${project}", Type = "org.apache.maven.project.MavenProject")] public NPanday.Model.Pom.Model mavenProject; public override Type GetMojoImplementationType() { return this.GetType(); } private void GenerateDependency(string filename) { ProcessStartInfo processStartInfo = new ProcessStartInfo("tlbimp", filename); processStartInfo.UseShellExecute = true; processStartInfo.WindowStyle = ProcessWindowStyle.Hidden; System.Diagnostics.Process.Start(processStartInfo); } private string GetFileName(NPanday.Model.Pom.Dependency dependency) { RegistryKey root = Registry.ClassesRoot; string filename = string.Empty; try { String[] classTokens = dependency.classifier.Split("}".ToCharArray()); String[] versionTokens = classTokens[1].Split("-".ToCharArray()); classTokens[1] = classTokens[1].Replace("-", "\\"); String newClassifier = classTokens[0] + "}" + classTokens[1]; RegistryKey typeLib = root.OpenSubKey("TypeLib"); RegistryKey target = typeLib.OpenSubKey(classTokens[0] + "}").OpenSubKey(versionTokens[1]).OpenSubKey(versionTokens[2]).OpenSubKey("win32"); filename = target.GetValue("").ToString(); } catch (Exception exe) { Console.WriteLine(exe.Message); } return filename; } private void LocalInstall(NPanday.Model.Pom.Dependency dependency, string fileName) { try { String[] rawName = GetFileName(dependency).Split("\\".ToCharArray()); string generatedDLL = rawName[rawName.Length - 1]; generatedDLL = generatedDLL.Replace("tlb", "dll"); string directory = localRepository.Replace("\\", "/"); //Creating of Directories directory = directory + "/" + dependency.groupId; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } directory = directory + "/" + dependency.artifactId; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } directory = directory + "/" + dependency.version; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } string newDll = dependency.artifactId + "-" + dependency.version + "-" + dependency.classifier + "." + dependency.type; string destinationFile = localRepository + "\\" + dependency.groupId + "\\" + dependency.artifactId + "\\" + dependency.version + "\\" + newDll; destinationFile = destinationFile.Replace("\\", "/"); string tempDir = "c:/Windows/Temp/NPanday"; if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } fileName = "\"" + fileName + "\""; fileName = fileName + " /out:" + tempDir + "/" + dependency.artifactId+".dll"; GenerateDependency(fileName); string sourceFile = tempDir + "/" + dependency.artifactId + ".dll"; bool waiting = true; while (waiting) { if (File.Exists(sourceFile)) { waiting = false; } } if (!File.Exists(destinationFile)) { System.Threading.Thread.Sleep(4500); File.Copy(sourceFile, destinationFile); } } catch (Exception exe) { Console.WriteLine("[ERROR] The Reference is not located.\n"+exe.Message); } } public void SystemInstall(NPanday.Model.Pom.Dependency dependency) { try { if (dependency.systemPath == null || dependency.systemPath == string.Empty) { Assembly a = System.Reflection.Assembly.LoadWithPartialName(dependency.artifactId); dependency.systemPath = a.Location; } string sourceFile = dependency.systemPath; sourceFile = sourceFile.Replace("\\", "/"); string directory = localRepository.Replace("\\", "/"); //Creating of Directories directory = directory + "/" + dependency.groupId; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } directory = directory + "/" + dependency.artifactId; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } directory = directory + "/" + dependency.version; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } string newDll = dependency.artifactId + "-" + dependency.version + "-" + dependency.classifier + "." + dependency.type; string destinationFile = localRepository + "\\" + dependency.groupId + "\\" + dependency.artifactId + "\\" + dependency.version + "\\" + newDll; destinationFile = destinationFile.Replace("\\", "/"); if (!File.Exists(destinationFile)) { File.Copy(sourceFile, destinationFile); } } catch (Exception exe) { Console.WriteLine(exe.Message); } } public override void Execute() { try { if(mavenProject.dependencies==null) { return; } foreach (NPanday.Model.Pom.Dependency dependency in mavenProject.dependencies) { if (dependency.type.Equals("com_reference")) { //GenerateDependency(GetFileName(dependency)); LocalInstall(dependency, GetFileName(dependency)); Console.WriteLine("Successfully Installed : " + dependency.artifactId); } if (dependency.type.Contains("gac") || dependency.type.Equals("library") || dependency.type.Equals("dotnet-library")) { if (dependency.systemPath != null || dependency.systemPath != string.Empty) { SystemInstall(dependency); Console.WriteLine("Successfully Installed : " + dependency.artifactId); } } } } catch (Exception exe) { Console.WriteLine(exe.Message); } } } }
using System; using UnityEngine; namespace Stratus { /// <summary> /// An optional attribute for Stratus singletons, offering more control over its initial setup. /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = true)] public sealed class StratusSingletonAttribute : Attribute { /// <summary> /// Whether the class should only be instantiated during playmode /// </summary> public bool isPlayerOnly { get; set; } = true; /// <summary> /// If instantiated, the name of the GameObject that will contain the singleton /// </summary> public string name { get; set; } /// <summary> /// Whether to instantiate an instance of the class if one is not found present at runtime /// </summary> public bool instantiate { get; set; } /// <summary> /// Whether the instance is persistent across scene loading /// </summary> public bool persistent { get; set; } /// <param name="name">The name of the GameObject where the singleton will be placed</param> /// <param name="persistent">Whether the instance is persistent across scene loading</param> /// <param name="instantiate">Whether to instantiate an instance of the class if one is not found present at runtime</param> public StratusSingletonAttribute(string name, bool persistent = true, bool instantiate = true) { this.name = name; this.persistent = persistent; this.instantiate = instantiate; } public StratusSingletonAttribute() { this.instantiate = true; this.persistent = true; } } /// <summary> /// A singleton is a class with only one active instance, instantiated if not present when its /// static members are accessed. Use the [Singleton] attribute on the class /// declaration in order to override the default settings. /// </summary> /// <typeparam name="T"></typeparam> [DisallowMultipleComponent] public abstract class StratusSingletonBehaviour<T> : StratusBehaviour where T : StratusBehaviour { //------------------------------------------------------------------------/ // Properties //------------------------------------------------------------------------/ /// <summary> /// Whether this singleton will be persistent whenever its parent scene is destroyed /// </summary> protected static bool isPersistent => attribute?.GetProperty<bool>(nameof(StratusSingletonAttribute.persistent)) ?? true; /// <summary> /// Whether the application is currently quitting play mode /// </summary> protected static bool isQuitting { get; set; } = false; /// <summary> /// Returns the current specific attributes for the derived singleton class, if any are present /// </summary> private static StratusSingletonAttribute attribute => typeof(T).GetAttribute<StratusSingletonAttribute>(); /// <summary> /// Whether the class should be instantiated. By default, true. /// </summary> private static bool shouldInstantiate => attribute?.GetProperty<bool>(nameof(StratusSingletonAttribute.instantiate)) ?? true; /// <summary> /// Whether the class should be instantiated while in editor mode /// </summary> private static bool isPlayerOnly => attribute?.GetProperty<bool>(nameof(StratusSingletonAttribute.isPlayerOnly)) ?? true; /// <summary> /// What name to use for GameObject this singleton will be instantiated on /// </summary> private static string ownerName => attribute?.GetProperty<string>(nameof(StratusSingletonAttribute.name)) ?? typeof(T).Name; /// <summary> /// Returns a reference to the singular instance of this class. If not available currently, /// it will instantiate it when accessed. /// </summary> public static T instance { get { // Look for an instance in the scene if (!_instance) { _instance = FindObjectOfType<T>(); // If not found, instantiate if (!_instance) { if (shouldInstantiate == false || (isPlayerOnly && StratusEditorBridge.isEditMode)) { //Trace.Script("Will not instantiate the class " + typeof(T).Name); return null; } //Trace.Script("Creating " + typeof(T).Name); GameObject obj = new GameObject { name = ownerName }; _instance = obj.AddComponent<T>(); } } return _instance; } } /// <summary> /// Whether this singleton has been instantiated /// </summary> public static bool instantiated => instance != null; //------------------------------------------------------------------------/ // Fields //------------------------------------------------------------------------/ /// <summary> /// The singular instance of the class /// </summary> protected static T _instance; //------------------------------------------------------------------------/ // Interface //------------------------------------------------------------------------/ protected abstract void OnAwake(); protected virtual void OnSingletonDestroyed() { } //------------------------------------------------------------------------/ // Messages //------------------------------------------------------------------------/ private void Awake() { // If the singleton instance hasn't been set, set it to self if (!instance) { _instance = this as T; } // If we are the singleton instance that was created (or recently set) if (instance == this as T) { if (isPersistent) { if (!StratusEditorBridge.isEditMode) { this.OnDontDestroyOnLoad(); } } this.OnAwake(); } // If we are not... else { Destroy(this.gameObject); } } private void OnDestroy() { if (this != _instance) { return; } _instance = null; this.OnSingletonDestroyed(); } private void OnApplicationQuit() { isQuitting = true; } protected virtual void OnDontDestroyOnLoad() { this.transform.SetParent(null); DontDestroyOnLoad(this); } //------------------------------------------------------------------------/ // Methods //------------------------------------------------------------------------/ /// <summary> /// Instantiates this singleton if possible /// </summary> /// <returns></returns> public static bool Instantiate() { if (instance != null) { return true; } return false; } protected void Poke() { } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.Diagnostics; /// <summary> /// This is public domain software - that is, you can do whatever you want /// with it, and include it software that is licensed under the GNU or the /// BSD license, or whatever other licence you choose, including proprietary /// closed source licenses. I do ask that you leave this lcHeader in tact. /// /// Trionic5Controls.NET makes use of this control to display pictures. /// Please visit <a href="http://www.Trionic5Controls.net/en/">http://www.Trionic5Controls.net/en/</a> /// </summary> namespace Trionic5Controls { /// <summary> /// Front end control of the scrollable, zoomable and scalable picture box. /// It is a facade and mediator of ScalablePictureBoxImp control and PictureTracker control. /// An application should use this control for showing picture /// instead of using ScalablePictureBox control directly. /// </summary> public partial class ScalablePictureBox : UserControl { /// <summary> /// delegate of PictureBox painted event handler /// </summary> /// <param name="visibleAreaRect">currently visible area of picture</param> /// <param name="pictureBoxRect">picture box area</param> //public delegate void PictureBoxPaintedEventHandlerEx(Rectangle visibleAreaRect, Rectangle pictureBoxRect, Graphics graphics); /// <summary> /// PictureBox painted event /// </summary> // public event ScalablePictureBox.PictureBoxPaintedEventHandlerEx PictureBoxPaintedEvent; /// <summary> /// indicating mouse dragging mode of picture tracker control /// </summary> private bool isDraggingPictureTracker = false; /// <summary> /// last mouse position of mouse dragging /// </summary> Point lastMousePos; /// <summary> /// the new area where the picture tracker control to be dragged /// </summary> Rectangle draggingRectangle; /// <summary> /// Constructor /// </summary> public ScalablePictureBox() { InitializeComponent(); this.pictureTracker.BringToFront(); // enable double buffering this.SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); // register event handler for events from ScalablePictureBox this.scalablePictureBoxImp.PictureBoxPaintedEvent += new ScalablePictureBoxImp.PictureBoxPaintedEventHandler(scalablePictureBoxImp_PictureBoxPaintedEvent); this.scalablePictureBoxImp.ZoomRateChangedEvent += new ScalablePictureBoxImp.ZoomRateChangedEventHandler(this.scalablePictureBox_ZoomRateChanged); // register event handler for events from PictureTracker this.pictureTracker.ScrollPictureEvent += new PictureTracker.ScrollPictureEventHandler(this.scalablePictureBoxImp.OnScrollPictureEvent); this.pictureTracker.PictureTrackerClosed += new PictureTracker.PictureTrackerClosedHandler(this.pictureTracker_PictureTrackerClosed); } void scalablePictureBoxImp_PictureBoxPaintedEvent(Rectangle visibleAreaRect, Rectangle pictureBoxRect, Graphics graphics) { //Console.WriteLine("scalablePictureBoxImp_PictureBoxPaintedEvent"); this.pictureTracker.OnPictureBoxPainted(visibleAreaRect, pictureBoxRect); //Console.WriteLine("this.pictureTracker.OnPictureBoxPainted"); /*if (PictureBoxPaintedEvent != null) { Rectangle thisControlClientRect = this.ClientRectangle; thisControlClientRect.X -= this.AutoScrollPosition.X; thisControlClientRect.Y -= this.AutoScrollPosition.Y; PictureBoxPaintedEvent(thisControlClientRect, this.ClientRectangle, graphics); } Console.WriteLine("PictureBoxPaintedEvent");*/ } /// <summary> /// Set a picture to show in ScalablePictureBox control /// </summary> public Image Picture { set { this.scalablePictureBoxImp.Picture = value; this.pictureTracker.Picture = value; this.scalablePictureBoxImp.ScalePictureBoxToFit(); } } /// <summary> /// Get picture box control /// </summary> [Bindable(false)] public PictureBox PictureBox { get { return this.scalablePictureBoxImp.PictureBox; } } /// <summary> /// Notify current scale percentage to PictureTracker control if current picture is /// zoomed in, or hide PictureTracker control if current picture is shown fully. /// </summary> /// <param name="zoomRate">zoom rate of picture</param> /// <param name="isWholePictureShown">true if the whole picture is shown</param> private void scalablePictureBox_ZoomRateChanged(int zoomRate, bool isWholePictureShown) { if (isWholePictureShown) { this.pictureTracker.Visible = false; this.pictureTracker.Enabled = false; } else { this.pictureTracker.Visible = true; this.pictureTracker.Enabled = true; this.pictureTracker.ZoomRate = zoomRate; } } /// <summary> /// Inform ScalablePictureBox control to show picture fully. /// </summary> private void pictureTracker_PictureTrackerClosed() { this.scalablePictureBoxImp.ImageSizeMode = PictureBoxSizeMode.Zoom; } /// <summary> /// Draw a reversible rectangle /// </summary> /// <param name="rect">rectangle to be drawn</param> private void DrawReversibleRect(Rectangle rect) { // Convert the location of rectangle to screen coordinates. rect.Location = PointToScreen(rect.Location); // Draw the reversible frame. ControlPaint.DrawReversibleFrame(rect, Color.Navy, FrameStyle.Thick); } /// <summary> /// begin to drag picture tracker control /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void pictureTracker_MouseDown(object sender, MouseEventArgs e) { isDraggingPictureTracker = true; // Make a note that we are dragging picture tracker control // Store the last mouse poit for this rubber-band rectangle. lastMousePos.X = e.X; lastMousePos.Y = e.Y; // draw initial dragging rectangle draggingRectangle = this.pictureTracker.Bounds; DrawReversibleRect(draggingRectangle); } /// <summary> /// dragging picture tracker control in mouse dragging mode /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void pictureTracker_MouseMove(object sender, MouseEventArgs e) { if (isDraggingPictureTracker) { // caculating next candidate dragging rectangle Point newPos = new Point(draggingRectangle.Location.X + e.X - lastMousePos.X, draggingRectangle.Location.Y + e.Y - lastMousePos.Y); Rectangle newPictureTrackerArea = draggingRectangle; newPictureTrackerArea.Location = newPos; // saving current mouse position to be used for next dragging this.lastMousePos = new Point(e.X, e.Y); // dragging picture tracker only when the candidate dragging rectangle // is within this ScalablePictureBox control if (this.ClientRectangle.Contains(newPictureTrackerArea)) { // removing previous rubber-band frame DrawReversibleRect(draggingRectangle); // updating dragging rectangle draggingRectangle = newPictureTrackerArea; // drawing new rubber-band frame DrawReversibleRect(draggingRectangle); } } } /// <summary> /// end dragging picture tracker control /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void pictureTracker_MouseUp(object sender, MouseEventArgs e) { if (isDraggingPictureTracker) { isDraggingPictureTracker = false; // erase dragging rectangle DrawReversibleRect(draggingRectangle); // move the picture tracker control to the new position this.pictureTracker.Location = draggingRectangle.Location; } } /// <summary> /// relocate picture box at bottom right corner when the control size changed /// </summary> /// <param name="e"></param> protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); int x = this.ClientSize.Width - this.pictureTracker.Width - 20; int y = this.ClientSize.Height - this.pictureTracker.Height - 20; this.pictureTracker.Location = new Point(x, y); } } }
// 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 Xunit; namespace System.Linq.Expressions.Tests { public static class LiftedMultiplyNullableTests { #region Test methods [Fact] public static void CheckLiftedMultiplyNullableByteTest() { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyMultiplyNullableByte(values[i], values[j]); } } } [Fact] public static void CheckLiftedMultiplyNullableCharTest() { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyMultiplyNullableChar(values[i], values[j]); } } } [Fact] public static void CheckLiftedMultiplyNullableDecimalTest() { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyMultiplyNullableDecimal(values[i], values[j]); } } } [Fact] public static void CheckLiftedMultiplyNullableDoubleTest() { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyMultiplyNullableDouble(values[i], values[j]); } } } [Fact] public static void CheckLiftedMultiplyNullableFloatTest() { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyMultiplyNullableFloat(values[i], values[j]); } } } [Fact] public static void CheckLiftedMultiplyNullableIntTest() { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyMultiplyNullableInt(values[i], values[j]); } } } [Fact] public static void CheckLiftedMultiplyNullableLongTest() { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyMultiplyNullableLong(values[i], values[j]); } } } [Fact] public static void CheckLiftedMultiplyNullableSByteTest() { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyMultiplyNullableSByte(values[i], values[j]); } } } [Fact] public static void CheckLiftedMultiplyNullableShortTest() { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyMultiplyNullableShort(values[i], values[j]); } } } [Fact] public static void CheckLiftedMultiplyNullableUIntTest() { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyMultiplyNullableUInt(values[i], values[j]); } } } [Fact] public static void CheckLiftedMultiplyNullableULongTest() { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyMultiplyNullableULong(values[i], values[j]); } } } [Fact] public static void CheckLiftedMultiplyNullableUShortTest() { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyMultiplyNullableUShort(values[i], values[j]); } } } #endregion #region Helpers public static byte MultiplyNullableByte(byte a, byte b) { return (byte)(a * b); } public static char MultiplyNullableChar(char a, char b) { return (char)(a * b); } public static decimal MultiplyNullableDecimal(decimal a, decimal b) { return (decimal)(a * b); } public static double MultiplyNullableDouble(double a, double b) { return (double)(a * b); } public static float MultiplyNullableFloat(float a, float b) { return (float)(a * b); } public static int MultiplyNullableInt(int a, int b) { return (int)(a * b); } public static long MultiplyNullableLong(long a, long b) { return (long)(a * b); } public static sbyte MultiplyNullableSByte(sbyte a, sbyte b) { return (sbyte)(a * b); } public static short MultiplyNullableShort(short a, short b) { return (short)(a * b); } public static uint MultiplyNullableUInt(uint a, uint b) { return (uint)(a * b); } public static ulong MultiplyNullableULong(ulong a, ulong b) { return (ulong)(a * b); } public static ushort MultiplyNullableUShort(ushort a, ushort b) { return (ushort)(a * b); } #endregion #region Test verifiers private static void VerifyMultiplyNullableByte(byte? a, byte? b) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.Multiply( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), typeof(LiftedMultiplyNullableTests).GetTypeInfo().GetDeclaredMethod("MultiplyNullableByte"))); Func<byte?> f = e.Compile(); byte? result = default(byte); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } byte? expected = default(byte); Exception csEx = null; try { expected = (byte?)(a * b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifyMultiplyNullableChar(char? a, char? b) { Expression<Func<char?>> e = Expression.Lambda<Func<char?>>( Expression.Multiply( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), typeof(LiftedMultiplyNullableTests).GetTypeInfo().GetDeclaredMethod("MultiplyNullableChar"))); Func<char?> f = e.Compile(); char? result = default(char); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } char? expected = default(char); Exception csEx = null; try { expected = (char?)(a * b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifyMultiplyNullableDecimal(decimal? a, decimal? b) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Multiply( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), typeof(LiftedMultiplyNullableTests).GetTypeInfo().GetDeclaredMethod("MultiplyNullableDecimal"))); Func<decimal?> f = e.Compile(); decimal? result = default(decimal); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } decimal? expected = default(decimal); Exception csEx = null; try { expected = (decimal?)(a * b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifyMultiplyNullableDouble(double? a, double? b) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Multiply( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), typeof(LiftedMultiplyNullableTests).GetTypeInfo().GetDeclaredMethod("MultiplyNullableDouble"))); Func<double?> f = e.Compile(); double? result = default(double); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } double? expected = default(double); Exception csEx = null; try { expected = (double?)(a * b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifyMultiplyNullableFloat(float? a, float? b) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Multiply( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), typeof(LiftedMultiplyNullableTests).GetTypeInfo().GetDeclaredMethod("MultiplyNullableFloat"))); Func<float?> f = e.Compile(); float? result = default(float); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } float? expected = default(float); Exception csEx = null; try { expected = (float?)(a * b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifyMultiplyNullableInt(int? a, int? b) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Multiply( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), typeof(LiftedMultiplyNullableTests).GetTypeInfo().GetDeclaredMethod("MultiplyNullableInt"))); Func<int?> f = e.Compile(); int? result = default(int); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } int? expected = default(int); Exception csEx = null; try { expected = (int?)(a * b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifyMultiplyNullableLong(long? a, long? b) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Multiply( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), typeof(LiftedMultiplyNullableTests).GetTypeInfo().GetDeclaredMethod("MultiplyNullableLong"))); Func<long?> f = e.Compile(); long? result = default(long); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } long? expected = default(long); Exception csEx = null; try { expected = (long?)(a * b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifyMultiplyNullableSByte(sbyte? a, sbyte? b) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.Multiply( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), typeof(LiftedMultiplyNullableTests).GetTypeInfo().GetDeclaredMethod("MultiplyNullableSByte"))); Func<sbyte?> f = e.Compile(); sbyte? result = default(sbyte); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } sbyte? expected = default(sbyte); Exception csEx = null; try { expected = (sbyte?)(a * b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifyMultiplyNullableShort(short? a, short? b) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Multiply( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), typeof(LiftedMultiplyNullableTests).GetTypeInfo().GetDeclaredMethod("MultiplyNullableShort"))); Func<short?> f = e.Compile(); short? result = default(short); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } short? expected = default(short); Exception csEx = null; try { expected = (short?)(a * b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifyMultiplyNullableUInt(uint? a, uint? b) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Multiply( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), typeof(LiftedMultiplyNullableTests).GetTypeInfo().GetDeclaredMethod("MultiplyNullableUInt"))); Func<uint?> f = e.Compile(); uint? result = default(uint); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } uint? expected = default(uint); Exception csEx = null; try { expected = (uint?)(a * b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifyMultiplyNullableULong(ulong? a, ulong? b) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Multiply( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), typeof(LiftedMultiplyNullableTests).GetTypeInfo().GetDeclaredMethod("MultiplyNullableULong"))); Func<ulong?> f = e.Compile(); ulong? result = default(ulong); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } ulong? expected = default(ulong); Exception csEx = null; try { expected = (ulong?)(a * b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifyMultiplyNullableUShort(ushort? a, ushort? b) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Multiply( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), typeof(LiftedMultiplyNullableTests).GetTypeInfo().GetDeclaredMethod("MultiplyNullableUShort"))); Func<ushort?> f = e.Compile(); ushort? result = default(ushort); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } ushort? expected = default(ushort); Exception csEx = null; try { expected = (ushort?)(a * b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } #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.Threading; using System.Diagnostics; using System.Collections; using System.Collections.Generic; namespace System.Collections.Concurrent { // Abstract base for a thread-safe dictionary mapping a set of keys (K) to values (V). // // To create an actual dictionary, subclass this type and override the protected Factory method // to instantiate values (V) for the "Add" case. // // The key must be of a type that implements IEquatable<K>. The unifier calls IEquality<K>.Equals() // and Object.GetHashCode() on the keys. // // Deadlock risks: // - Keys may be tested for equality and asked to compute their hashcode while the unifier // holds its lock. Thus these operations must be written carefully to avoid deadlocks and // reentrancy in to the table. // // - The Factory method will never be called inside the unifier lock. If two threads race to // enter a value for the same key, the Factory() may get invoked twice for the same key - one // of them will "win" the race and its result entered into the dictionary - other gets thrown away. // // Notes: // - This class is used to look up types when GetType() or typeof() is invoked. // That means that this class itself cannot do or call anything that does these // things. // // - For this reason, it chooses not to mimic the official ConcurrentDictionary class // (I don't even want to risk using delegates.) Even the LowLevel versions of these // general utility classes may not be low-level enough for this class's purpose. // // Thread safety guarantees: // // ConcurrentUnifier is fully thread-safe and requires no // additional locking to be done by callers. // // Performance characteristics: // // ConcurrentUnifier will not block a reader, even while // the table is being written. Only one writer is allowed at a time; // ConcurrentUnifier handles the synchronization that ensures this. // // Safety for concurrent readers is ensured as follows: // // Each hash bucket is maintained as a stack. Inserts are done under // a lock; the entry is filled out completely, then "published" by a // single write to the top of the bucket. This ensures that a reader // will see a valid snapshot of the bucket, once it has read the head. // // On resize, we allocate an entirely new table, rather than resizing // in place. We fill in the new table completely, under the lock, // then "publish" it with a single write. Any reader that races with // this will either see the old table or the new one; each will contain // the same data. // internal abstract class ConcurrentUnifier<K, V> where K : IEquatable<K> where V : class { protected ConcurrentUnifier() { _lock = new Lock(); _container = new Container(this); } // // Retrieve the *unique* value for a given key. If the key was previously not entered into the dictionary, // this method invokes the overridable Factory() method to create the new value. The Factory() method is // invoked outside of any locks. If two threads race to enter a value for the same key, the Factory() // may get invoked twice for the same key - one of them will "win" the race and its result entered into the // dictionary - other gets thrown away. // public V GetOrAdd(K key) { Debug.Assert(key != null); Debug.Assert(!_lock.IsAcquired, "GetOrAdd called while lock already acquired. A possible cause of this is an Equals or GetHashCode method that causes reentrancy in the table."); int hashCode = key.GetHashCode(); V value; bool found = _container.TryGetValue(key, hashCode, out value); #if DEBUG { V checkedValue; bool checkedFound; // In debug builds, always exercise a locked TryGet (this is a good way to detect deadlock/reentrancy through Equals/GetHashCode()). using (LockHolder.Hold(_lock)) { _container.VerifyUnifierConsistency(); int h = key.GetHashCode(); checkedFound = _container.TryGetValue(key, h, out checkedValue); } if (found) { // State of a key must never go from found to not found, and only one value may exist per key. Debug.Assert(checkedFound); if (default(V) == null) // No good way to do the "only one value" check for value types. Debug.Assert(Object.ReferenceEquals(checkedValue, value)); } } #endif //DEBUG if (found) return value; value = this.Factory(key); using (LockHolder.Hold(_lock)) { V heyIWasHereFirst; if (_container.TryGetValue(key, hashCode, out heyIWasHereFirst)) return heyIWasHereFirst; if (!_container.HasCapacity) _container.Resize(); // This overwrites the _container field. _container.Add(key, hashCode, value); return value; } } protected abstract V Factory(K key); private volatile Container _container; private readonly Lock _lock; private sealed class Container { public Container(ConcurrentUnifier<K, V> owner) { // Note: This could be done by calling Resize()'s logic but we cannot safely do that as this code path is reached // during class construction time and Resize() pulls in enough stuff that we get cyclic cctor warnings from the build. _buckets = new int[_initialCapacity]; for (int i = 0; i < _initialCapacity; i++) _buckets[i] = -1; _entries = new Entry[_initialCapacity]; _nextFreeEntry = 0; _owner = owner; } private Container(ConcurrentUnifier<K, V> owner, int[] buckets, Entry[] entries, int nextFreeEntry) { _buckets = buckets; _entries = entries; _nextFreeEntry = nextFreeEntry; _owner = owner; } public bool TryGetValue(K key, int hashCode, out V value) { // Lock acquistion NOT required (but lock inacquisition NOT guaranteed either.) int bucket = ComputeBucket(hashCode, _buckets.Length); int i = Volatile.Read(ref _buckets[bucket]); while (i != -1) { if (key.Equals(_entries[i]._key)) { value = _entries[i]._value; return true; } i = _entries[i]._next; } value = default(V); return false; } public void Add(K key, int hashCode, V value) { Debug.Assert(_owner._lock.IsAcquired); int bucket = ComputeBucket(hashCode, _buckets.Length); int newEntryIdx = _nextFreeEntry; _entries[newEntryIdx]._key = key; _entries[newEntryIdx]._value = value; _entries[newEntryIdx]._hashCode = hashCode; _entries[newEntryIdx]._next = _buckets[bucket]; _nextFreeEntry++; // The line that atomically adds the new key/value pair. If the thread is killed before this line executes but after // we've incremented _nextFreeEntry, this entry is harmlessly leaked until the next resize. Volatile.Write(ref _buckets[bucket], newEntryIdx); VerifyUnifierConsistency(); } public bool HasCapacity { get { Debug.Assert(_owner._lock.IsAcquired); return _nextFreeEntry != _entries.Length; } } public void Resize() { Debug.Assert(_owner._lock.IsAcquired); int newSize = HashHelpers.GetPrime(_buckets.Length * 2); #if DEBUG newSize = _buckets.Length + 3; #endif if (newSize <= _nextFreeEntry) throw new OutOfMemoryException(); Entry[] newEntries = new Entry[newSize]; int[] newBuckets = new int[newSize]; for (int i = 0; i < newSize; i++) newBuckets[i] = -1; // Note that we walk the bucket chains rather than iterating over _entries. This is because we allow for the possibility // of abandoned entries (with undefined contents) if a thread is killed between allocating an entry and linking it onto the // bucket chain. int newNextFreeEntry = 0; for (int bucket = 0; bucket < _buckets.Length; bucket++) { for (int entry = _buckets[bucket]; entry != -1; entry = _entries[entry]._next) { newEntries[newNextFreeEntry]._key = _entries[entry]._key; newEntries[newNextFreeEntry]._value = _entries[entry]._value; newEntries[newNextFreeEntry]._hashCode = _entries[entry]._hashCode; int newBucket = ComputeBucket(newEntries[newNextFreeEntry]._hashCode, newSize); newEntries[newNextFreeEntry]._next = newBuckets[newBucket]; newBuckets[newBucket] = newNextFreeEntry; newNextFreeEntry++; } } // The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if // a thread died between the time between we allocated the entry and the time we link it into the bucket stack. Debug.Assert(newNextFreeEntry <= _nextFreeEntry); // The line that atomically installs the resize. If this thread is killed before this point, // the table remains full and the next guy attempting an add will have to redo the resize. _owner._container = new Container(_owner, newBuckets, newEntries, newNextFreeEntry); _owner._container.VerifyUnifierConsistency(); } private static int ComputeBucket(int hashCode, int numBuckets) { int bucket = (hashCode & 0x7fffffff) % numBuckets; return bucket; } [Conditional("DEBUG")] public void VerifyUnifierConsistency() { #if DEBUG // There's a point at which this check becomes gluttonous, even by checked build standards... if (_nextFreeEntry >= 5000 && (0 != (_nextFreeEntry % 100))) return; Debug.Assert(_owner._lock.IsAcquired); Debug.Assert(_nextFreeEntry >= 0 && _nextFreeEntry <= _entries.Length); int numEntriesEncountered = 0; for (int bucket = 0; bucket < _buckets.Length; bucket++) { int walk1 = _buckets[bucket]; int walk2 = _buckets[bucket]; // walk2 advances two elements at a time - if walk1 ever meets walk2, we've detected a cycle. while (walk1 != -1) { numEntriesEncountered++; Debug.Assert(walk1 >= 0 && walk1 < _nextFreeEntry); Debug.Assert(walk2 >= -1 && walk2 < _nextFreeEntry); Debug.Assert(_entries[walk1]._key != null); int hashCode = _entries[walk1]._key.GetHashCode(); Debug.Assert(hashCode == _entries[walk1]._hashCode); int storedBucket = ComputeBucket(_entries[walk1]._hashCode, _buckets.Length); Debug.Assert(storedBucket == bucket); walk1 = _entries[walk1]._next; if (walk2 != -1) walk2 = _entries[walk2]._next; if (walk2 != -1) walk2 = _entries[walk2]._next; if (walk1 == walk2 && walk2 != -1) Debug.Assert(false, "Bucket " + bucket + " has a cycle in its linked list."); } } // The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if // a thread died between the time between we allocated the entry and the time we link it into the bucket stack. Debug.Assert(numEntriesEncountered <= _nextFreeEntry); #endif //DEBUG } private readonly int[] _buckets; private readonly Entry[] _entries; private int _nextFreeEntry; private readonly ConcurrentUnifier<K, V> _owner; private const int _initialCapacity = 5; } private struct Entry { public K _key; public V _value; public int _hashCode; public int _next; } } }
using System.Globalization; namespace EstimatorX.Shared.Extensions; /// <summary> /// Converts a string data type to another base data type using a safe conversion method. /// </summary> public static class StringConvert { /// <summary> /// Converts the specified string representation of a logical value to its Boolean equivalent. /// </summary> /// <param name="value">A string that contains the value of either <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/>.</param> /// <returns> /// true if <paramref name="value"/> equals <see cref="F:System.Boolean.TrueString"/>, or false if <paramref name="value"/> equals <see cref="F:System.Boolean.FalseString"/> or null. /// </returns> public static bool? ToBoolean(this string value) { if (value == null) return null; if (bool.TryParse(value, out var result)) return result; string v = value.Trim(); if (string.Equals(v, "t", StringComparison.OrdinalIgnoreCase) || string.Equals(v, "true", StringComparison.OrdinalIgnoreCase) || string.Equals(v, "y", StringComparison.OrdinalIgnoreCase) || string.Equals(v, "yes", StringComparison.OrdinalIgnoreCase) || string.Equals(v, "1", StringComparison.OrdinalIgnoreCase) || string.Equals(v, "x", StringComparison.OrdinalIgnoreCase) || string.Equals(v, "on", StringComparison.OrdinalIgnoreCase)) return true; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 8-bit unsigned integer. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <returns> /// An 8-bit unsigned integer that is equivalent to <paramref name="value"/>, or zero if <paramref name="value"/> is null. /// </returns> public static byte? ToByte(this string value) { if (value == null) return null; if (byte.TryParse(value, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 8-bit unsigned integer, using specified culture-specific formatting information. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <returns> /// An 8-bit unsigned integer that is equivalent to <paramref name="value"/>, or zero if <paramref name="value"/> is null. /// </returns> public static byte? ToByte(this string value, IFormatProvider provider) { if (value == null) return null; if (byte.TryParse(value, NumberStyles.Integer, provider, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a date and time to an equivalent date and time value. /// </summary> /// <param name="value">The string representation of a date and time.</param> /// <returns> /// The date and time equivalent of the value of <paramref name="value"/>, or the date and time equivalent of <see cref="F:System.DateTime.MinValue"/> if <paramref name="value"/> is null. /// </returns> public static DateTime? ToDateTime(this string value) { if (value == null) return null; if (DateTime.TryParse(value, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent date and time, using the specified culture-specific formatting information. /// </summary> /// <param name="value">A string that contains a date and time to convert.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <returns> /// The date and time equivalent of the value of <paramref name="value"/>, or the date and time equivalent of <see cref="F:System.DateTime.MinValue"/> if <paramref name="value"/> is null. /// </returns> public static DateTime? ToDateTime(this string value, IFormatProvider provider) { if (value == null) return null; if (DateTime.TryParse(value, provider, DateTimeStyles.None, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent decimal number. /// </summary> /// <param name="value">A string that contains a number to convert.</param> /// <returns> /// A decimal number that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static decimal? ToDecimal(this string value) { if (value == null) return null; if (decimal.TryParse(value, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent decimal number, using the specified culture-specific formatting information. /// </summary> /// <param name="value">A string that contains a number to convert.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <returns> /// A decimal number that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static decimal? ToDecimal(this string value, IFormatProvider provider) { if (value == null) return null; if (decimal.TryParse(value, NumberStyles.Number, provider, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent double-precision floating-point number. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <returns> /// A double-precision floating-point number that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static double? ToDouble(this string value) { if (value == null) return null; if (double.TryParse(value, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent double-precision floating-point number, using the specified culture-specific formatting information. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <returns> /// A double-precision floating-point number that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static double? ToDouble(this string value, IFormatProvider provider) { if (value == null) return null; if (double.TryParse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 16-bit signed integer. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <returns> /// A 16-bit signed integer that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static short? ToInt16(this string value) { if (value == null) return null; if (short.TryParse(value, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 16-bit signed integer, using the specified culture-specific formatting information. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <returns> /// A 16-bit signed integer that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static short? ToInt16(this string value, IFormatProvider provider) { if (value == null) return null; if (short.TryParse(value, NumberStyles.Integer, provider, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 32-bit signed integer. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <returns> /// A 32-bit signed integer that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static int? ToInt32(this string value) { if (value == null) return null; if (int.TryParse(value, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 32-bit signed integer, using the specified culture-specific formatting information. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <returns> /// A 32-bit signed integer that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static int? ToInt32(this string value, IFormatProvider provider) { if (value == null) return null; if (int.TryParse(value, NumberStyles.Integer, provider, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 64-bit signed integer. /// </summary> /// <param name="value">A string that contains a number to convert.</param> /// <returns> /// A 64-bit signed integer that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static long? ToInt64(this string value) { if (value == null) return null; if (long.TryParse(value, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 64-bit signed integer, using the specified culture-specific formatting information. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <returns> /// A 64-bit signed integer that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static long? ToInt64(this string value, IFormatProvider provider) { if (value == null) return null; if (long.TryParse(value, NumberStyles.Integer, provider, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent single-precision floating-point number. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <returns> /// A single-precision floating-point number that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static float? ToSingle(this string value) { if (value == null) return null; if (float.TryParse(value, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent single-precision floating-point number, using the specified culture-specific formatting information. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <returns> /// A single-precision floating-point number that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static float? ToSingle(this string value, IFormatProvider provider) { if (value == null) return null; if (float.TryParse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 16-bit unsigned integer. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <returns> /// A 16-bit unsigned integer that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static ushort? ToUInt16(this string value) { if (value == null) return null; if (ushort.TryParse(value, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 16-bit unsigned integer, using the specified culture-specific formatting information. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <returns> /// A 16-bit unsigned integer that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static ushort? ToUInt16(this string value, IFormatProvider provider) { if (value == null) return null; if (ushort.TryParse(value, NumberStyles.Integer, provider, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 32-bit unsigned integer. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <returns> /// A 32-bit unsigned integer that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static uint? ToUInt32(this string value) { if (value == null) return null; if (uint.TryParse(value, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 32-bit unsigned integer, using the specified culture-specific formatting information. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <returns> /// A 32-bit unsigned integer that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static uint? ToUInt32(this string value, IFormatProvider provider) { if (value == null) return null; if (uint.TryParse(value, NumberStyles.Integer, provider, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 64-bit unsigned integer. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <returns> /// A 64-bit signed integer that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static ulong? ToUInt64(this string value) { if (value == null) return null; if (ulong.TryParse(value, out var result)) return result; return null; } /// <summary> /// Converts the specified string representation of a number to an equivalent 64-bit unsigned integer, using the specified culture-specific formatting information. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <returns> /// A 64-bit unsigned integer that is equivalent to the number in <paramref name="value"/>, or 0 (zero) if <paramref name="value"/> is null. /// </returns> public static ulong? ToUInt64(this string value, IFormatProvider provider) { if (value == null) return null; if (ulong.TryParse(value, NumberStyles.Integer, provider, out var result)) return result; return null; } /// <summary> /// Converts the specified string to an equivalent <see cref="TimeSpan"/> value. /// </summary> /// <param name="value">The string representation of a <see cref="TimeSpan"/>.</param> /// <returns> /// The <see cref="TimeSpan"/> equivalent of the <paramref name="value"/>, or <see cref="F:System.TimeSpan.Zero"/> if <paramref name="value"/> is null. /// </returns> public static TimeSpan? ToTimeSpan(this string value) { if (value == null) return null; if (TimeSpan.TryParse(value, out var result)) return result; return null; } /// <summary> /// Converts the specified string to an equivalent <see cref="Guid"/> value. /// </summary> /// <param name="value">The string representation of a <see cref="Guid"/>.</param> /// <returns> /// The <see cref="Guid"/> equivalent of the <paramref name="value"/>, or <see cref="F:System.Guid.Empty"/> if <paramref name="value"/> is null. /// </returns> public static Guid? ToGuid(this string value) { if (value == null) return null; if (Guid.TryParse(value, out var result)) return result; return null; } /// <summary> /// Try to convert the specified string to the specified type. /// </summary> /// <param name="input">The input string to convert.</param> /// <param name="value">The converted value.</param> /// <returns><c>true</c> if the value is converted; otherwise <c>false</c></returns> public static bool TryConvert<T>(this string input, out T value) { var type = typeof(T); var result = TryConvert(input, type, out var objectType); value = result ? (T)objectType : default(T); return result; } /// <summary> /// Try to convert the specified string to the specified type. /// </summary> /// <param name="input">The input string to convert.</param> /// <param name="type">The type to convert to.</param> /// <param name="value">The converted value.</param> /// <returns><c>true</c> if the value is converted; otherwise <c>false</c></returns> public static bool TryConvert(this string input, Type type, out object value) { // first try string if (type == typeof(string)) { value = input; return true; } // check nullable if (input == null && type.IsNullable()) { value = null; return true; } Type underlyingType = type.GetUnderlyingType(); // convert by type if (underlyingType == typeof(bool)) { value = input.ToBoolean(); return value != null; } if (underlyingType == typeof(byte)) { value = input.ToByte(); return value != null; } if (underlyingType == typeof(DateTime)) { value = input.ToDateTime(); return value != null; } if (underlyingType == typeof(decimal)) { value = input.ToDecimal(); return value != null; } if (underlyingType == typeof(double)) { value = input.ToDouble(); return value != null; } if (underlyingType == typeof(short)) { value = input.ToInt16(); return value != null; } if (underlyingType == typeof(int)) { value = input.ToInt32(); return value != null; } if (underlyingType == typeof(long)) { value = input.ToInt64(); return value != null; } if (underlyingType == typeof(float)) { value = input.ToSingle(); return value != null; } if (underlyingType == typeof(ushort)) { value = input.ToUInt16(); return value != null; } if (underlyingType == typeof(uint)) { value = input.ToUInt32(); return value != null; } if (underlyingType == typeof(ulong)) { value = input.ToUInt64(); return value != null; } if (underlyingType == typeof(TimeSpan)) { value = input.ToTimeSpan(); return value != null; } if (underlyingType == typeof(Guid)) { value = input.ToGuid(); return value != null; } value = null; return false; } }
// // HPanedThin.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Pinta.Docking.Gui; using System.Collections.Generic; using Pinta.Docking; namespace MonoDevelop.Components { class HPanedThin: Gtk.HPaned { static HashSet<int> stylesParsed = new HashSet<int> (); CustomPanedHandle handle; public HPanedThin () { GtkWorkarounds.FixContainerLeak (this); handle = new CustomPanedHandle (this); handle.Parent = this; } public int GrabAreaSize { get { return handle.GrabAreaSize; } set { handle.GrabAreaSize = value; QueueResize (); } } public Gtk.Widget HandleWidget { get { return handle.HandleWidget; } set { handle.HandleWidget = value; } } internal static void InitStyle (Gtk.Paned paned, int size) { string id = "MonoDevelop.ThinPanedHandle.s" + size; if (stylesParsed.Add (size)) { Gtk.Rc.ParseString ("style \"" + id + "\" {\n GtkPaned::handle-size = " + size + "\n }\n"); Gtk.Rc.ParseString ("widget \"*." + id + "\" style \"" + id + "\"\n"); } paned.Name = id; } protected override void ForAll (bool include_internals, Gtk.Callback callback) { base.ForAll (include_internals, callback); if (handle != null) callback (handle); } protected override bool OnExposeEvent (Gdk.EventExpose evnt) { base.OnExposeEvent (evnt); if (Child1 != null && Child1.Visible && Child2 != null && Child2.Visible) { var gc = new Gdk.GC (evnt.Window); gc.RgbFgColor = Styles.ThinSplitterColor; var x = Child1.Allocation.X + Child1.Allocation.Width; evnt.Window.DrawLine (gc, x, Allocation.Y, x, Allocation.Y + Allocation.Height); gc.Dispose (); } return true; } } class CustomPanedHandle: Gtk.EventBox { static Gdk.Cursor resizeCursorW = new Gdk.Cursor (Gdk.CursorType.SbHDoubleArrow); static Gdk.Cursor resizeCursorH = new Gdk.Cursor (Gdk.CursorType.SbVDoubleArrow); internal const int HandleGrabWidth = 4; Gtk.Paned parent; bool horizontal; bool dragging; int initialPos; int initialPanedPos; public CustomPanedHandle (Gtk.Paned parent) { this.parent = parent; this.horizontal = parent is HPanedThin; GrabAreaSize = HandleGrabWidth; Events |= Gdk.EventMask.EnterNotifyMask | Gdk.EventMask.LeaveNotifyMask | Gdk.EventMask.PointerMotionMask | Gdk.EventMask.ButtonPressMask | Gdk.EventMask.ButtonReleaseMask; parent.SizeRequested += delegate { SizeRequest (); }; parent.SizeAllocated += HandleSizeAllocated; HandleWidget = null; } void HandleSizeAllocated (object o, Gtk.SizeAllocatedArgs args) { if (parent.Child1 != null && parent.Child1.Visible && parent.Child2 != null && parent.Child2.Visible) { Show (); int centerSize = Child == null ? GrabAreaSize / 2 : 0; if (horizontal) SizeAllocate (new Gdk.Rectangle (parent.Child1.Allocation.X + parent.Child1.Allocation.Width - centerSize, args.Allocation.Y, GrabAreaSize, args.Allocation.Height)); else SizeAllocate (new Gdk.Rectangle (args.Allocation.X, parent.Child1.Allocation.Y + parent.Child1.Allocation.Height - centerSize, args.Allocation.Width, GrabAreaSize)); } else Hide (); } public int GrabAreaSize { get { if (horizontal) return SizeRequest ().Width; else return SizeRequest ().Height; } set { if (horizontal) WidthRequest = value; else HeightRequest = value; } } public Gtk.Widget HandleWidget { get { return Child; } set { if (Child != null) { Remove (Child); } if (value != null) { Add (value); value.Show (); VisibleWindow = true; WidthRequest = HeightRequest = -1; HPanedThin.InitStyle (parent, GrabAreaSize); } else { VisibleWindow = false; if (horizontal) WidthRequest = 1; else HeightRequest = 1; HPanedThin.InitStyle (parent, 1); } } } protected override bool OnEnterNotifyEvent (Gdk.EventCrossing evnt) { if (horizontal) GdkWindow.Cursor = resizeCursorW; else GdkWindow.Cursor = resizeCursorH; return base.OnEnterNotifyEvent (evnt); } protected override bool OnLeaveNotifyEvent (Gdk.EventCrossing evnt) { GdkWindow.Cursor = null; return base.OnLeaveNotifyEvent (evnt); } protected override bool OnButtonPressEvent (Gdk.EventButton evnt) { if (horizontal) initialPos = (int) evnt.XRoot; else initialPos = (int) evnt.YRoot; initialPanedPos = parent.Position; dragging = true; return true; } protected override bool OnButtonReleaseEvent (Gdk.EventButton evnt) { dragging = false; return true; } protected override bool OnMotionNotifyEvent (Gdk.EventMotion evnt) { if (dragging) { if (horizontal) { int newpos = initialPanedPos + ((int) evnt.XRoot - initialPos); parent.Position = newpos >= 10 ? newpos : 10; } else { int newpos = initialPanedPos + ((int) evnt.YRoot - initialPos); parent.Position = newpos >= 10 ? newpos : 10; } } return base.OnMotionNotifyEvent (evnt); } } }
// 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 Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.CSharp.Debugging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging { public class NameResolverTests { private void Test(string text, string searchText, params string[] expectedNames) { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(text)) { var nameResolver = new BreakpointResolver(workspace.CurrentSolution, searchText); var results = nameResolver.DoAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); Assert.Equal(expectedNames, results.Select(r => r.LocationNameOpt)); } } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestCSharpLanguageDebugInfoCreateNameResolver() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(" ")) { var debugInfo = new CSharpBreakpointResolutionService(); var results = debugInfo.ResolveBreakpointsAsync(workspace.CurrentSolution, "foo", CancellationToken.None).WaitAndGetResult(CancellationToken.None); Assert.Equal(0, results.Count()); } } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestSimpleNameInClass() { var text = @"class C { void Foo() { } }"; Test(text, "Foo", "C.Foo()"); Test(text, "foo"); Test(text, "C.Foo", "C.Foo()"); Test(text, "N.C.Foo"); Test(text, "Foo<T>"); Test(text, "C<T>.Foo"); Test(text, "Foo()", "C.Foo()"); Test(text, "Foo(int i)"); Test(text, "Foo(int)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestSimpleNameInNamespace() { var text = @" namespace N { class C { void Foo() { } } }"; Test(text, "Foo", "N.C.Foo()"); Test(text, "foo"); Test(text, "C.Foo", "N.C.Foo()"); Test(text, "N.C.Foo", "N.C.Foo()"); Test(text, "Foo<T>"); Test(text, "C<T>.Foo"); Test(text, "Foo()", "N.C.Foo()"); Test(text, "C.Foo()", "N.C.Foo()"); Test(text, "N.C.Foo()", "N.C.Foo()"); Test(text, "Foo(int i)"); Test(text, "Foo(int)"); Test(text, "Foo(a)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestSimpleNameInGenericClassNamespace() { var text = @" namespace N { class C<T> { void Foo() { } } }"; Test(text, "Foo", "N.C<T>.Foo()"); Test(text, "foo"); Test(text, "C.Foo", "N.C<T>.Foo()"); Test(text, "N.C.Foo", "N.C<T>.Foo()"); Test(text, "Foo<T>"); Test(text, "C<T>.Foo", "N.C<T>.Foo()"); Test(text, "C<T>.Foo()", "N.C<T>.Foo()"); Test(text, "Foo()", "N.C<T>.Foo()"); Test(text, "C.Foo()", "N.C<T>.Foo()"); Test(text, "N.C.Foo()", "N.C<T>.Foo()"); Test(text, "Foo(int i)"); Test(text, "Foo(int)"); Test(text, "Foo(a)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestGenericNameInClassNamespace() { var text = @" namespace N { class C { void Foo<T>() { } } }"; Test(text, "Foo", "N.C.Foo<T>()"); Test(text, "foo"); Test(text, "C.Foo", "N.C.Foo<T>()"); Test(text, "N.C.Foo", "N.C.Foo<T>()"); Test(text, "Foo<T>", "N.C.Foo<T>()"); Test(text, "Foo<X>", "N.C.Foo<T>()"); Test(text, "Foo<T,X>"); Test(text, "C<T>.Foo"); Test(text, "C<T>.Foo()"); Test(text, "Foo()", "N.C.Foo<T>()"); Test(text, "C.Foo()", "N.C.Foo<T>()"); Test(text, "N.C.Foo()", "N.C.Foo<T>()"); Test(text, "Foo(int i)"); Test(text, "Foo(int)"); Test(text, "Foo(a)"); Test(text, "Foo<T>(int i)"); Test(text, "Foo<T>(int)"); Test(text, "Foo<T>(a)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestOverloadsInSingleClass() { var text = @"class C { void Foo() { } void Foo(int i) { } }"; Test(text, "Foo", "C.Foo()", "C.Foo(int)"); Test(text, "foo"); Test(text, "C.Foo", "C.Foo()", "C.Foo(int)"); Test(text, "N.C.Foo"); Test(text, "Foo<T>"); Test(text, "C<T>.Foo"); Test(text, "Foo()", "C.Foo()"); Test(text, "Foo(int i)", "C.Foo(int)"); Test(text, "Foo(int)", "C.Foo(int)"); Test(text, "Foo(i)", "C.Foo(int)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestMethodsInMultipleClasses() { var text = @"namespace N { class C { void Foo() { } } } namespace N1 { class C { void Foo(int i) { } } }"; Test(text, "Foo", "N1.C.Foo(int)", "N.C.Foo()"); Test(text, "foo"); Test(text, "C.Foo", "N1.C.Foo(int)", "N.C.Foo()"); Test(text, "N.C.Foo", "N.C.Foo()"); Test(text, "N1.C.Foo", "N1.C.Foo(int)"); Test(text, "Foo<T>"); Test(text, "C<T>.Foo"); Test(text, "Foo()", "N.C.Foo()"); Test(text, "Foo(int i)", "N1.C.Foo(int)"); Test(text, "Foo(int)", "N1.C.Foo(int)"); Test(text, "Foo(i)", "N1.C.Foo(int)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestMethodsWithDifferentArityInMultipleClasses() { var text = @"namespace N { class C { void Foo() { } } } namespace N1 { class C { void Foo<T>(int i) { } } }"; Test(text, "Foo", "N1.C.Foo<T>(int)", "N.C.Foo()"); Test(text, "foo"); Test(text, "C.Foo", "N1.C.Foo<T>(int)", "N.C.Foo()"); Test(text, "N.C.Foo", "N.C.Foo()"); Test(text, "N1.C.Foo", "N1.C.Foo<T>(int)"); Test(text, "Foo<T>", "N1.C.Foo<T>(int)"); Test(text, "C<T>.Foo"); Test(text, "Foo()", "N.C.Foo()"); Test(text, "Foo<T>()"); Test(text, "Foo(int i)", "N1.C.Foo<T>(int)"); Test(text, "Foo(int)", "N1.C.Foo<T>(int)"); Test(text, "Foo(i)", "N1.C.Foo<T>(int)"); Test(text, "Foo<T>(int i)", "N1.C.Foo<T>(int)"); Test(text, "Foo<T>(int)", "N1.C.Foo<T>(int)"); Test(text, "Foo<T>(i)", "N1.C.Foo<T>(int)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestOverloadsWithMultipleParametersInSingleClass() { var text = @"class C { void Foo(int a) { } void Foo(int a, string b = ""bb"") { } void Foo(__arglist) { } }"; Test(text, "Foo", "C.Foo(int)", "C.Foo(int, [string])", "C.Foo(__arglist)"); Test(text, "foo"); Test(text, "C.Foo", "C.Foo(int)", "C.Foo(int, [string])", "C.Foo(__arglist)"); Test(text, "N.C.Foo"); Test(text, "Foo<T>"); Test(text, "C<T>.Foo"); Test(text, "Foo()", "C.Foo(__arglist)"); Test(text, "Foo(int i)", "C.Foo(int)"); Test(text, "Foo(int)", "C.Foo(int)"); Test(text, "Foo(int x = 42)", "C.Foo(int)"); Test(text, "Foo(i)", "C.Foo(int)"); Test(text, "Foo(int i, int b)", "C.Foo(int, [string])"); Test(text, "Foo(int, bool)", "C.Foo(int, [string])"); Test(text, "Foo(i, s)", "C.Foo(int, [string])"); Test(text, "Foo(,)", "C.Foo(int, [string])"); Test(text, "Foo(int x = 42,)", "C.Foo(int, [string])"); Test(text, "Foo(int x = 42, y = 42)", "C.Foo(int, [string])"); Test(text, "Foo([attr] x = 42, y = 42)", "C.Foo(int, [string])"); Test(text, "Foo(int i, int b, char c)"); Test(text, "Foo(int, bool, char)"); Test(text, "Foo(i, s, c)"); Test(text, "Foo(__arglist)", "C.Foo(int)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void AccessorTests() { var text = @"class C { int Property1 { get { return 42; } } int Property2 { set { } } int Property3 { get; set;} }"; Test(text, "Property1", "C.Property1"); Test(text, "Property2", "C.Property2"); Test(text, "Property3", "C.Property3"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void NegativeTests() { var text = @"using System.Runtime.CompilerServices; abstract class C { public abstract void AbstractMethod(int a); int Field; delegate void Delegate(); event Delegate Event; [IndexerName(""ABCD"")] int this[int i] { get { return i; } } void Foo() { } void Foo(int x = 1, int y = 2) { } ~C() { } }"; Test(text, "AbstractMethod"); Test(text, "Field"); Test(text, "Delegate"); Test(text, "Event"); Test(text, "this"); Test(text, "C.this[int]"); Test(text, "C.get_Item"); Test(text, "C.get_Item(i)"); Test(text, "C[i]"); Test(text, "ABCD"); Test(text, "C.ABCD(int)"); Test(text, "42"); Test(text, "Foo", "C.Foo()", "C.Foo([int], [int])"); // just making sure it would normally resolve before trying bad syntax Test(text, "Foo Foo"); Test(text, "Foo()asdf"); Test(text, "Foo(),"); Test(text, "Foo(),f"); Test(text, "Foo().Foo"); Test(text, "Foo("); Test(text, "(Foo"); Test(text, "Foo)"); Test(text, "(Foo)"); Test(text, "Foo(x = 42, y = 42)", "C.Foo([int], [int])"); // just making sure it would normally resolve before trying bad syntax Test(text, "int x = 42"); Test(text, "Foo(int x = 42, y = 42"); Test(text, "C"); Test(text, "C.C"); Test(text, "~"); Test(text, "~C"); Test(text, "C.~C()"); Test(text, ""); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestInstanceConstructors() { var text = @"class C { public C() { } } class G<T> { public G() { } ~G() { } }"; Test(text, "C", "C.C()"); Test(text, "C.C", "C.C()"); Test(text, "C.C()", "C.C()"); Test(text, "C()", "C.C()"); Test(text, "C<T>"); Test(text, "C<T>()"); Test(text, "C(int i)"); Test(text, "C(int)"); Test(text, "C(i)"); Test(text, "G", "G<T>.G()"); Test(text, "G()", "G<T>.G()"); Test(text, "G.G", "G<T>.G()"); Test(text, "G.G()", "G<T>.G()"); Test(text, "G<T>.G", "G<T>.G()"); Test(text, "G<t>.G()", "G<T>.G()"); Test(text, "G<T>"); Test(text, "G<T>()"); Test(text, "G.G<T>"); Test(text, ".ctor"); Test(text, ".ctor()"); Test(text, "C.ctor"); Test(text, "C.ctor()"); Test(text, "G.ctor"); Test(text, "G<T>.ctor()"); Test(text, "Finalize", "G<T>.~G()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestStaticConstructors() { var text = @"class C { static C() { } }"; Test(text, "C", "C.C()"); Test(text, "C.C", "C.C()"); Test(text, "C.C()", "C.C()"); Test(text, "C()", "C.C()"); Test(text, "C<T>"); Test(text, "C<T>()"); Test(text, "C(int i)"); Test(text, "C(int)"); Test(text, "C(i)"); Test(text, "C.cctor"); Test(text, "C.cctor()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestAllConstructors() { var text = @"class C { static C() { } public C(int i) { } }"; Test(text, "C", "C.C(int)", "C.C()"); Test(text, "C.C", "C.C(int)", "C.C()"); Test(text, "C.C()", "C.C()"); Test(text, "C()", "C.C()"); Test(text, "C<T>"); Test(text, "C<T>()"); Test(text, "C(int i)", "C.C(int)"); Test(text, "C(int)", "C.C(int)"); Test(text, "C(i)", "C.C(int)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestPartialMethods() { var text = @"partial class C { partial int M1(); partial void M2() { } partial void M2(); partial int M3(); partial int M3(int x) { return 0; } partial void M4() { } }"; Test(text, "M1"); Test(text, "C.M1"); Test(text, "M2", "C.M2()"); Test(text, "M3", "C.M3(int)"); Test(text, "M3()"); Test(text, "M3(y)", "C.M3(int)"); Test(text, "M4", "C.M4()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestLeadingAndTrailingText() { var text = @"class C { void Foo() { }; }"; Test(text, "Foo;", "C.Foo()"); Test(text, "Foo();", "C.Foo()"); Test(text, " Foo;", "C.Foo()"); Test(text, " Foo;;"); Test(text, " Foo; ;"); Test(text, "Foo(); ", "C.Foo()"); Test(text, " Foo ( ) ; ", "C.Foo()"); Test(text, "Foo(); // comment", "C.Foo()"); Test(text, "/*comment*/Foo(/* params */); /* comment", "C.Foo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestEscapedKeywords() { var text = @"struct @true { } class @foreach { void where(@true @this) { } void @false() { } }"; Test(text, "where", "@foreach.where(@true)"); Test(text, "@where", "@foreach.where(@true)"); Test(text, "@foreach.where", "@foreach.where(@true)"); Test(text, "foreach.where"); Test(text, "@foreach.where(true)"); Test(text, "@foreach.where(@if)", "@foreach.where(@true)"); Test(text, "false"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestAliasQualifiedNames() { var text = @"extern alias A class C { void Foo(D d) { } }"; Test(text, "A::Foo"); Test(text, "A::Foo(A::B)"); Test(text, "A::Foo(A::B)"); Test(text, "A::C.Foo"); Test(text, "C.Foo(A::Q)", "C.Foo(D)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestNestedTypesAndNamespaces() { var text = @"namespace N1 { class C { void Foo() { } } namespace N2 { class C { } } namespace N3 { class D { } } namespace N4 { class C { void Foo(double x) { } class D { void Foo() { } class E { void Foo() { } } } } } namespace N5 { } }"; Test(text, "Foo", "N1.N4.C.Foo(double)", "N1.N4.C.D.Foo()", "N1.N4.C.D.E.Foo()", "N1.C.Foo()"); Test(text, "C.Foo", "N1.N4.C.Foo(double)", "N1.C.Foo()"); Test(text, "D.Foo", "N1.N4.C.D.Foo()"); Test(text, "N1.N4.C.D.Foo", "N1.N4.C.D.Foo()"); Test(text, "N1.Foo"); Test(text, "N3.C.Foo"); Test(text, "N5.C.Foo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public void TestInterfaces() { var text = @"interface I1 { void Foo(); } class C1 : I1 { void I1.Foo() { } }"; Test(text, "Foo", "C1.Foo()"); Test(text, "I1.Foo"); Test(text, "C1.Foo", "C1.Foo()"); Test(text, "C1.I1.Moo"); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RDS.Model { /// <summary> /// Contains the result of a successful invocation of the following actions: /// /// <ul> <li> <a>CreateDBInstance</a> </li> <li> <a>DeleteDBInstance</a> </li> <li> <a>ModifyDBInstance</a> /// </li> </ul> /// <para> /// This data type is used as a response element in the <a>DescribeDBInstances</a> action. /// </para> /// </summary> public partial class DBInstance { private int? _allocatedStorage; private bool? _autoMinorVersionUpgrade; private string _availabilityZone; private int? _backupRetentionPeriod; private string _caCertificateIdentifier; private string _characterSetName; private string _dbClusterIdentifier; private string _dbInstanceClass; private string _dbInstanceIdentifier; private int? _dbInstancePort; private string _dbInstanceStatus; private string _dbiResourceId; private string _dbName; private List<DBParameterGroupStatus> _dbParameterGroups = new List<DBParameterGroupStatus>(); private List<DBSecurityGroupMembership> _dbSecurityGroups = new List<DBSecurityGroupMembership>(); private DBSubnetGroup _dbSubnetGroup; private Endpoint _endpoint; private string _engine; private string _engineVersion; private DateTime? _instanceCreateTime; private int? _iops; private string _kmsKeyId; private DateTime? _latestRestorableTime; private string _licenseModel; private string _masterUsername; private bool? _multiAZ; private List<OptionGroupMembership> _optionGroupMemberships = new List<OptionGroupMembership>(); private PendingModifiedValues _pendingModifiedValues; private string _preferredBackupWindow; private string _preferredMaintenanceWindow; private bool? _publiclyAccessible; private List<string> _readReplicaDBInstanceIdentifiers = new List<string>(); private string _readReplicaSourceDBInstanceIdentifier; private string _secondaryAvailabilityZone; private List<DBInstanceStatusInfo> _statusInfos = new List<DBInstanceStatusInfo>(); private bool? _storageEncrypted; private string _storageType; private string _tdeCredentialArn; private List<VpcSecurityGroupMembership> _vpcSecurityGroups = new List<VpcSecurityGroupMembership>(); /// <summary> /// Gets and sets the property AllocatedStorage. /// <para> /// Specifies the allocated storage size specified in gigabytes. /// </para> /// </summary> public int AllocatedStorage { get { return this._allocatedStorage.GetValueOrDefault(); } set { this._allocatedStorage = value; } } // Check to see if AllocatedStorage property is set internal bool IsSetAllocatedStorage() { return this._allocatedStorage.HasValue; } /// <summary> /// Gets and sets the property AutoMinorVersionUpgrade. /// <para> /// Indicates that minor version patches are applied automatically. /// </para> /// </summary> public bool AutoMinorVersionUpgrade { get { return this._autoMinorVersionUpgrade.GetValueOrDefault(); } set { this._autoMinorVersionUpgrade = value; } } // Check to see if AutoMinorVersionUpgrade property is set internal bool IsSetAutoMinorVersionUpgrade() { return this._autoMinorVersionUpgrade.HasValue; } /// <summary> /// Gets and sets the property AvailabilityZone. /// <para> /// Specifies the name of the Availability Zone the DB instance is located in. /// </para> /// </summary> public string AvailabilityZone { get { return this._availabilityZone; } set { this._availabilityZone = value; } } // Check to see if AvailabilityZone property is set internal bool IsSetAvailabilityZone() { return this._availabilityZone != null; } /// <summary> /// Gets and sets the property BackupRetentionPeriod. /// <para> /// Specifies the number of days for which automatic DB snapshots are retained. /// </para> /// </summary> public int BackupRetentionPeriod { get { return this._backupRetentionPeriod.GetValueOrDefault(); } set { this._backupRetentionPeriod = value; } } // Check to see if BackupRetentionPeriod property is set internal bool IsSetBackupRetentionPeriod() { return this._backupRetentionPeriod.HasValue; } /// <summary> /// Gets and sets the property CACertificateIdentifier. /// <para> /// The identifier of the CA certificate for this DB instance. /// </para> /// </summary> public string CACertificateIdentifier { get { return this._caCertificateIdentifier; } set { this._caCertificateIdentifier = value; } } // Check to see if CACertificateIdentifier property is set internal bool IsSetCACertificateIdentifier() { return this._caCertificateIdentifier != null; } /// <summary> /// Gets and sets the property CharacterSetName. /// <para> /// If present, specifies the name of the character set that this instance is associated /// with. /// </para> /// </summary> public string CharacterSetName { get { return this._characterSetName; } set { this._characterSetName = value; } } // Check to see if CharacterSetName property is set internal bool IsSetCharacterSetName() { return this._characterSetName != null; } /// <summary> /// Gets and sets the property DBClusterIdentifier. /// <para> /// If the DB instance is a member of a DB cluster, contains the name of the DB cluster /// that the DB instance is a member of. /// </para> /// </summary> public string DBClusterIdentifier { get { return this._dbClusterIdentifier; } set { this._dbClusterIdentifier = value; } } // Check to see if DBClusterIdentifier property is set internal bool IsSetDBClusterIdentifier() { return this._dbClusterIdentifier != null; } /// <summary> /// Gets and sets the property DBInstanceClass. /// <para> /// Contains the name of the compute and memory capacity class of the DB instance. /// </para> /// </summary> public string DBInstanceClass { get { return this._dbInstanceClass; } set { this._dbInstanceClass = value; } } // Check to see if DBInstanceClass property is set internal bool IsSetDBInstanceClass() { return this._dbInstanceClass != null; } /// <summary> /// Gets and sets the property DBInstanceIdentifier. /// <para> /// Contains a user-supplied database identifier. This identifier is the unique key that /// identifies a DB instance. /// </para> /// </summary> public string DBInstanceIdentifier { get { return this._dbInstanceIdentifier; } set { this._dbInstanceIdentifier = value; } } // Check to see if DBInstanceIdentifier property is set internal bool IsSetDBInstanceIdentifier() { return this._dbInstanceIdentifier != null; } /// <summary> /// Gets and sets the property DbInstancePort. /// <para> /// Specifies the port that the DB instance listens on. If the DB instance is part of /// a DB cluster, this can be a different port than the DB cluster port. /// </para> /// </summary> public int DbInstancePort { get { return this._dbInstancePort.GetValueOrDefault(); } set { this._dbInstancePort = value; } } // Check to see if DbInstancePort property is set internal bool IsSetDbInstancePort() { return this._dbInstancePort.HasValue; } /// <summary> /// Gets and sets the property DBInstanceStatus. /// <para> /// Specifies the current state of this database. /// </para> /// </summary> public string DBInstanceStatus { get { return this._dbInstanceStatus; } set { this._dbInstanceStatus = value; } } // Check to see if DBInstanceStatus property is set internal bool IsSetDBInstanceStatus() { return this._dbInstanceStatus != null; } /// <summary> /// Gets and sets the property DbiResourceId. /// <para> /// If <code>StorageEncrypted</code> is true, the region-unique, immutable identifier /// for the encrypted DB instance. This identifier is found in AWS CloudTrail log entries /// whenever the KMS key for the DB instance is accessed. /// </para> /// </summary> public string DbiResourceId { get { return this._dbiResourceId; } set { this._dbiResourceId = value; } } // Check to see if DbiResourceId property is set internal bool IsSetDbiResourceId() { return this._dbiResourceId != null; } /// <summary> /// Gets and sets the property DBName. /// <para> /// The meaning of this parameter differs according to the database engine you use. For /// example, this value returns either MySQL or PostgreSQL information when returning /// values from CreateDBInstanceReadReplica since Read Replicas are only supported for /// MySQL and PostgreSQL. /// </para> /// /// <para> /// <b>MySQL, SQL Server, PostgreSQL</b> /// </para> /// /// <para> /// Contains the name of the initial database of this instance that was provided at create /// time, if one was specified when the DB instance was created. This same name is returned /// for the life of the DB instance. /// </para> /// /// <para> /// Type: String /// </para> /// /// <para> /// <b>Oracle</b> /// </para> /// /// <para> /// Contains the Oracle System ID (SID) of the created DB instance. Not shown when the /// returned parameters do not apply to an Oracle DB instance. /// </para> /// </summary> public string DBName { get { return this._dbName; } set { this._dbName = value; } } // Check to see if DBName property is set internal bool IsSetDBName() { return this._dbName != null; } /// <summary> /// Gets and sets the property DBParameterGroups. /// <para> /// Provides the list of DB parameter groups applied to this DB instance. /// </para> /// </summary> public List<DBParameterGroupStatus> DBParameterGroups { get { return this._dbParameterGroups; } set { this._dbParameterGroups = value; } } // Check to see if DBParameterGroups property is set internal bool IsSetDBParameterGroups() { return this._dbParameterGroups != null && this._dbParameterGroups.Count > 0; } /// <summary> /// Gets and sets the property DBSecurityGroups. /// <para> /// Provides List of DB security group elements containing only <code>DBSecurityGroup.Name</code> /// and <code>DBSecurityGroup.Status</code> subelements. /// </para> /// </summary> public List<DBSecurityGroupMembership> DBSecurityGroups { get { return this._dbSecurityGroups; } set { this._dbSecurityGroups = value; } } // Check to see if DBSecurityGroups property is set internal bool IsSetDBSecurityGroups() { return this._dbSecurityGroups != null && this._dbSecurityGroups.Count > 0; } /// <summary> /// Gets and sets the property DBSubnetGroup. /// <para> /// Specifies information on the subnet group associated with the DB instance, including /// the name, description, and subnets in the subnet group. /// </para> /// </summary> public DBSubnetGroup DBSubnetGroup { get { return this._dbSubnetGroup; } set { this._dbSubnetGroup = value; } } // Check to see if DBSubnetGroup property is set internal bool IsSetDBSubnetGroup() { return this._dbSubnetGroup != null; } /// <summary> /// Gets and sets the property Endpoint. /// <para> /// Specifies the connection endpoint. /// </para> /// </summary> public Endpoint Endpoint { get { return this._endpoint; } set { this._endpoint = value; } } // Check to see if Endpoint property is set internal bool IsSetEndpoint() { return this._endpoint != null; } /// <summary> /// Gets and sets the property Engine. /// <para> /// Provides the name of the database engine to be used for this DB instance. /// </para> /// </summary> public string Engine { get { return this._engine; } set { this._engine = value; } } // Check to see if Engine property is set internal bool IsSetEngine() { return this._engine != null; } /// <summary> /// Gets and sets the property EngineVersion. /// <para> /// Indicates the database engine version. /// </para> /// </summary> public string EngineVersion { get { return this._engineVersion; } set { this._engineVersion = value; } } // Check to see if EngineVersion property is set internal bool IsSetEngineVersion() { return this._engineVersion != null; } /// <summary> /// Gets and sets the property InstanceCreateTime. /// <para> /// Provides the date and time the DB instance was created. /// </para> /// </summary> public DateTime InstanceCreateTime { get { return this._instanceCreateTime.GetValueOrDefault(); } set { this._instanceCreateTime = value; } } // Check to see if InstanceCreateTime property is set internal bool IsSetInstanceCreateTime() { return this._instanceCreateTime.HasValue; } /// <summary> /// Gets and sets the property Iops. /// <para> /// Specifies the Provisioned IOPS (I/O operations per second) value. /// </para> /// </summary> public int Iops { get { return this._iops.GetValueOrDefault(); } set { this._iops = value; } } // Check to see if Iops property is set internal bool IsSetIops() { return this._iops.HasValue; } /// <summary> /// Gets and sets the property KmsKeyId. /// <para> /// If <code>StorageEncrypted</code> is true, the KMS key identifier for the encrypted /// DB instance. /// </para> /// </summary> public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } // Check to see if KmsKeyId property is set internal bool IsSetKmsKeyId() { return this._kmsKeyId != null; } /// <summary> /// Gets and sets the property LatestRestorableTime. /// <para> /// Specifies the latest time to which a database can be restored with point-in-time /// restore. /// </para> /// </summary> public DateTime LatestRestorableTime { get { return this._latestRestorableTime.GetValueOrDefault(); } set { this._latestRestorableTime = value; } } // Check to see if LatestRestorableTime property is set internal bool IsSetLatestRestorableTime() { return this._latestRestorableTime.HasValue; } /// <summary> /// Gets and sets the property LicenseModel. /// <para> /// License model information for this DB instance. /// </para> /// </summary> public string LicenseModel { get { return this._licenseModel; } set { this._licenseModel = value; } } // Check to see if LicenseModel property is set internal bool IsSetLicenseModel() { return this._licenseModel != null; } /// <summary> /// Gets and sets the property MasterUsername. /// <para> /// Contains the master username for the DB instance. /// </para> /// </summary> public string MasterUsername { get { return this._masterUsername; } set { this._masterUsername = value; } } // Check to see if MasterUsername property is set internal bool IsSetMasterUsername() { return this._masterUsername != null; } /// <summary> /// Gets and sets the property MultiAZ. /// <para> /// Specifies if the DB instance is a Multi-AZ deployment. /// </para> /// </summary> public bool MultiAZ { get { return this._multiAZ.GetValueOrDefault(); } set { this._multiAZ = value; } } // Check to see if MultiAZ property is set internal bool IsSetMultiAZ() { return this._multiAZ.HasValue; } /// <summary> /// Gets and sets the property OptionGroupMemberships. /// <para> /// Provides the list of option group memberships for this DB instance. /// </para> /// </summary> public List<OptionGroupMembership> OptionGroupMemberships { get { return this._optionGroupMemberships; } set { this._optionGroupMemberships = value; } } // Check to see if OptionGroupMemberships property is set internal bool IsSetOptionGroupMemberships() { return this._optionGroupMemberships != null && this._optionGroupMemberships.Count > 0; } /// <summary> /// Gets and sets the property PendingModifiedValues. /// <para> /// Specifies that changes to the DB instance are pending. This element is only included /// when changes are pending. Specific changes are identified by subelements. /// </para> /// </summary> public PendingModifiedValues PendingModifiedValues { get { return this._pendingModifiedValues; } set { this._pendingModifiedValues = value; } } // Check to see if PendingModifiedValues property is set internal bool IsSetPendingModifiedValues() { return this._pendingModifiedValues != null; } /// <summary> /// Gets and sets the property PreferredBackupWindow. /// <para> /// Specifies the daily time range during which automated backups are created if automated /// backups are enabled, as determined by the <code>BackupRetentionPeriod</code>. /// </para> /// </summary> public string PreferredBackupWindow { get { return this._preferredBackupWindow; } set { this._preferredBackupWindow = value; } } // Check to see if PreferredBackupWindow property is set internal bool IsSetPreferredBackupWindow() { return this._preferredBackupWindow != null; } /// <summary> /// Gets and sets the property PreferredMaintenanceWindow. /// <para> /// Specifies the weekly time range during which system maintenance can occur, in Universal /// Coordinated Time (UTC). /// </para> /// </summary> public string PreferredMaintenanceWindow { get { return this._preferredMaintenanceWindow; } set { this._preferredMaintenanceWindow = value; } } // Check to see if PreferredMaintenanceWindow property is set internal bool IsSetPreferredMaintenanceWindow() { return this._preferredMaintenanceWindow != null; } /// <summary> /// Gets and sets the property PubliclyAccessible. /// <para> /// Specifies the accessibility options for the DB instance. A value of true specifies /// an Internet-facing instance with a publicly resolvable DNS name, which resolves to /// a public IP address. A value of false specifies an internal instance with a DNS name /// that resolves to a private IP address. /// </para> /// /// <para> /// Default: The default behavior varies depending on whether a VPC has been requested /// or not. The following list shows the default behavior in each case. /// </para> /// <ul> <li> <b>Default VPC:</b>true</li> <li> <b>VPC:</b>false</li> </ul> /// <para> /// If no DB subnet group has been specified as part of the request and the PubliclyAccessible /// value has not been set, the DB instance will be publicly accessible. If a specific /// DB subnet group has been specified as part of the request and the PubliclyAccessible /// value has not been set, the DB instance will be private. /// </para> /// </summary> public bool PubliclyAccessible { get { return this._publiclyAccessible.GetValueOrDefault(); } set { this._publiclyAccessible = value; } } // Check to see if PubliclyAccessible property is set internal bool IsSetPubliclyAccessible() { return this._publiclyAccessible.HasValue; } /// <summary> /// Gets and sets the property ReadReplicaDBInstanceIdentifiers. /// <para> /// Contains one or more identifiers of the Read Replicas associated with this DB instance. /// /// </para> /// </summary> public List<string> ReadReplicaDBInstanceIdentifiers { get { return this._readReplicaDBInstanceIdentifiers; } set { this._readReplicaDBInstanceIdentifiers = value; } } // Check to see if ReadReplicaDBInstanceIdentifiers property is set internal bool IsSetReadReplicaDBInstanceIdentifiers() { return this._readReplicaDBInstanceIdentifiers != null && this._readReplicaDBInstanceIdentifiers.Count > 0; } /// <summary> /// Gets and sets the property ReadReplicaSourceDBInstanceIdentifier. /// <para> /// Contains the identifier of the source DB instance if this DB instance is a Read Replica. /// /// </para> /// </summary> public string ReadReplicaSourceDBInstanceIdentifier { get { return this._readReplicaSourceDBInstanceIdentifier; } set { this._readReplicaSourceDBInstanceIdentifier = value; } } // Check to see if ReadReplicaSourceDBInstanceIdentifier property is set internal bool IsSetReadReplicaSourceDBInstanceIdentifier() { return this._readReplicaSourceDBInstanceIdentifier != null; } /// <summary> /// Gets and sets the property SecondaryAvailabilityZone. /// <para> /// If present, specifies the name of the secondary Availability Zone for a DB instance /// with multi-AZ support. /// </para> /// </summary> public string SecondaryAvailabilityZone { get { return this._secondaryAvailabilityZone; } set { this._secondaryAvailabilityZone = value; } } // Check to see if SecondaryAvailabilityZone property is set internal bool IsSetSecondaryAvailabilityZone() { return this._secondaryAvailabilityZone != null; } /// <summary> /// Gets and sets the property StatusInfos. /// <para> /// The status of a Read Replica. If the instance is not a Read Replica, this will be /// blank. /// </para> /// </summary> public List<DBInstanceStatusInfo> StatusInfos { get { return this._statusInfos; } set { this._statusInfos = value; } } // Check to see if StatusInfos property is set internal bool IsSetStatusInfos() { return this._statusInfos != null && this._statusInfos.Count > 0; } /// <summary> /// Gets and sets the property StorageEncrypted. /// <para> /// Specifies whether the DB instance is encrypted. /// </para> /// </summary> public bool StorageEncrypted { get { return this._storageEncrypted.GetValueOrDefault(); } set { this._storageEncrypted = value; } } // Check to see if StorageEncrypted property is set internal bool IsSetStorageEncrypted() { return this._storageEncrypted.HasValue; } /// <summary> /// Gets and sets the property StorageType. /// <para> /// Specifies the storage type associated with DB instance. /// </para> /// </summary> public string StorageType { get { return this._storageType; } set { this._storageType = value; } } // Check to see if StorageType property is set internal bool IsSetStorageType() { return this._storageType != null; } /// <summary> /// Gets and sets the property TdeCredentialArn. /// <para> /// The ARN from the Key Store with which the instance is associated for TDE encryption. /// /// </para> /// </summary> public string TdeCredentialArn { get { return this._tdeCredentialArn; } set { this._tdeCredentialArn = value; } } // Check to see if TdeCredentialArn property is set internal bool IsSetTdeCredentialArn() { return this._tdeCredentialArn != null; } /// <summary> /// Gets and sets the property VpcSecurityGroups. /// <para> /// Provides List of VPC security group elements that the DB instance belongs to. /// </para> /// </summary> public List<VpcSecurityGroupMembership> VpcSecurityGroups { get { return this._vpcSecurityGroups; } set { this._vpcSecurityGroups = value; } } // Check to see if VpcSecurityGroups property is set internal bool IsSetVpcSecurityGroups() { return this._vpcSecurityGroups != null && this._vpcSecurityGroups.Count > 0; } } }
namespace Microsoft.Protocols.TestSuites.MS_OFFICIALFILE { using System; using System.Web.Services.Protocols; using System.Xml; using System.Xml.Serialization; using Microsoft.Protocols.TestTools; /// <summary> /// MS-OFFICIALFILE protocol's adapter. /// </summary> public partial class MS_OFFICIALFILEAdapter : ManagedAdapterBase, IMS_OFFICIALFILEAdapter { #region variables /// <summary> /// Specify Enum Represent Result of Validation. /// </summary> private OfficialFileSoap officialfileService; #endregion variables /// <summary> /// Overrides IAdapter's Initialize(), to set testSite.DefaultProtocolDocShortName. /// </summary> /// <param name="testSite">Transfer ITestSite into adapter,Make adapter can use ITestSite's function.</param> public override void Initialize(ITestSite testSite) { base.Initialize(testSite); testSite.DefaultProtocolDocShortName = "MS-OFFICIALFILE"; // Get the name of common configuration file. string commonConfigFileName = Common.Common.GetConfigurationPropertyValue("CommonConfigurationFileName", this.Site); // Merge the common configuration. Common.Common.MergeGlobalConfig(commonConfigFileName, this.Site); // Merge the Should/May configuration. Common.Common.MergeSHOULDMAYConfig(this.Site); // Initialize the OfficialFileSoap. this.officialfileService = Common.Proxy.CreateProxy<OfficialFileSoap>(testSite, true, true); AdapterHelper.Initialize(testSite); // Set the transportType. TransportType transportType = Common.Common.GetConfigurationPropertyValue<TransportType>("TransportType", this.Site); // Case request URl include HTTPS prefix, use this function to avoid closing base connection. // Local client will accept all certificate after execute this function. if (transportType == TransportType.HTTPS) { AdapterHelper.AcceptAllCertificate(); } // Set the version of the SOAP protocol used to make the SOAP request to the web service this.officialfileService.SoapVersion = Common.Common.GetConfigurationPropertyValue<SoapProtocolVersion>("SoapVersion", this.Site); } /// <summary> /// Initialize the services of MS-OFFICIALFILE. /// </summary> /// <param name="paras">The TransportType object indicates which transport parameters are used.</param> public void IntializeService(InitialPara paras) { // Initialize the url this.officialfileService.Url = paras.Url; // Set the security credential for Web service client authentication. this.officialfileService.Credentials = AdapterHelper.ConfigureCredential(paras.UserName, paras.Password, paras.Domain); } /// <summary> /// This operation is used to determine the storage location for the submission based on the rules in the repository and a suggested save location chosen by a user. /// </summary> /// <param name="properties">The properties of the file.</param> /// <param name="contentTypeName">The file type.</param> /// <param name="originalSaveLocation">The suggested save location chosen by a user.</param> /// <returns>An implementation specific URL to the storage location and some results for the submission or SoapException thrown.</returns> public DocumentRoutingResult GetFinalRoutingDestinationFolderUrl(RecordsRepositoryProperty[] properties, string contentTypeName, string originalSaveLocation) { DocumentRoutingResult documentRoutingResult = this.officialfileService.GetFinalRoutingDestinationFolderUrl(properties, contentTypeName, originalSaveLocation); // As response is returned successfully, the transport related requirements can be captured. this.VerifyTransportRelatedRequirments(); this.VerifyGetFinalRoutingDestinationFolderUrl(); return documentRoutingResult; } /// <summary> /// This operation is used to retrieves data about the type, version of the repository and whether the repository is configured for routing. /// </summary> /// <returns>Data about the type, version of the repository and whether the repository is configured for routing or SoapException thrown.</returns> public ServerInfo GetServerInfo() { string serverInfo = this.officialfileService.GetServerInfo(); // As response is returned successfully, the transport related requirements can be captured. this.VerifyTransportRelatedRequirments(); // Verify GetServerInfo operation. ServerInfo serverInfoClass = this.VerifyAndParseGetServerInfo(serverInfo); return serverInfoClass; } /// <summary> /// This operation is used to submit a file and its associated properties to the repository. /// </summary> /// <param name="fileToSubmit">The contents of the file.</param> /// <param name="properties"> The properties of the file.</param> /// <param name="recordRouting">The file type.</param> /// <param name="sourceUrl">The source URL of the file.</param> /// <param name="userName">The name of the user submitting the file.</param> /// <returns>The data of SubmitFileResult or SoapException thrown.</returns> public SubmitFileResult SubmitFile( [XmlElementAttribute(DataType = "base64Binary")] byte[] fileToSubmit, [XmlArrayItemAttribute(IsNullable = false)] RecordsRepositoryProperty[] properties, string recordRouting, string sourceUrl, string userName) { string submitFileResult = this.officialfileService.SubmitFile( fileToSubmit, properties, recordRouting, sourceUrl, userName); // As response is returned successfully, the transport related requirements can be captured. this.VerifyTransportRelatedRequirments(); SubmitFileResult value = this.VerifyAndParseSubmitFile(submitFileResult); return value; } /// <summary> /// This operation is called to retrieve information about the legal holds in a repository. /// </summary> /// <returns>A list of legal holds.</returns> public HoldInfo[] GetHoldsInfo() { HoldInfo[] getHoldsInfoResult = this.officialfileService.GetHoldsInfo(); // As response is returned successfully, the transport related requirements can be captured this.VerifyTransportRelatedRequirments(); this.VerifyGetHoldsInfo(); return getHoldsInfoResult; } /// <summary> /// This method is used to retrieve the recording routing information. /// </summary> /// <param name="recordRouting">The file type.</param> /// <returns>Recording routing information.</returns> public string GetRecordingRouting(string recordRouting) { string routingInfor = this.officialfileService.GetRecordRouting(recordRouting); // Verify GetRecordingRouting operation. this.VerifyGetRoutingInfo(); return routingInfor; } /// <summary> /// This method is used to retrieve the recording routing collection information. /// </summary> /// <returns>Implementation-specific result data</returns> public string GetRecordRoutingCollection() { string recordingCollection = this.officialfileService.GetRecordRoutingCollection(); // Verify GetRecordingRoutingCollection operation. this.VerifyGetRoutingCollectionInfo(); return recordingCollection; } /// <summary> /// This method is used to parse the GetServerInfoResult from xml to class. /// </summary> /// <param name="serverInfo">A string indicates the serverInfo returned by the protocol server.</param> /// <returns>A serverInfo parsed from the response.</returns> private ServerInfo ParseGetServerInfoResult(string serverInfo) { ServerInfo info = new ServerInfo(); // Read string in SubmitFileResult response XmlDocument document = new XmlDocument(); document.LoadXml(serverInfo); XmlNodeList nodeList = null; XmlNode node = null; nodeList = document.GetElementsByTagName("ServerType"); if (nodeList != null && nodeList.Count == 1) { node = nodeList[0]; info.ServerType = node.InnerText; } nodeList = document.GetElementsByTagName("ServerVersion"); if (nodeList != null && nodeList.Count == 1) { node = nodeList[0]; info.ServerVersion = node.InnerText; } nodeList = document.GetElementsByTagName("RoutingWeb"); if (nodeList != null && nodeList.Count == 1) { node = nodeList[0]; info.RoutingWeb = node.InnerText; } return info; } /// <summary> /// This method is used to parse the SubmitFileResult from xml to class. /// </summary> /// <param name="response">The value response from server.</param> /// <returns>Enum value of SubmitFileResult.</returns> private SubmitFileResult ParseSubmitFileResult(string response) { SubmitFileResult result = new SubmitFileResult(); // Read string in SubmitFileResult response XmlDocument document = new XmlDocument(); document.LoadXml(response); XmlNodeList nodeList = null; XmlNode node = null; nodeList = document.GetElementsByTagName("ResultCode"); if (nodeList != null && nodeList.Count == 1) { node = nodeList[0]; switch (node.InnerText) { case "Success": result.ResultCode = SubmitFileResultCode.Success; break; case "MoreInformation": result.ResultCode = SubmitFileResultCode.MoreInformation; break; case "InvalidRouterConfiguration": result.ResultCode = SubmitFileResultCode.InvalidRouterConfiguration; break; case "InvalidArgument": result.ResultCode = SubmitFileResultCode.InvalidArgument; break; case "InvalidUser": result.ResultCode = SubmitFileResultCode.InvalidUser; break; case "NotFound": result.ResultCode = SubmitFileResultCode.NotFound; break; case "FileRejected": result.ResultCode = SubmitFileResultCode.FileRejected; break; case "UnknownError": result.ResultCode = SubmitFileResultCode.UnknownError; break; default: break; } } nodeList = document.GetElementsByTagName("CustomProcessingResult"); if (nodeList != null && nodeList.Count == 1) { node = nodeList[0]; result.CustomProcessingResult = new CustomProcessingResult(); switch (node.InnerText) { case "Success": result.CustomProcessingResult.HoldProcessingResult = HoldProcessingResult.Success; break; case "Failure": result.CustomProcessingResult.HoldProcessingResult = HoldProcessingResult.Failure; break; case "InDropOffZone": result.CustomProcessingResult.HoldProcessingResult = HoldProcessingResult.InDropOffZone; break; default: break; } } nodeList = document.GetElementsByTagName("ResultUrl"); if (nodeList != null && nodeList.Count == 1) { node = nodeList[0]; result.ResultUrl = node.InnerText; } nodeList = document.GetElementsByTagName("AdditionalInformation"); if (nodeList != null && nodeList.Count == 1) { node = nodeList[0]; result.AdditionalInformation = node.InnerText; } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics.Contracts; using System.ServiceModel.Channels; using Microsoft.Xml; namespace System.ServiceModel { public class NetTcpBinding : Binding { private OptionalReliableSession _reliableSession; // private BindingElements private TcpTransportBindingElement _transport; private BinaryMessageEncodingBindingElement _encoding; private TransactionFlowBindingElement _context; private ReliableSessionBindingElement _session; private long _maxBufferPoolSize; private NetTcpSecurity _security = new NetTcpSecurity(); public NetTcpBinding() { Initialize(); } public NetTcpBinding(SecurityMode securityMode) : this() { _security.Mode = securityMode; } public NetTcpBinding(SecurityMode securityMode, bool reliableSessionEnabled) : this(securityMode) { this.ReliableSession.Enabled = reliableSessionEnabled; } private NetTcpBinding(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding, TransactionFlowBindingElement context, ReliableSessionBindingElement session, NetTcpSecurity security) : this() { _security = security; this.ReliableSession.Enabled = session != null; InitializeFrom(transport, encoding, context, session); } private NetTcpBinding(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding, NetTcpSecurity security) : this() { _security = security; } [DefaultValue(ConnectionOrientedTransportDefaults.TransferMode)] public TransferMode TransferMode { get { return _transport.TransferMode; } set { _transport.TransferMode = value; } } [DefaultValue(ConnectionOrientedTransportDefaults.HostNameComparisonMode)] public HostNameComparisonMode HostNameComparisonMode { get { return _transport.HostNameComparisonMode; } set { _transport.HostNameComparisonMode = value; } } [DefaultValue(TransportDefaults.MaxBufferPoolSize)] public long MaxBufferPoolSize { get { return _maxBufferPoolSize; } set { _maxBufferPoolSize = value; } } [DefaultValue(TransportDefaults.MaxBufferSize)] public int MaxBufferSize { get { return _transport.MaxBufferSize; } set { _transport.MaxBufferSize = value; } } [DefaultValue(TransportDefaults.MaxReceivedMessageSize)] public long MaxReceivedMessageSize { get { return _transport.MaxReceivedMessageSize; } set { _transport.MaxReceivedMessageSize = value; } } [DefaultValue(TcpTransportDefaults.PortSharingEnabled)] public bool PortSharingEnabled { get { return _transport.PortSharingEnabled; } set { _transport.PortSharingEnabled = value; } } public XmlDictionaryReaderQuotas ReaderQuotas { get { return _encoding.ReaderQuotas; } set { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); value.CopyTo(_encoding.ReaderQuotas); } } public OptionalReliableSession ReliableSession { get { return _reliableSession; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } _reliableSession.CopySettings(value); } } public override string Scheme { get { return _transport.Scheme; } } public EnvelopeVersion EnvelopeVersion { get { return EnvelopeVersion.Soap12; } } public NetTcpSecurity Security { get { return _security; } set { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); _security = value; } } public bool TransactionFlow { get { return _context.Transactions; } set { _context.Transactions = value; } } public TransactionProtocol TransactionProtocol { get { return _context.TransactionProtocol; } set { _context.TransactionProtocol = value; } } private static TransactionFlowBindingElement GetDefaultTransactionFlowBindingElement() { return new TransactionFlowBindingElement(NetTcpDefaults.TransactionsEnabled); } private void Initialize() { _transport = new TcpTransportBindingElement(); _encoding = new BinaryMessageEncodingBindingElement(); _context = new TransactionFlowBindingElement(NetTcpDefaults.TransactionsEnabled); _session = new ReliableSessionBindingElement(); _reliableSession = new OptionalReliableSession(_session); // NetNative and CoreCLR initialize to what TransportBindingElement does in the desktop // This property is not available in shipped contracts _maxBufferPoolSize = TransportDefaults.MaxBufferPoolSize; } private void InitializeFrom(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding, TransactionFlowBindingElement context, ReliableSessionBindingElement session) { // TODO: Fx.Assert(transport != null, "Invalid (null) transport value."); // TODO: Fx.Assert(encoding != null, "Invalid (null) encoding value."); // TODO: Fx.Assert(context != null, "Invalid (null) context value."); // TODO: Fx.Assert(security != null, "Invalid (null) security value."); // transport this.HostNameComparisonMode = transport.HostNameComparisonMode; this.MaxBufferPoolSize = transport.MaxBufferPoolSize; this.MaxBufferSize = transport.MaxBufferSize; this.MaxReceivedMessageSize = transport.MaxReceivedMessageSize; this.PortSharingEnabled = transport.PortSharingEnabled; this.TransferMode = transport.TransferMode; // encoding this.ReaderQuotas = encoding.ReaderQuotas; // context this.TransactionFlow = context.Transactions; this.TransactionProtocol = context.TransactionProtocol; //session if (session != null) { // only set properties that have standard binding manifestations _session.InactivityTimeout = session.InactivityTimeout; _session.Ordered = session.Ordered; } } // check that properties of the HttpTransportBindingElement and // MessageEncodingBindingElement not exposed as properties on BasicHttpBinding // match default values of the binding elements private bool IsBindingElementsMatch(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding) { if (!_transport.IsMatch(transport)) return false; if (!_encoding.IsMatch(encoding)) return false; if (!_context.IsMatch(_context)) return false; if (_reliableSession.Enabled) { if (!_session.IsMatch(_session)) return false; } return true; } // check that properties of the HttpTransportBindingElement and // MessageEncodingBindingElement not exposed as properties on BasicHttpBinding // match default values of the binding elements private bool IsBindingElementsMatch(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding, TransactionFlowBindingElement context, ReliableSessionBindingElement session) { if (!_transport.IsMatch(transport)) return false; if (!_encoding.IsMatch(encoding)) return false; if (!_context.IsMatch(context)) return false; if (_reliableSession.Enabled) { if (!_session.IsMatch(session)) return false; } else if (session != null) return false; return true; } private void CheckSettings() { #if FEATURE_NETNATIVE // In .NET Native, some settings for the binding security are not supported; this check is not necessary for CoreCLR NetTcpSecurity security = this.Security; if (security == null) { return; } SecurityMode mode = security.Mode; if (mode == SecurityMode.None) { return; } else if (mode == SecurityMode.Message) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Mode", mode))); } // Message.ClientCredentialType = Certificate, IssuedToken or Windows are not supported. if (mode == SecurityMode.TransportWithMessageCredential) { MessageSecurityOverTcp message = security.Message; if (message != null) { MessageCredentialType mct = message.ClientCredentialType; if ((mct == MessageCredentialType.Certificate) || (mct == MessageCredentialType.IssuedToken) || (mct == MessageCredentialType.Windows)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Message.ClientCredentialType", mct))); } } } // Transport.ClientCredentialType = Certificate is not supported. Contract.Assert((mode == SecurityMode.Transport) || (mode == SecurityMode.TransportWithMessageCredential), "Unexpected SecurityMode value: " + mode); TcpTransportSecurity transport = security.Transport; if ((transport != null) && (transport.ClientCredentialType == TcpClientCredentialType.Certificate)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Transport.ClientCredentialType", transport.ClientCredentialType))); } #endif // FEATURE_NETNATIVE } public override BindingElementCollection CreateBindingElements() { this.CheckSettings(); // return collection of BindingElements BindingElementCollection bindingElements = new BindingElementCollection(); // order of BindingElements is important bindingElements.Add(_context); // add session if (_reliableSession.Enabled) bindingElements.Add(_session); // add security (*optional) SecurityBindingElement wsSecurity = CreateMessageSecurity(); if (wsSecurity != null) bindingElements.Add(wsSecurity); // add encoding bindingElements.Add(_encoding); // add transport security BindingElement transportSecurity = CreateTransportSecurity(); if (transportSecurity != null) { bindingElements.Add(transportSecurity); } // add transport (tcp) bindingElements.Add(_transport); return bindingElements.Clone(); } internal static bool TryCreate(BindingElementCollection elements, out Binding binding) { binding = null; if (elements.Count > 6) return false; // collect all binding elements TcpTransportBindingElement transport = null; BinaryMessageEncodingBindingElement encoding = null; TransactionFlowBindingElement context = null; ReliableSessionBindingElement session = null; SecurityBindingElement wsSecurity = null; BindingElement transportSecurity = null; foreach (BindingElement element in elements) { if (element is SecurityBindingElement) wsSecurity = element as SecurityBindingElement; else if (element is TransportBindingElement) transport = element as TcpTransportBindingElement; else if (element is MessageEncodingBindingElement) encoding = element as BinaryMessageEncodingBindingElement; else if (element is TransactionFlowBindingElement) context = element as TransactionFlowBindingElement; else if (element is ReliableSessionBindingElement) session = element as ReliableSessionBindingElement; else { if (transportSecurity != null) return false; transportSecurity = element; } } if (transport == null) return false; if (encoding == null) return false; if (context == null) context = GetDefaultTransactionFlowBindingElement(); TcpTransportSecurity tcpTransportSecurity = new TcpTransportSecurity(); UnifiedSecurityMode mode = GetModeFromTransportSecurity(transportSecurity); NetTcpSecurity security; if (!TryCreateSecurity(wsSecurity, mode, session != null, transportSecurity, tcpTransportSecurity, out security)) return false; if (!SetTransportSecurity(transportSecurity, security.Mode, tcpTransportSecurity)) return false; NetTcpBinding netTcpBinding = new NetTcpBinding(transport, encoding, context, session, security); if (!netTcpBinding.IsBindingElementsMatch(transport, encoding, context, session)) return false; binding = netTcpBinding; return true; } private BindingElement CreateTransportSecurity() { return _security.CreateTransportSecurity(); } private static UnifiedSecurityMode GetModeFromTransportSecurity(BindingElement transport) { return NetTcpSecurity.GetModeFromTransportSecurity(transport); } private static bool SetTransportSecurity(BindingElement transport, SecurityMode mode, TcpTransportSecurity transportSecurity) { return NetTcpSecurity.SetTransportSecurity(transport, mode, transportSecurity); } private SecurityBindingElement CreateMessageSecurity() { if (_security.Mode == SecurityMode.Message) { throw ExceptionHelper.PlatformNotSupported(nameof(SecurityMode.Message)); } if (_security.Mode == SecurityMode.TransportWithMessageCredential) { return _security.CreateMessageSecurity(ReliableSession.Enabled); } else { return null; } } private static bool TryCreateSecurity(SecurityBindingElement sbe, UnifiedSecurityMode mode, bool isReliableSession, BindingElement transportSecurity, TcpTransportSecurity tcpTransportSecurity, out NetTcpSecurity security) { if (sbe != null) mode &= UnifiedSecurityMode.Message | UnifiedSecurityMode.TransportWithMessageCredential; else mode &= ~(UnifiedSecurityMode.Message | UnifiedSecurityMode.TransportWithMessageCredential); SecurityMode securityMode = SecurityModeHelper.ToSecurityMode(mode); // TODO: Fx.Assert(SecurityModeHelper.IsDefined(securityMode), string.Format("Invalid SecurityMode value: {0}.", securityMode.ToString())); if (NetTcpSecurity.TryCreate(sbe, securityMode, isReliableSession, transportSecurity, tcpTransportSecurity, out security)) return true; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; namespace System.Security.Cryptography.Asn1 { internal partial class AsnReader { /// <summary> /// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified /// encoding type, returning the contents as an unprocessed <see cref="ReadOnlyMemory{T}"/> /// over the original data. /// </summary> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="contents"> /// On success, receives a <see cref="ReadOnlyMemory{T}"/> over the original data /// corresponding to the contents of the character string. /// </param> /// <returns> /// <c>true</c> and advances the reader if the value had a primitive encoding, /// <c>false</c> and does not advance the reader if it had a constructed encoding. /// </returns> /// <remarks> /// This method does not determine if the string used only characters defined by the encoding. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <seealso cref="TryCopyCharacterStringBytes(UniversalTagNumber,Span{byte},out int)"/> public bool TryReadPrimitiveCharacterStringBytes( UniversalTagNumber encodingType, out ReadOnlyMemory<byte> contents) { return TryReadPrimitiveCharacterStringBytes( new Asn1Tag(encodingType), encodingType, out contents); } /// <summary> /// Reads the next value as a character with a specified tag, returning the contents /// as an unprocessed <see cref="ReadOnlyMemory{T}"/> over the original data. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="contents"> /// On success, receives a <see cref="ReadOnlyMemory{T}"/> over the original data /// corresponding to the value of the OCTET STRING. /// </param> /// <returns> /// <c>true</c> and advances the reader if the OCTET STRING value had a primitive encoding, /// <c>false</c> and does not advance the reader if it had a constructed encoding. /// </returns> /// <remarks> /// This method does not determine if the string used only characters defined by the encoding. /// </remarks> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as /// <paramref name="encodingType"/>. /// </exception> /// <seealso cref="TryCopyCharacterStringBytes(Asn1Tag,UniversalTagNumber,Span{byte},out int)"/> public bool TryReadPrimitiveCharacterStringBytes( Asn1Tag expectedTag, UniversalTagNumber encodingType, out ReadOnlyMemory<byte> contents) { CheckCharacterStringEncodingType(encodingType); // T-REC-X.690-201508 sec 8.23.3, all character strings are encoded as octet strings. return TryReadPrimitiveOctetStringBytes(expectedTag, encodingType, out contents); } /// <summary> /// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified /// encoding type, copying the value into a provided destination buffer. /// </summary> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="bytesWritten"> /// On success, receives the number of bytes written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <remarks> /// This method does not determine if the string used only characters defined by the encoding. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="ReadCharacterString(UniversalTagNumber)"/> /// <seealso cref="TryCopyCharacterString(UniversalTagNumber,Span{char},out int)"/> public bool TryCopyCharacterStringBytes( UniversalTagNumber encodingType, Span<byte> destination, out int bytesWritten) { return TryCopyCharacterStringBytes( new Asn1Tag(encodingType), encodingType, destination, out bytesWritten); } /// <summary> /// Reads the next value as character string with the specified tag and /// encoding type, copying the value into a provided destination buffer. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="bytesWritten"> /// On success, receives the number of bytes written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <remarks> /// This method does not determine if the string used only characters defined by the encoding. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as /// <paramref name="encodingType"/>. /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/> /// <seealso cref="TryCopyCharacterString(Asn1Tag,UniversalTagNumber,Span{char},out int)"/> public bool TryCopyCharacterStringBytes( Asn1Tag expectedTag, UniversalTagNumber encodingType, Span<byte> destination, out int bytesWritten) { CheckCharacterStringEncodingType(encodingType); bool copied = TryCopyCharacterStringBytes( expectedTag, encodingType, destination, out int bytesRead, out bytesWritten); if (copied) { _data = _data.Slice(bytesRead); } return copied; } /// <summary> /// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified /// encoding type, copying the value into a provided destination buffer. /// </summary> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="bytesWritten"> /// On success, receives the number of bytes written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <remarks> /// This method does not determine if the string used only characters defined by the encoding. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="ReadCharacterString(UniversalTagNumber)"/> /// <seealso cref="TryCopyCharacterString(UniversalTagNumber,Span{char},out int)"/> public bool TryCopyCharacterStringBytes( UniversalTagNumber encodingType, ArraySegment<byte> destination, out int bytesWritten) { return TryCopyCharacterStringBytes( new Asn1Tag(encodingType), encodingType, destination.AsSpan(), out bytesWritten); } /// <summary> /// Reads the next value as character string with the specified tag and /// encoding type, copying the value into a provided destination buffer. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="bytesWritten"> /// On success, receives the number of bytes written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <remarks> /// This method does not determine if the string used only characters defined by the encoding. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as /// <paramref name="encodingType"/>. /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/> /// <seealso cref="TryCopyCharacterString(Asn1Tag,UniversalTagNumber,Span{char},out int)"/> public bool TryCopyCharacterStringBytes( Asn1Tag expectedTag, UniversalTagNumber encodingType, ArraySegment<byte> destination, out int bytesWritten) { return TryCopyCharacterStringBytes( expectedTag, encodingType, destination.AsSpan(), out bytesWritten); } /// <summary> /// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified /// encoding type, copying the decoded value into a provided destination buffer. /// </summary> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="charsWritten"> /// On success, receives the number of chars written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the string did not successfully decode /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="ReadCharacterString(UniversalTagNumber)"/> /// <seealso cref="TryCopyCharacterStringBytes(UniversalTagNumber,Span{byte},out int)"/> public bool TryCopyCharacterString( UniversalTagNumber encodingType, Span<char> destination, out int charsWritten) { return TryCopyCharacterString( new Asn1Tag(encodingType), encodingType, destination, out charsWritten); } /// <summary> /// Reads the next value as character string with the specified tag and /// encoding type, copying the decoded value into a provided destination buffer. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="charsWritten"> /// On success, receives the number of chars written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the string did not successfully decode /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as /// <paramref name="encodingType"/>. /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="TryCopyCharacterStringBytes(Asn1Tag,UniversalTagNumber,Span{byte},out int)"/> /// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/> public bool TryCopyCharacterString( Asn1Tag expectedTag, UniversalTagNumber encodingType, Span<char> destination, out int charsWritten) { Text.Encoding encoding = AsnCharacterStringEncodings.GetEncoding(encodingType); return TryCopyCharacterString(expectedTag, encodingType, encoding, destination, out charsWritten); } /// <summary> /// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified /// encoding type, copying the decoded value into a provided destination buffer. /// </summary> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="charsWritten"> /// On success, receives the number of chars written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the string did not successfully decode /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="ReadCharacterString(UniversalTagNumber)"/> /// <seealso cref="TryCopyCharacterStringBytes(UniversalTagNumber,ArraySegment{byte},out int)"/> /// <seealso cref="TryCopyCharacterString(Asn1Tag,UniversalTagNumber,ArraySegment{char},out int)"/> public bool TryCopyCharacterString( UniversalTagNumber encodingType, ArraySegment<char> destination, out int charsWritten) { return TryCopyCharacterString( new Asn1Tag(encodingType), encodingType, destination.AsSpan(), out charsWritten); } /// <summary> /// Reads the next value as character string with the specified tag and /// encoding type, copying the decoded value into a provided destination buffer. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="charsWritten"> /// On success, receives the number of chars written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the string did not successfully decode /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as /// <paramref name="encodingType"/>. /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="TryCopyCharacterStringBytes(Asn1Tag,UniversalTagNumber,ArraySegment{byte},out int)"/> /// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/> public bool TryCopyCharacterString( Asn1Tag expectedTag, UniversalTagNumber encodingType, ArraySegment<char> destination, out int charsWritten) { return TryCopyCharacterString( expectedTag, encodingType, destination.AsSpan(), out charsWritten); } /// <summary> /// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified /// encoding type, returning the decoded value as a <see cref="string"/>. /// </summary> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <returns> /// the decoded value as a <see cref="string"/>. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the string did not successfully decode /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="TryCopyCharacterStringBytes(UniversalTagNumber,Span{byte},out int)"/> /// <seealso cref="TryCopyCharacterString(UniversalTagNumber,Span{char},out int)"/> /// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/> public string ReadCharacterString(UniversalTagNumber encodingType) => ReadCharacterString(new Asn1Tag(encodingType), encodingType); /// <summary> /// Reads the next value as character string with the specified tag and /// encoding type, returning the decoded value as a <see cref="string"/>. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <returns> /// the decoded value as a <see cref="string"/>. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the string did not successfully decode /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as /// <paramref name="encodingType"/>. /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="TryCopyCharacterStringBytes(Asn1Tag,UniversalTagNumber,Span{byte},out int)"/> /// <seealso cref="TryCopyCharacterString(Asn1Tag,UniversalTagNumber,Span{char},out int)"/> public string ReadCharacterString(Asn1Tag expectedTag, UniversalTagNumber encodingType) { Text.Encoding encoding = AsnCharacterStringEncodings.GetEncoding(encodingType); return ReadCharacterString(expectedTag, encodingType, encoding); } // T-REC-X.690-201508 sec 8.23 private bool TryCopyCharacterStringBytes( Asn1Tag expectedTag, UniversalTagNumber universalTagNumber, Span<byte> destination, out int bytesRead, out int bytesWritten) { // T-REC-X.690-201508 sec 8.23.3, all character strings are encoded as octet strings. if (TryReadPrimitiveOctetStringBytes( expectedTag, out Asn1Tag actualTag, out int? contentLength, out int headerLength, out ReadOnlyMemory<byte> contents, universalTagNumber)) { bytesWritten = contents.Length; if (destination.Length < bytesWritten) { bytesWritten = 0; bytesRead = 0; return false; } contents.Span.CopyTo(destination); bytesRead = headerLength + bytesWritten; return true; } Debug.Assert(actualTag.IsConstructed); bool copied = TryCopyConstructedOctetStringContents( Slice(_data, headerLength, contentLength), destination, contentLength == null, out int contentBytesRead, out bytesWritten); if (copied) { bytesRead = headerLength + contentBytesRead; } else { bytesRead = 0; } return copied; } private static unsafe bool TryCopyCharacterString( ReadOnlySpan<byte> source, Span<char> destination, Text.Encoding encoding, out int charsWritten) { if (source.Length == 0) { charsWritten = 0; return true; } fixed (byte* bytePtr = &MemoryMarshal.GetReference(source)) fixed (char* charPtr = &MemoryMarshal.GetReference(destination)) { try { int charCount = encoding.GetCharCount(bytePtr, source.Length); if (charCount > destination.Length) { charsWritten = 0; return false; } charsWritten = encoding.GetChars(bytePtr, source.Length, charPtr, destination.Length); Debug.Assert(charCount == charsWritten); } catch (DecoderFallbackException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } return true; } } private string ReadCharacterString( Asn1Tag expectedTag, UniversalTagNumber universalTagNumber, Text.Encoding encoding) { byte[] rented = null; // T-REC-X.690-201508 sec 8.23.3, all character strings are encoded as octet strings. ReadOnlySpan<byte> contents = GetOctetStringContents( expectedTag, universalTagNumber, out int bytesRead, ref rented); try { string str; if (contents.Length == 0) { str = string.Empty; } else { unsafe { fixed (byte* bytePtr = &MemoryMarshal.GetReference(contents)) { try { str = encoding.GetString(bytePtr, contents.Length); } catch (DecoderFallbackException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } } } _data = _data.Slice(bytesRead); return str; } finally { if (rented != null) { CryptoPool.Return(rented, contents.Length); } } } private bool TryCopyCharacterString( Asn1Tag expectedTag, UniversalTagNumber universalTagNumber, Text.Encoding encoding, Span<char> destination, out int charsWritten) { byte[] rented = null; // T-REC-X.690-201508 sec 8.23.3, all character strings are encoded as octet strings. ReadOnlySpan<byte> contents = GetOctetStringContents( expectedTag, universalTagNumber, out int bytesRead, ref rented); try { bool copied = TryCopyCharacterString( contents, destination, encoding, out charsWritten); if (copied) { _data = _data.Slice(bytesRead); } return copied; } finally { if (rented != null) { CryptoPool.Return(rented, contents.Length); } } } private static void CheckCharacterStringEncodingType(UniversalTagNumber encodingType) { // T-REC-X.680-201508 sec 41 switch (encodingType) { case UniversalTagNumber.BMPString: case UniversalTagNumber.GeneralString: case UniversalTagNumber.GraphicString: case UniversalTagNumber.IA5String: case UniversalTagNumber.ISO646String: case UniversalTagNumber.NumericString: case UniversalTagNumber.PrintableString: case UniversalTagNumber.TeletexString: // T61String is an alias for TeletexString (already listed) case UniversalTagNumber.UniversalString: case UniversalTagNumber.UTF8String: case UniversalTagNumber.VideotexString: // VisibleString is an alias for ISO646String (already listed) return; } throw new ArgumentOutOfRangeException(nameof(encodingType)); } } }
// 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.Data.Common; using System.Diagnostics; using System.Runtime.InteropServices; using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Data.SqlTypes { /// <summary> /// Represents a currency value ranging from /// -2<superscript term='63'/> (or -922,337,203,685,477.5808) to 2<superscript term='63'/> -1 (or /// +922,337,203,685,477.5807) with an accuracy to /// a ten-thousandth of currency unit to be stored in or retrieved from a /// database. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] [XmlSchemaProvider("GetXsdType")] public struct SqlMoney : INullable, IComparable, IXmlSerializable { // NOTE: If any instance fields change, update SqlTypeWorkarounds type in System.Data.SqlClient. private bool _fNotNull; // false if null private long _value; // SQL Server stores money8 as ticks of 1/10000. internal static readonly int s_iMoneyScale = 4; private static readonly long s_lTickBase = 10000; private static readonly double s_dTickBase = s_lTickBase; private static readonly long s_minLong = unchecked((long)0x8000000000000000L) / s_lTickBase; private static readonly long s_maxLong = 0x7FFFFFFFFFFFFFFFL / s_lTickBase; // constructor // construct a Null private SqlMoney(bool fNull) { _fNotNull = false; _value = 0; } // Constructs from a long value without scaling. The ignored parameter exists // only to distinguish this constructor from the constructor that takes a long. // Used only internally. internal SqlMoney(long value, int ignored) { _value = value; _fNotNull = true; } /// <summary> /// Initializes a new instance of the <see cref='SqlMoney'/> class with the value given. /// </summary> public SqlMoney(int value) { _value = value * s_lTickBase; _fNotNull = true; } /// <summary> /// Initializes a new instance of the <see cref='SqlMoney'/> class with the value given. /// </summary> public SqlMoney(long value) { if (value < s_minLong || value > s_maxLong) throw new OverflowException(SQLResource.ArithOverflowMessage); _value = value * s_lTickBase; _fNotNull = true; } /// <summary> /// Initializes a new instance of the <see cref='SqlMoney'/> class with the value given. /// </summary> public SqlMoney(decimal value) { // Since Decimal is a value type, operate directly on value, don't worry about changing it. SqlDecimal snum = new SqlDecimal(value); snum.AdjustScale(s_iMoneyScale - snum.Scale, true); Debug.Assert(snum.Scale == s_iMoneyScale); if (snum._data3 != 0 || snum._data4 != 0) throw new OverflowException(SQLResource.ArithOverflowMessage); bool fPositive = snum.IsPositive; ulong ulValue = snum._data1 + (((ulong)snum._data2) << 32); if (fPositive && ulValue > long.MaxValue || !fPositive && ulValue > unchecked((ulong)(long.MinValue))) throw new OverflowException(SQLResource.ArithOverflowMessage); _value = fPositive ? (long)ulValue : unchecked(-(long)ulValue); _fNotNull = true; } /// <summary> /// Initializes a new instance of the <see cref='SqlMoney'/> class with the value given. /// </summary> public SqlMoney(double value) : this(new decimal(value)) { } /// <summary> /// Gets a value indicating whether the <see cref='Value'/> /// property is assigned to null. /// </summary> public bool IsNull { get { return !_fNotNull; } } /// <summary> /// Gets or sets the monetary value of an instance of the <see cref='SqlMoney'/> class. /// </summary> public decimal Value { get { if (_fNotNull) return ToDecimal(); else throw new SqlNullValueException(); } } public decimal ToDecimal() { if (IsNull) throw new SqlNullValueException(); bool fNegative = false; long value = _value; if (_value < 0) { fNegative = true; value = unchecked(-_value); } return new decimal(unchecked((int)value), unchecked((int)(value >> 32)), 0, fNegative, (byte)s_iMoneyScale); } public long ToInt64() { if (IsNull) throw new SqlNullValueException(); long ret = _value / (s_lTickBase / 10); bool fPositive = (ret >= 0); long remainder = ret % 10; ret = ret / 10; if (remainder >= 5) { if (fPositive) ret++; else ret--; } return ret; } internal long ToSqlInternalRepresentation() { if (IsNull) throw new SqlNullValueException(); return _value; } public int ToInt32() { return checked((int)(ToInt64())); } public double ToDouble() { return decimal.ToDouble(ToDecimal()); } // Implicit conversion from Decimal to SqlMoney public static implicit operator SqlMoney(decimal x) { return new SqlMoney(x); } // Explicit conversion from Double to SqlMoney public static explicit operator SqlMoney(double x) { return new SqlMoney(x); } // Implicit conversion from long to SqlMoney public static implicit operator SqlMoney(long x) { return new SqlMoney(new decimal(x)); } // Explicit conversion from SqlMoney to Decimal. Throw exception if x is Null. public static explicit operator decimal (SqlMoney x) { return x.Value; } public override string ToString() { if (IsNull) { return SQLResource.NullString; } decimal money = ToDecimal(); // Formatting of SqlMoney: At least two digits after decimal point return money.ToString("#0.00##", null); } public static SqlMoney Parse(string s) { // Try parsing the format of '#0.00##' generated by ToString() by using the // culture invariant NumberFormatInfo as well as the current culture's format // decimal d; SqlMoney money; const NumberStyles SqlNumberStyle = NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint | NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingWhite; if (s == SQLResource.NullString) { money = SqlMoney.Null; } else if (decimal.TryParse(s, SqlNumberStyle, NumberFormatInfo.InvariantInfo, out d)) { money = new SqlMoney(d); } else { money = new SqlMoney(decimal.Parse(s, NumberStyles.Currency, NumberFormatInfo.CurrentInfo)); } return money; } // Unary operators public static SqlMoney operator -(SqlMoney x) { if (x.IsNull) return Null; if (x._value == s_minLong) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlMoney(-x._value, 0); } // Binary operators // Arithmetic operators public static SqlMoney operator +(SqlMoney x, SqlMoney y) { try { return (x.IsNull || y.IsNull) ? Null : new SqlMoney(checked(x._value + y._value), 0); } catch (OverflowException) { throw new OverflowException(SQLResource.ArithOverflowMessage); } } public static SqlMoney operator -(SqlMoney x, SqlMoney y) { try { return (x.IsNull || y.IsNull) ? Null : new SqlMoney(checked(x._value - y._value), 0); } catch (OverflowException) { throw new OverflowException(SQLResource.ArithOverflowMessage); } } public static SqlMoney operator *(SqlMoney x, SqlMoney y) { return (x.IsNull || y.IsNull) ? Null : new SqlMoney(decimal.Multiply(x.ToDecimal(), y.ToDecimal())); } public static SqlMoney operator /(SqlMoney x, SqlMoney y) { return (x.IsNull || y.IsNull) ? Null : new SqlMoney(decimal.Divide(x.ToDecimal(), y.ToDecimal())); } // Implicit conversions // Implicit conversion from SqlBoolean to SqlMoney public static explicit operator SqlMoney(SqlBoolean x) { return x.IsNull ? Null : new SqlMoney(x.ByteValue); } // Implicit conversion from SqlByte to SqlMoney public static implicit operator SqlMoney(SqlByte x) { return x.IsNull ? Null : new SqlMoney(x.Value); } // Implicit conversion from SqlInt16 to SqlMoney public static implicit operator SqlMoney(SqlInt16 x) { return x.IsNull ? Null : new SqlMoney(x.Value); } // Implicit conversion from SqlInt32 to SqlMoney public static implicit operator SqlMoney(SqlInt32 x) { return x.IsNull ? Null : new SqlMoney(x.Value); } // Implicit conversion from SqlInt64 to SqlMoney public static implicit operator SqlMoney(SqlInt64 x) { return x.IsNull ? Null : new SqlMoney(x.Value); } // Explicit conversions // Explicit conversion from SqlSingle to SqlMoney public static explicit operator SqlMoney(SqlSingle x) { return x.IsNull ? Null : new SqlMoney(x.Value); } // Explicit conversion from SqlDouble to SqlMoney public static explicit operator SqlMoney(SqlDouble x) { return x.IsNull ? Null : new SqlMoney(x.Value); } // Explicit conversion from SqlDecimal to SqlMoney public static explicit operator SqlMoney(SqlDecimal x) { return x.IsNull ? SqlMoney.Null : new SqlMoney(x.Value); } // Explicit conversion from SqlString to SqlMoney // Throws FormatException or OverflowException if necessary. public static explicit operator SqlMoney(SqlString x) { return x.IsNull ? Null : new SqlMoney(decimal.Parse(x.Value, NumberStyles.Currency, null)); } // Builtin functions // Overloading comparison operators public static SqlBoolean operator ==(SqlMoney x, SqlMoney y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value == y._value); } public static SqlBoolean operator !=(SqlMoney x, SqlMoney y) { return !(x == y); } public static SqlBoolean operator <(SqlMoney x, SqlMoney y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value < y._value); } public static SqlBoolean operator >(SqlMoney x, SqlMoney y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value > y._value); } public static SqlBoolean operator <=(SqlMoney x, SqlMoney y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value <= y._value); } public static SqlBoolean operator >=(SqlMoney x, SqlMoney y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value >= y._value); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator + public static SqlMoney Add(SqlMoney x, SqlMoney y) { return x + y; } // Alternative method for operator - public static SqlMoney Subtract(SqlMoney x, SqlMoney y) { return x - y; } // Alternative method for operator * public static SqlMoney Multiply(SqlMoney x, SqlMoney y) { return x * y; } // Alternative method for operator / public static SqlMoney Divide(SqlMoney x, SqlMoney y) { return x / y; } // Alternative method for operator == public static SqlBoolean Equals(SqlMoney x, SqlMoney y) { return (x == y); } // Alternative method for operator != public static SqlBoolean NotEquals(SqlMoney x, SqlMoney y) { return (x != y); } // Alternative method for operator < public static SqlBoolean LessThan(SqlMoney x, SqlMoney y) { return (x < y); } // Alternative method for operator > public static SqlBoolean GreaterThan(SqlMoney x, SqlMoney y) { return (x > y); } // Alternative method for operator <= public static SqlBoolean LessThanOrEqual(SqlMoney x, SqlMoney y) { return (x <= y); } // Alternative method for operator >= public static SqlBoolean GreaterThanOrEqual(SqlMoney x, SqlMoney y) { return (x >= y); } // Alternative method for conversions. public SqlBoolean ToSqlBoolean() { return (SqlBoolean)this; } public SqlByte ToSqlByte() { return (SqlByte)this; } public SqlDouble ToSqlDouble() { return this; } public SqlInt16 ToSqlInt16() { return (SqlInt16)this; } public SqlInt32 ToSqlInt32() { return (SqlInt32)this; } public SqlInt64 ToSqlInt64() { return (SqlInt64)this; } public SqlDecimal ToSqlDecimal() { return this; } public SqlSingle ToSqlSingle() { return this; } public SqlString ToSqlString() { return (SqlString)this; } // IComparable // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this < object, zero if this = object, // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object value) { if (value is SqlMoney) { SqlMoney i = (SqlMoney)value; return CompareTo(i); } throw ADP.WrongType(value.GetType(), typeof(SqlMoney)); } public int CompareTo(SqlMoney value) { // If both Null, consider them equal. // Otherwise, Null is less than anything. if (IsNull) return value.IsNull ? 0 : -1; else if (value.IsNull) return 1; if (this < value) return -1; if (this > value) return 1; return 0; } // Compares this instance with a specified object public override bool Equals(object value) { if (!(value is SqlMoney)) { return false; } SqlMoney i = (SqlMoney)value; if (i.IsNull || IsNull) return (i.IsNull && IsNull); else return (this == i).Value; } // For hashing purpose public override int GetHashCode() { // Don't use Value property, because Value will convert to Decimal, which is not necessary. return IsNull ? 0 : _value.GetHashCode(); } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); _fNotNull = false; } else { SqlMoney money = new SqlMoney(XmlConvert.ToDecimal(reader.ReadElementString())); _fNotNull = money._fNotNull; _value = money._value; } } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { writer.WriteString(XmlConvert.ToString(ToDecimal())); } } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("decimal", XmlSchema.Namespace); } /// <summary> /// Represents a null value that can be assigned to /// the <see cref='Value'/> property of an instance of /// the <see cref='SqlMoney'/>class. /// </summary> public static readonly SqlMoney Null = new SqlMoney(true); /// <summary> /// Represents the zero value that can be assigned to the <see cref='Value'/> property of an instance of /// the <see cref='SqlMoney'/> class. /// </summary> public static readonly SqlMoney Zero = new SqlMoney(0); /// <summary> /// Represents the minimum value that can be assigned /// to <see cref='Value'/> property of an instance of /// the <see cref='SqlMoney'/> /// class. /// </summary> public static readonly SqlMoney MinValue = new SqlMoney(unchecked((long)0x8000000000000000L), 0); /// <summary> /// Represents the maximum value that can be assigned to /// the <see cref='Value'/> property of an instance of /// the <see cref='SqlMoney'/> /// class. /// </summary> public static readonly SqlMoney MaxValue = new SqlMoney(0x7FFFFFFFFFFFFFFFL, 0); } // SqlMoney } // namespace System.Data.SqlTypes
using System; #if UNITY_EDITOR using UnityEditor; #endif namespace UnityEngine.Experimental.Rendering.HDPipeline { [Serializable] public class SubsurfaceScatteringProfile : ScriptableObject { public enum TexturingMode : int { PreAndPostScatter = 0, PostScatter = 1 }; public const int numSamples = 11; // Must be an odd number [ColorUsage(false, true, 0.05f, 2.0f, 1.0f, 1.0f)] public Color stdDev1; [ColorUsage(false, true, 0.05f, 2.0f, 1.0f, 1.0f)] public Color stdDev2; public float lerpWeight; public TexturingMode texturingMode; public bool enableTransmission; public Color tintColor; public Vector2 thicknessRemap; [HideInInspector] public int settingsIndex; [SerializeField] Vector4[] m_FilterKernel; [SerializeField] Vector3[] m_HalfRcpVariances; [SerializeField] Vector4 m_HalfRcpWeightedVariances; // --- Public Methods --- public SubsurfaceScatteringProfile() { stdDev1 = new Color(0.3f, 0.3f, 0.3f, 0.0f); stdDev2 = new Color(0.6f, 0.6f, 0.6f, 0.0f); lerpWeight = 0.5f; texturingMode = TexturingMode.PreAndPostScatter; enableTransmission = false; tintColor = Color.white; thicknessRemap = new Vector2(0, 1); settingsIndex = SubsurfaceScatteringSettings.neutralProfileID; // Updated by SubsurfaceScatteringSettings.OnValidate() once assigned UpdateKernelAndVarianceData(); } public Vector4[] filterKernel { // Set via UpdateKernelAndVarianceData(). get { return m_FilterKernel; } } public Vector3[] halfRcpVariances { // Set via UpdateKernelAndVarianceData(). get { return m_HalfRcpVariances; } } public Vector4 halfRcpWeightedVariances { // Set via UpdateKernelAndVarianceData(). get { return m_HalfRcpWeightedVariances; } } public void UpdateKernelAndVarianceData() { if (m_FilterKernel == null || m_FilterKernel.Length != numSamples) { m_FilterKernel = new Vector4[numSamples]; } if (m_HalfRcpVariances == null) { m_HalfRcpVariances = new Vector3[2]; } // Our goal is to blur the image using a filter which is represented // as a product of a linear combination of two normalized 1D Gaussians // as suggested by Jimenez et al. in "Separable Subsurface Scattering". // A normalized (i.e. energy-preserving) 1D Gaussian with the mean of 0 // is defined as follows: G1(x, v) = exp(-x * x / (2 * v)) / sqrt(2 * Pi * v), // where 'v' is variance and 'x' is the radial distance from the origin. // Using the weight 'w', our 1D and the resulting 2D filters are given as: // A1(v1, v2, w, x) = G1(x, v1) * (1 - w) + G1(r, v2) * w, // A2(v1, v2, w, x, y) = A1(v1, v2, w, x) * A1(v1, v2, w, y). // The resulting filter function is a non-Gaussian PDF. // It is separable by design, but generally not radially symmetric. // Find the widest Gaussian across 3 color channels. float maxStdDev1 = Mathf.Max(stdDev1.r, stdDev1.g, stdDev1.b); float maxStdDev2 = Mathf.Max(stdDev2.r, stdDev2.g, stdDev2.b); Vector3 weightSum = new Vector3(0, 0, 0); float rcpNumSamples = 1.0f / numSamples; // Importance sample the linear combination of two Gaussians. for (uint i = 0; i < numSamples; i++) { float u = (i <= numSamples / 2) ? 0.5f - i * rcpNumSamples // The center and to the left : (i + 0.5f) * rcpNumSamples; // From the center to the right float pos = GaussianCombinationCdfInverse(u, maxStdDev1, maxStdDev2, lerpWeight); float pdf = GaussianCombination(pos, maxStdDev1, maxStdDev2, lerpWeight); Vector3 val; val.x = GaussianCombination(pos, stdDev1.r, stdDev2.r, lerpWeight); val.y = GaussianCombination(pos, stdDev1.g, stdDev2.g, lerpWeight); val.z = GaussianCombination(pos, stdDev1.b, stdDev2.b, lerpWeight); // We do not divide by 'numSamples' since we will renormalize, anyway. m_FilterKernel[i].x = val.x * (1 / pdf); m_FilterKernel[i].y = val.y * (1 / pdf); m_FilterKernel[i].z = val.z * (1 / pdf); m_FilterKernel[i].w = pos; weightSum.x += m_FilterKernel[i].x; weightSum.y += m_FilterKernel[i].y; weightSum.z += m_FilterKernel[i].z; } // Renormalize the weights to conserve energy. for (uint i = 0; i < numSamples; i++) { m_FilterKernel[i].x *= 1 / weightSum.x; m_FilterKernel[i].y *= 1 / weightSum.y; m_FilterKernel[i].z *= 1 / weightSum.z; } // Store (1 / (2 * Variance)) per color channel per Gaussian. m_HalfRcpVariances[0].x = 0.5f / (stdDev1.r * stdDev1.r); m_HalfRcpVariances[0].y = 0.5f / (stdDev1.g * stdDev1.g); m_HalfRcpVariances[0].z = 0.5f / (stdDev1.b * stdDev1.b); m_HalfRcpVariances[1].x = 0.5f / (stdDev2.r * stdDev2.r); m_HalfRcpVariances[1].y = 0.5f / (stdDev2.g * stdDev2.g); m_HalfRcpVariances[1].z = 0.5f / (stdDev2.b * stdDev2.b); Vector4 weightedStdDev; weightedStdDev.x = Mathf.Lerp(stdDev1.r, stdDev2.r, lerpWeight); weightedStdDev.y = Mathf.Lerp(stdDev1.g, stdDev2.g, lerpWeight); weightedStdDev.z = Mathf.Lerp(stdDev1.b, stdDev2.b, lerpWeight); weightedStdDev.w = Mathf.Lerp(maxStdDev1, maxStdDev2, lerpWeight); // Store (1 / (2 * WeightedVariance)) per color channel. m_HalfRcpWeightedVariances.x = 0.5f / (weightedStdDev.x * weightedStdDev.x); m_HalfRcpWeightedVariances.y = 0.5f / (weightedStdDev.y * weightedStdDev.y); m_HalfRcpWeightedVariances.z = 0.5f / (weightedStdDev.z * weightedStdDev.z); m_HalfRcpWeightedVariances.w = 0.5f / (weightedStdDev.w * weightedStdDev.w); } // --- Private Methods --- static float Gaussian(float x, float stdDev) { float variance = stdDev * stdDev; return Mathf.Exp(-x * x / (2 * variance)) / Mathf.Sqrt(2 * Mathf.PI * variance); } static float GaussianCombination(float x, float stdDev1, float stdDev2, float lerpWeight) { return Mathf.Lerp(Gaussian(x, stdDev1), Gaussian(x, stdDev2), lerpWeight); } static float RationalApproximation(float t) { // Abramowitz and Stegun formula 26.2.23. // The absolute value of the error should be less than 4.5 e-4. float[] c = {2.515517f, 0.802853f, 0.010328f}; float[] d = {1.432788f, 0.189269f, 0.001308f}; return t - ((c[2] * t + c[1]) * t + c[0]) / (((d[2] * t + d[1]) * t + d[0]) * t + 1.0f); } // Ref: https://www.johndcook.com/blog/csharp_phi_inverse/ static float NormalCdfInverse(float p, float stdDev) { float x; if (p < 0.5) { // F^-1(p) = - G^-1(p) x = -RationalApproximation(Mathf.Sqrt(-2.0f * Mathf.Log(p))); } else { // F^-1(p) = G^-1(1-p) x = RationalApproximation(Mathf.Sqrt(-2.0f * Mathf.Log(1.0f - p))); } return x * stdDev; } static float GaussianCombinationCdfInverse(float p, float stdDev1, float stdDev2, float lerpWeight) { return Mathf.Lerp(NormalCdfInverse(p, stdDev1), NormalCdfInverse(p, stdDev2), lerpWeight); } } [Serializable] public class SubsurfaceScatteringSettings : ISerializationCallbackReceiver { public const int maxNumProfiles = 8; public const int neutralProfileID = maxNumProfiles - 1; public int numProfiles; public SubsurfaceScatteringProfile[] profiles; // Below is the cache filled during OnValidate(). [NonSerialized] public int texturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter [NonSerialized] public int transmissionFlags; // 1 bit/profile; 0 = inf. thick, 1 = supports transmission [NonSerialized] public Vector4[] tintColors; // For transmission; alpha is unused [NonSerialized] public float[] thicknessRemaps; [NonSerialized] public Vector4[] halfRcpVariancesAndLerpWeights; [NonSerialized] public Vector4[] halfRcpWeightedVariances; [NonSerialized] public Vector4[] filterKernels; // --- Public Methods --- public SubsurfaceScatteringSettings() { numProfiles = 1; profiles = new SubsurfaceScatteringProfile[numProfiles]; profiles[0] = null; texturingModeFlags = 0; transmissionFlags = 0; tintColors = null; thicknessRemaps = null; halfRcpVariancesAndLerpWeights = null; halfRcpWeightedVariances = null; filterKernels = null; UpdateCache(); } public void OnValidate() { // Reserve one slot for the neutral profile. numProfiles = Math.Min(profiles.Length, maxNumProfiles - 1); if (profiles.Length != numProfiles) { Array.Resize(ref profiles, numProfiles); } for (int i = 0; i < numProfiles; i++) { if (profiles[i] != null) { // Assign the profile IDs. profiles[i].settingsIndex = i; } } Color c = new Color(); for (int i = 0; i < numProfiles; i++) { // Skip unassigned profiles. if (profiles[i] == null) continue; c.r = Mathf.Clamp(profiles[i].stdDev1.r, 0.05f, 2.0f); c.g = Mathf.Clamp(profiles[i].stdDev1.g, 0.05f, 2.0f); c.b = Mathf.Clamp(profiles[i].stdDev1.b, 0.05f, 2.0f); c.a = 0.0f; profiles[i].stdDev1 = c; c.r = Mathf.Clamp(profiles[i].stdDev2.r, 0.05f, 2.0f); c.g = Mathf.Clamp(profiles[i].stdDev2.g, 0.05f, 2.0f); c.b = Mathf.Clamp(profiles[i].stdDev2.b, 0.05f, 2.0f); c.a = 0.0f; profiles[i].stdDev2 = c; profiles[i].lerpWeight = Mathf.Clamp01(profiles[i].lerpWeight); profiles[i].tintColor.r = Mathf.Clamp01(profiles[i].tintColor.r); profiles[i].tintColor.g = Mathf.Clamp01(profiles[i].tintColor.g); profiles[i].tintColor.b = Mathf.Clamp01(profiles[i].tintColor.b); profiles[i].tintColor.a = 1.0f; profiles[i].thicknessRemap.x = Mathf.Clamp(profiles[i].thicknessRemap.x, 0, profiles[i].thicknessRemap.y); profiles[i].thicknessRemap.y = Mathf.Max(profiles[i].thicknessRemap.x, profiles[i].thicknessRemap.y); profiles[i].UpdateKernelAndVarianceData(); } UpdateCache(); } public void UpdateCache() { texturingModeFlags = 0; transmissionFlags = 0; if (tintColors == null || tintColors.Length != maxNumProfiles) { tintColors = new Vector4[maxNumProfiles]; } if (thicknessRemaps == null || thicknessRemaps.Length != (maxNumProfiles * 2)) { thicknessRemaps = new float[maxNumProfiles * 2]; } if (halfRcpVariancesAndLerpWeights == null || halfRcpVariancesAndLerpWeights.Length != (maxNumProfiles * 2)) { halfRcpVariancesAndLerpWeights = new Vector4[maxNumProfiles * 2]; } if (halfRcpWeightedVariances == null || halfRcpWeightedVariances.Length != maxNumProfiles) { halfRcpWeightedVariances = new Vector4[maxNumProfiles]; } if (filterKernels == null || filterKernels.Length != (maxNumProfiles * SubsurfaceScatteringProfile.numSamples)) { filterKernels = new Vector4[maxNumProfiles * SubsurfaceScatteringProfile.numSamples]; } for (int i = 0; i < numProfiles; i++) { // Skip unassigned profiles. if (profiles[i] == null) continue; texturingModeFlags |= ((int)profiles[i].texturingMode) << i; transmissionFlags |= (profiles[i].enableTransmission ? 1 : 0) << i; tintColors[i] = profiles[i].tintColor; thicknessRemaps[2 * i] = profiles[i].thicknessRemap.x; thicknessRemaps[2 * i + 1] = profiles[i].thicknessRemap.y - profiles[i].thicknessRemap.x; halfRcpVariancesAndLerpWeights[2 * i] = profiles[i].halfRcpVariances[0]; halfRcpVariancesAndLerpWeights[2 * i].w = 1.0f - profiles[i].lerpWeight; halfRcpVariancesAndLerpWeights[2 * i + 1] = profiles[i].halfRcpVariances[1]; halfRcpVariancesAndLerpWeights[2 * i + 1].w = profiles[i].lerpWeight; halfRcpWeightedVariances[i] = profiles[i].halfRcpWeightedVariances; for (int j = 0, n = SubsurfaceScatteringProfile.numSamples; j < n; j++) { filterKernels[n * i + j] = profiles[i].filterKernel[j]; } } // Fill the neutral profile. { int i = neutralProfileID; halfRcpWeightedVariances[i] = Vector4.one; for (int j = 0, n = SubsurfaceScatteringProfile.numSamples; j < n; j++) { filterKernels[n * i + j] = Vector4.one; filterKernels[n * i + j].w = 0.0f; } } } public void OnBeforeSerialize() { // No special action required. } public void OnAfterDeserialize() { UpdateCache(); } } #if UNITY_EDITOR public class SubsurfaceScatteringProfileFactory { [MenuItem("Assets/Create/Subsurface Scattering Profile", priority = 666)] static void MenuCreateSubsurfaceScatteringProfile() { Texture2D icon = EditorGUIUtility.FindTexture("ScriptableObject Icon"); ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateSubsurfaceScatteringProfile>(), "New SSS Profile.asset", icon, null); } public static SubsurfaceScatteringProfile CreateSssProfileAtPath(string path) { var profile = ScriptableObject.CreateInstance<SubsurfaceScatteringProfile>(); profile.name = System.IO.Path.GetFileName(path); AssetDatabase.CreateAsset(profile, path); return profile; } } class DoCreateSubsurfaceScatteringProfile : UnityEditor.ProjectWindowCallback.EndNameEditAction { public override void Action(int instanceId, string pathName, string resourceFile) { var profiles = SubsurfaceScatteringProfileFactory.CreateSssProfileAtPath(pathName); ProjectWindowUtil.ShowCreatedAsset(profiles); } } [CustomEditor(typeof(SubsurfaceScatteringProfile))] public class SubsurfaceScatteringProfileEditor : Editor { private class Styles { public readonly GUIContent sssProfilePreview0 = new GUIContent("Profile Preview"); public readonly GUIContent sssProfilePreview1 = new GUIContent("Shows the fraction of light scattered from the source as radius increases to 1."); public readonly GUIContent sssProfilePreview2 = new GUIContent("Note that the intensity of the region in the center may be clamped."); public readonly GUIContent sssTransmittancePreview0 = new GUIContent("Transmittance Preview"); public readonly GUIContent sssTransmittancePreview1 = new GUIContent("Shows the fraction of light passing through the object as thickness increases to 1."); public readonly GUIContent sssProfileStdDev1 = new GUIContent("Standard Deviation #1", "Determines the shape of the 1st Gaussian filter. Increases the strength and the radius of the blur of the corresponding color channel."); public readonly GUIContent sssProfileStdDev2 = new GUIContent("Standard Deviation #2", "Determines the shape of the 2nd Gaussian filter. Increases the strength and the radius of the blur of the corresponding color channel."); public readonly GUIContent sssProfileLerpWeight = new GUIContent("Filter Interpolation", "Controls linear interpolation between the two Gaussian filters."); public readonly GUIContent sssTexturingMode = new GUIContent("Texturing Mode", "Specifies when the diffuse texture should be applied."); public readonly GUIContent[] sssTexturingModeOptions = new GUIContent[2] { new GUIContent("Pre- and post-scatter", "Texturing is performed during both the lighting and the SSS passes. Slightly blurs the diffuse texture. Choose this mode if your diffuse texture contains little to no SSS lighting."), new GUIContent("Post-scatter", "Texturing is performed only during the SSS pass. Effectively preserves the sharpness of the diffuse texture. Choose this mode if your diffuse texture already contains SSS lighting (e.g. a photo of skin).") }; public readonly GUIContent sssProfileTransmission = new GUIContent("Enable Transmission", "Toggles simulation of light passing through thin objects. Depends on the thickness of the material."); public readonly GUIContent sssProfileTintColor = new GUIContent("Transmission Tint Color", "Tints transmitted light."); public readonly GUIContent sssProfileMinMaxThickness = new GUIContent("Min-Max Thickness", "Shows the values of the thickness remap below."); public readonly GUIContent sssProfileThicknessRemap = new GUIContent("Thickness Remap", "Remaps the thickness parameter from [0, 1] to the desired range."); public readonly GUIStyle centeredMiniBoldLabel = new GUIStyle(GUI.skin.label); public Styles() { centeredMiniBoldLabel.alignment = TextAnchor.MiddleCenter; centeredMiniBoldLabel.fontSize = 10; centeredMiniBoldLabel.fontStyle = FontStyle.Bold; } } private static Styles styles { get { if (s_Styles == null) { s_Styles = new Styles(); } return s_Styles; } } private static Styles s_Styles = null; private RenderTexture m_ProfileImage, m_TransmittanceImage; private Material m_ProfileMaterial, m_TransmittanceMaterial; private SerializedProperty m_StdDev1, m_StdDev2, m_LerpWeight, m_TintColor, m_TexturingMode, m_Transmission, m_ThicknessRemap; void OnEnable() { m_StdDev1 = serializedObject.FindProperty("stdDev1"); m_StdDev2 = serializedObject.FindProperty("stdDev2"); m_LerpWeight = serializedObject.FindProperty("lerpWeight"); m_TexturingMode = serializedObject.FindProperty("texturingMode"); m_Transmission = serializedObject.FindProperty("enableTransmission"); m_TintColor = serializedObject.FindProperty("tintColor"); m_ThicknessRemap = serializedObject.FindProperty("thicknessRemap"); m_ProfileMaterial = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/DrawGaussianProfile"); m_TransmittanceMaterial = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/DrawTransmittanceGraph"); m_ProfileImage = new RenderTexture(256, 256, 0, RenderTextureFormat.DefaultHDR); m_TransmittanceImage = new RenderTexture(16, 256, 0, RenderTextureFormat.DefaultHDR); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUI.BeginChangeCheck(); { EditorGUILayout.PropertyField(m_StdDev1, styles.sssProfileStdDev1); EditorGUILayout.PropertyField(m_StdDev2, styles.sssProfileStdDev2); EditorGUILayout.PropertyField(m_LerpWeight, styles.sssProfileLerpWeight); m_TexturingMode.intValue = EditorGUILayout.Popup(styles.sssTexturingMode, m_TexturingMode.intValue, styles.sssTexturingModeOptions); EditorGUILayout.PropertyField(m_Transmission, styles.sssProfileTransmission); EditorGUILayout.PropertyField(m_TintColor, styles.sssProfileTintColor); EditorGUILayout.PropertyField(m_ThicknessRemap, styles.sssProfileMinMaxThickness); Vector2 thicknessRemap = m_ThicknessRemap.vector2Value; EditorGUILayout.MinMaxSlider(styles.sssProfileThicknessRemap, ref thicknessRemap.x, ref thicknessRemap.y, 0, 10); m_ThicknessRemap.vector2Value = thicknessRemap; EditorGUILayout.Space(); EditorGUILayout.LabelField(styles.sssProfilePreview0, styles.centeredMiniBoldLabel); EditorGUILayout.LabelField(styles.sssProfilePreview1, EditorStyles.centeredGreyMiniLabel); EditorGUILayout.LabelField(styles.sssProfilePreview2, EditorStyles.centeredGreyMiniLabel); EditorGUILayout.Space(); } // Draw the profile. m_ProfileMaterial.SetColor("_StdDev1", m_StdDev1.colorValue); m_ProfileMaterial.SetColor("_StdDev2", m_StdDev2.colorValue); m_ProfileMaterial.SetFloat("_LerpWeight", m_LerpWeight.floatValue); EditorGUI.DrawPreviewTexture(GUILayoutUtility.GetRect(256, 256), m_ProfileImage, m_ProfileMaterial, ScaleMode.ScaleToFit, 1.0f); EditorGUILayout.Space(); EditorGUILayout.LabelField(styles.sssTransmittancePreview0, styles.centeredMiniBoldLabel); EditorGUILayout.LabelField(styles.sssTransmittancePreview1, EditorStyles.centeredGreyMiniLabel); EditorGUILayout.Space(); // Draw the transmittance graph. m_TransmittanceMaterial.SetColor("_StdDev1", m_StdDev1.colorValue); m_TransmittanceMaterial.SetColor("_StdDev2", m_StdDev2.colorValue); m_TransmittanceMaterial.SetFloat("_LerpWeight", m_LerpWeight.floatValue); m_TransmittanceMaterial.SetVector("_ThicknessRemap", m_ThicknessRemap.vector2Value); m_TransmittanceMaterial.SetVector("_TintColor", m_TintColor.colorValue); EditorGUI.DrawPreviewTexture(GUILayoutUtility.GetRect(16, 16), m_TransmittanceImage, m_TransmittanceMaterial, ScaleMode.ScaleToFit, 16.0f); serializedObject.ApplyModifiedProperties(); if (EditorGUI.EndChangeCheck()) { // Validate each individual asset and update caches. HDRenderPipelineInstance hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipelineInstance; hdPipeline.sssSettings.OnValidate(); } } } #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.IO; using System.Linq; using System.Reflection.Metadata.Cil.Decoder; using System.Reflection.Metadata.Cil.Visitor; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Metadata.Cil { /// <summary> /// Class representing an assembly. /// </summary> public struct CilAssembly : ICilVisitable, IDisposable { private CilReaders _readers; private AssemblyDefinition _assemblyDefinition; private byte[] _publicKey; private IEnumerable<CilTypeDefinition> _typeDefinitions; private string _name; private string _culture; private int _hashAlgorithm; private Version _version; private IEnumerable<CilAssemblyReference> _assemblyReferences; private IEnumerable<CilTypeReference> _typeReferences; private IEnumerable<CilCustomAttribute> _customAttribues; private IEnumerable<CilModuleReference> _moduleReferences; private CilModuleDefinition _moduleDefinition; private CilHeaderOptions _headerOptions; private bool _isHeaderInitialized; private bool _isModuleInitialized; private bool _disposed; #region Public APIs public static CilAssembly Create(Stream stream) { CilAssembly assembly = new CilAssembly(); CilReaders readers = CilReaders.Create(stream); assembly._readers = readers; assembly._hashAlgorithm = -1; assembly._assemblyDefinition = readers.MdReader.GetAssemblyDefinition(); assembly._isModuleInitialized = false; assembly._isHeaderInitialized = false; assembly._disposed = false; return assembly; } public static CilAssembly Create(string path) { if (!File.Exists(path)) { throw new ArgumentException("File doesn't exist in path"); } return Create(File.OpenRead(path)); } /// <summary> /// Property that represent the Assembly name. /// </summary> public string Name { get { return CilDecoder.GetCachedValue(_assemblyDefinition.Name, _readers, ref _name); } } /// <summary> /// Property containing the assembly culture. known as locale, such as en-US or fr-CA. /// </summary> public string Culture { get { return CilDecoder.GetCachedValue(_assemblyDefinition.Culture, _readers, ref _culture); } } /// <summary> /// Property that represents the hash algorithm used on this assembly to hash the files. /// </summary> public int HashAlgorithm { get { if(_hashAlgorithm == -1) { _hashAlgorithm = Convert.ToInt32(_assemblyDefinition.HashAlgorithm); } return _hashAlgorithm; } } /// <summary> /// Version of the assembly. /// Containing: /// MajorVersion /// MinorVersion /// BuildNumber /// RevisionNumber /// </summary> public Version Version { get { if(_version == null) { _version = _assemblyDefinition.Version; } return _version; } } public CilModuleDefinition ModuleDefinition { get { if (!_isModuleInitialized) { _isModuleInitialized = true; _moduleDefinition = CilModuleDefinition.Create(_readers.MdReader.GetModuleDefinition(), ref _readers); } return _moduleDefinition; } } public CilHeaderOptions HeaderOptions { get { if (!_isHeaderInitialized) { _isHeaderInitialized = true; _headerOptions = CilHeaderOptions.Create(ref _readers); } return _headerOptions; } } /// <summary> /// A binary object representing a public encryption key for a strong-named assembly. /// Represented as a byte array on a string format (00 00 00 00 00 00 00 00 00) /// </summary> public byte[] PublicKey { get { if (_publicKey == null) { _publicKey = _readers.MdReader.GetBlobBytes(_assemblyDefinition.PublicKey); } return _publicKey; } } public bool HasPublicKey { get { return PublicKey.Length != 0; } } public bool HasCulture { get { return !_assemblyDefinition.Culture.IsNil; } } public bool IsDll { get { return _readers.PEReader.PEHeaders.IsDll; } } public bool IsExe { get { return _readers.PEReader.PEHeaders.IsExe; } } /// <summary> /// Assembly flags if it is strong named, whether the JIT tracking and optimization is enabled, and if the assembly can be retargeted at run time to a different assembly version. /// </summary> public string Flags { get { if (_assemblyDefinition.Flags.HasFlag(AssemblyFlags.Retargetable)) { return "retargetable "; } return string.Empty; } } /// <summary> /// The type definitions contained on the current assembly. /// </summary> public IEnumerable<CilTypeDefinition> TypeDefinitions { get { if (_typeDefinitions == null) { _typeDefinitions = GetTypeDefinitions(); } return _typeDefinitions.AsEnumerable<CilTypeDefinition>(); } } public IEnumerable<CilTypeReference> TypeReferences { get { if(_typeReferences == null) { _typeReferences = GetTypeReferences(); } return _typeReferences; } } public IEnumerable<CilAssemblyReference> AssemblyReferences { get { if(_assemblyReferences == null) { _assemblyReferences = GetAssemblyReferences(); } return _assemblyReferences; } } public IEnumerable<CilModuleReference> ModuleReferences { get { if(_moduleReferences == null) { _moduleReferences = GetModuleReferences(); } return _moduleReferences; } } public IEnumerable<CilCustomAttribute> CustomAttributes { get { if(_customAttribues == null) { _customAttribues = GetCustomAttributes(); } return _customAttribues; } } public string GetPublicKeyString() { if (!HasPublicKey) return string.Empty; return CilDecoder.CreateByteArrayString(PublicKey); } /// <summary> /// Method to get the hash algorithm formatted in the MSIL syntax. /// </summary> /// <returns>string representing the hash algorithm.</returns> public string GetFormattedHashAlgorithm() { return String.Format("0x{0:x8}", HashAlgorithm); } /// <summary> /// Method to get the version formatted to the MSIL syntax. MajorVersion:MinorVersion:BuildVersion:RevisionVersion. /// </summary> /// <returns>string representing the version.</returns> public string GetFormattedVersion() { return CilDecoder.CreateVersionString(Version); } public void WriteTo(TextWriter writer) { this.Accept(new CilToStringVisitor(new CilVisitorOptions(true), writer)); } public void Accept(ICilVisitor visitor) { visitor.Visit(this); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region Private Methods private void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _readers.Dispose(); } _disposed = true; } } private IEnumerable<CilTypeDefinition> GetTypeDefinitions() { var handles = _readers.MdReader.TypeDefinitions; foreach(var handle in handles) { if (handle.IsNil) { continue; } var typeDefinition = _readers.MdReader.GetTypeDefinition(handle); if(typeDefinition.GetDeclaringType().IsNil) yield return CilTypeDefinition.Create(typeDefinition, ref _readers, MetadataTokens.GetToken(handle)); } } private IEnumerable<CilTypeReference> GetTypeReferences() { var handles = _readers.MdReader.TypeReferences; foreach(var handle in handles) { var typeReference = _readers.MdReader.GetTypeReference(handle); yield return CilTypeReference.Create(typeReference, ref _readers, MetadataTokens.GetToken(handle)); } } private IEnumerable<CilAssemblyReference> GetAssemblyReferences() { foreach(var handle in _readers.MdReader.AssemblyReferences) { var assembly = _readers.MdReader.GetAssemblyReference(handle); int token = MetadataTokens.GetToken(handle); yield return CilAssemblyReference.Create(assembly, token, ref _readers, this); } } private IEnumerable<CilCustomAttribute> GetCustomAttributes() { foreach(var handle in _assemblyDefinition.GetCustomAttributes()) { var attribute = _readers.MdReader.GetCustomAttribute(handle); yield return new CilCustomAttribute(attribute, ref _readers); } } private IEnumerable<CilModuleReference> GetModuleReferences() { for(int rid = 1, rowCount = _readers.MdReader.GetTableRowCount(TableIndex.ModuleRef); rid <= rowCount; rid++) { var handle = MetadataTokens.ModuleReferenceHandle(rid); var moduleReference = _readers.MdReader.GetModuleReference(handle); int token = MetadataTokens.GetToken(handle); yield return CilModuleReference.Create(moduleReference, ref _readers, token); } } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using HtcSharp.HttpModule.Core.Internal; using HtcSharp.HttpModule.Http.Abstractions; using HtcSharp.HttpModule.Shared.CertificateGeneration; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace HtcSharp.HttpModule.Core { // SourceTools-Start // Remote-File C:\ASP\src\Servers\Kestrel\Core\src\KestrelServerOptions.cs // Start-At-Remote-Line 19 // SourceTools-End /// <summary> /// Provides programmatic configuration of Kestrel-specific features. /// </summary> public class KestrelServerOptions { /// <summary> /// Configures the endpoints that Kestrel should listen to. /// </summary> /// <remarks> /// If this list is empty, the server.urls setting (e.g. UseUrls) is used. /// </remarks> internal List<ListenOptions> ListenOptions { get; } = new List<ListenOptions>(); /// <summary> /// Gets or sets whether the <c>Server</c> header should be included in each response. /// </summary> /// <remarks> /// Defaults to true. /// </remarks> public bool AddServerHeader { get; set; } = true; /// <summary> /// Gets or sets a value that controls whether synchronous IO is allowed for the <see cref="HttpContext.Request"/> and <see cref="HttpContext.Response"/> /// </summary> /// <remarks> /// Defaults to false. /// </remarks> public bool AllowSynchronousIO { get; set; } = false; /// <summary> /// Gets or sets a value that controls whether the string values materialized /// will be reused across requests; if they match, or if the strings will always be reallocated. /// </summary> /// <remarks> /// Defaults to false. /// </remarks> public bool DisableStringReuse { get; set; } = false; /// <summary> /// Enables the Listen options callback to resolve and use services registered by the application during startup. /// Typically initialized by UseKestrel()"/>. /// </summary> public IServiceProvider ApplicationServices { get; set; } /// <summary> /// Provides access to request limit options. /// </summary> public KestrelServerLimits Limits { get; } = new KestrelServerLimits(); /// <summary> /// Provides a configuration source where endpoints will be loaded from on server start. /// The default is null. /// </summary> public KestrelConfigurationLoader ConfigurationLoader { get; set; } /// <summary> /// A default configuration action for all endpoints. Use for Listen, configuration, the default url, and URLs. /// </summary> private Action<ListenOptions> EndpointDefaults { get; set; } = _ => { }; /// <summary> /// A default configuration action for all https endpoints. /// </summary> private Action<HttpsConnectionAdapterOptions> HttpsDefaults { get; set; } = _ => { }; /// <summary> /// The default server certificate for https endpoints. This is applied lazily after HttpsDefaults and user options. /// </summary> internal X509Certificate2 DefaultCertificate { get; set; } /// <summary> /// Has the default dev certificate load been attempted? /// </summary> internal bool IsDevCertLoaded { get; set; } /// <summary> /// Treat request headers as Latin-1 or ISO/IEC 8859-1 instead of UTF-8. /// </summary> internal bool Latin1RequestHeaders { get; set; } /// <summary> /// Specifies a configuration Action to run for each newly created endpoint. Calling this again will replace /// the prior action. /// </summary> public void ConfigureEndpointDefaults(Action<ListenOptions> configureOptions) { EndpointDefaults = configureOptions ?? throw new ArgumentNullException(nameof(configureOptions)); } internal void ApplyEndpointDefaults(ListenOptions listenOptions) { listenOptions.KestrelServerOptions = this; ConfigurationLoader?.ApplyConfigurationDefaults(listenOptions); EndpointDefaults(listenOptions); } /// <summary> /// Specifies a configuration Action to run for each newly created https endpoint. Calling this again will replace /// the prior action. /// </summary> public void ConfigureHttpsDefaults(Action<HttpsConnectionAdapterOptions> configureOptions) { HttpsDefaults = configureOptions ?? throw new ArgumentNullException(nameof(configureOptions)); } internal void ApplyHttpsDefaults(HttpsConnectionAdapterOptions httpsOptions) { HttpsDefaults(httpsOptions); } internal void ApplyDefaultCert(HttpsConnectionAdapterOptions httpsOptions) { if (httpsOptions.ServerCertificate != null || httpsOptions.ServerCertificateSelector != null) { return; } EnsureDefaultCert(); httpsOptions.ServerCertificate = DefaultCertificate; } private void EnsureDefaultCert() { if (DefaultCertificate == null && !IsDevCertLoaded) { IsDevCertLoaded = true; // Only try once var logger = ApplicationServices.GetRequiredService<ILogger<KestrelServer>>(); try { DefaultCertificate = CertificateManager.ListCertificates(CertificatePurpose.HTTPS, StoreName.My, StoreLocation.CurrentUser, isValid: true) .FirstOrDefault(); if (DefaultCertificate != null) { logger.LocatedDevelopmentCertificate(DefaultCertificate); } else { logger.UnableToLocateDevelopmentCertificate(); } } catch { logger.UnableToLocateDevelopmentCertificate(); } } } /// <summary> /// Creates a configuration loader for setting up Kestrel. /// </summary> public KestrelConfigurationLoader Configure() { var loader = new KestrelConfigurationLoader(this, new ConfigurationBuilder().Build()); ConfigurationLoader = loader; return loader; } /// <summary> /// Creates a configuration loader for setting up Kestrel that takes an IConfiguration as input. /// This configuration must be scoped to the configuration section for Kestrel. /// </summary> public KestrelConfigurationLoader Configure(IConfiguration config) { var loader = new KestrelConfigurationLoader(this, config); ConfigurationLoader = loader; return loader; } /// <summary> /// Bind to given IP address and port. /// </summary> public void Listen(IPAddress address, int port) { Listen(address, port, _ => { }); } /// <summary> /// Bind to given IP address and port. /// The callback configures endpoint-specific settings. /// </summary> public void Listen(IPAddress address, int port, Action<ListenOptions> configure) { if (address == null) { throw new ArgumentNullException(nameof(address)); } Listen(new IPEndPoint(address, port), configure); } /// <summary> /// Bind to given IP endpoint. /// </summary> public void Listen(IPEndPoint endPoint) { Listen(endPoint, _ => { }); } /// <summary> /// Bind to given IP address and port. /// The callback configures endpoint-specific settings. /// </summary> public void Listen(IPEndPoint endPoint, Action<ListenOptions> configure) { if (endPoint == null) { throw new ArgumentNullException(nameof(endPoint)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var listenOptions = new ListenOptions(endPoint); ApplyEndpointDefaults(listenOptions); configure(listenOptions); ListenOptions.Add(listenOptions); } /// <summary> /// Listens on ::1 and 127.0.0.1 with the given port. Requesting a dynamic port by specifying 0 is not supported /// for this type of endpoint. /// </summary> public void ListenLocalhost(int port) => ListenLocalhost(port, options => { }); /// <summary> /// Listens on ::1 and 127.0.0.1 with the given port. Requesting a dynamic port by specifying 0 is not supported /// for this type of endpoint. /// </summary> public void ListenLocalhost(int port, Action<ListenOptions> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var listenOptions = new LocalhostListenOptions(port); ApplyEndpointDefaults(listenOptions); configure(listenOptions); ListenOptions.Add(listenOptions); } /// <summary> /// Listens on all IPs using IPv6 [::], or IPv4 0.0.0.0 if IPv6 is not supported. /// </summary> public void ListenAnyIP(int port) => ListenAnyIP(port, options => { }); /// <summary> /// Listens on all IPs using IPv6 [::], or IPv4 0.0.0.0 if IPv6 is not supported. /// </summary> public void ListenAnyIP(int port, Action<ListenOptions> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var listenOptions = new AnyIPListenOptions(port); ApplyEndpointDefaults(listenOptions); configure(listenOptions); ListenOptions.Add(listenOptions); } /// <summary> /// Bind to given Unix domain socket path. /// </summary> public void ListenUnixSocket(string socketPath) { ListenUnixSocket(socketPath, _ => { }); } /// <summary> /// Bind to given Unix domain socket path. /// Specify callback to configure endpoint-specific settings. /// </summary> public void ListenUnixSocket(string socketPath, Action<ListenOptions> configure) { if (socketPath == null) { throw new ArgumentNullException(nameof(socketPath)); } if (!Path.IsPathRooted(socketPath)) { throw new ArgumentException(CoreStrings.UnixSocketPathMustBeAbsolute, nameof(socketPath)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var listenOptions = new ListenOptions(socketPath); ApplyEndpointDefaults(listenOptions); configure(listenOptions); ListenOptions.Add(listenOptions); } /// <summary> /// Open a socket file descriptor. /// </summary> public void ListenHandle(ulong handle) { ListenHandle(handle, _ => { }); } /// <summary> /// Open a socket file descriptor. /// The callback configures endpoint-specific settings. /// </summary> public void ListenHandle(ulong handle, Action<ListenOptions> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var listenOptions = new ListenOptions(handle); ApplyEndpointDefaults(listenOptions); configure(listenOptions); ListenOptions.Add(listenOptions); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Text; namespace ALinq.SqlClient { internal partial class ObjectReaderCompiler { private class Rereader : DbDataReader { // Fields private bool first; private readonly string[] names; private readonly DbDataReader reader; // Methods internal Rereader(DbDataReader reader) : this(reader, false, null) { } internal Rereader(DbDataReader reader, bool hasCurrentRow, string[] names) { this.reader = reader; first = hasCurrentRow; this.names = names; } public override void Close() { } public override bool GetBoolean(int i) { return reader.GetBoolean(i); } public override byte GetByte(int i) { return reader.GetByte(i); } public override long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferOffset, int length) { return reader.GetBytes(i, fieldOffset, buffer, bufferOffset, length); } public override char GetChar(int i) { return reader.GetChar(i); } public override long GetChars(int i, long fieldOffset, char[] buffer, int bufferOffset, int length) { return reader.GetChars(i, fieldOffset, buffer, bufferOffset, length); } public override string GetDataTypeName(int i) { return reader.GetDataTypeName(i); } public override DateTime GetDateTime(int i) { return reader.GetDateTime(i); } public override decimal GetDecimal(int i) { return reader.GetDecimal(i); } public override double GetDouble(int i) { return reader.GetDouble(i); } public override IEnumerator GetEnumerator() { return reader.GetEnumerator(); } public override Type GetFieldType(int i) { return reader.GetFieldType(i); } public override float GetFloat(int i) { return reader.GetFloat(i); } public override Guid GetGuid(int i) { return reader.GetGuid(i); } public override short GetInt16(int i) { return reader.GetInt16(i); } public override int GetInt32(int i) { return reader.GetInt32(i); } public override long GetInt64(int i) { return reader.GetInt64(i); } public override string GetName(int i) { if (names != null) { return names[i]; } return reader.GetName(i); } public override int GetOrdinal(string name) { return reader.GetOrdinal(name); } public override DataTable GetSchemaTable() { return reader.GetSchemaTable(); } public override string GetString(int i) { return reader.GetString(i); } public override object GetValue(int i) { return reader.GetValue(i); } public override int GetValues(object[] values) { return reader.GetValues(values); } public override bool IsDBNull(int i) { return reader.IsDBNull(i); } public override bool NextResult() { return false; } public override bool Read() { if (first) { first = false; return true; } return reader.Read(); } // Properties public override int Depth { get { return reader.Depth; } } public override int FieldCount { get { return reader.FieldCount; } } public override bool HasRows { get { if (!first) { return reader.HasRows; } return true; } } public override bool IsClosed { get { return reader.IsClosed; } } public override object this[string name] { get { return reader[name]; } } public override object this[int i] { get { return reader[i]; } } public override int RecordsAffected { get { return reader.RecordsAffected; } } } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using Encog.ML.Data; using Encog.ML.Factory.Train; using Encog.ML.Train; using Encog.Plugin; namespace Encog.ML.Factory { /// <summary> /// This factory is used to create trainers for machine learning methods. /// </summary> /// public class MLTrainFactory { /// <summary> /// The maximum number of parents for K2. /// </summary> public const string PropertyMaxParents = "MAXPARENTS"; ///<summary> /// The number of particles. ///</summary> public const String PropertyParticles = "PARTICLES"; /// <summary> /// Nelder Mead training for Bayesian. /// </summary> public const String TypeNelderMead = "nm"; /// <summary> /// K2 training for Bayesian. /// </summary> public const String TypeBayesian = "bayesian"; /// <summary> /// PSO training. /// </summary> public const String TypePSO = "pso"; /// <summary> /// String constant for RPROP training. /// </summary> /// public const String TypeRPROP = "rprop"; /// <summary> /// String constant for RPROP training. /// </summary> /// public const String TypeQPROP = "qprop"; /// <summary> /// String constant for backprop training. /// </summary> /// public const String TypeBackprop = "backprop"; /// <summary> /// String constant for SCG training. /// </summary> /// public const String TypeSCG = "scg"; /// <summary> /// String constant for LMA training. /// </summary> /// public const String TypeLma = "lma"; /// <summary> /// String constant for SVM training. /// </summary> /// public const String TypeSVM = "svm-train"; /// <summary> /// String constant for SVM-Search training. /// </summary> /// public const String TypeSVMSearch = "svm-search"; /// <summary> /// String constant for SOM-Neighborhood training. /// </summary> /// public const String TypeSOMNeighborhood = "som-neighborhood"; /// <summary> /// String constant for SOM-Cluster training. /// </summary> /// public const String TypeSOMCluster = "som-cluster"; /// <summary> /// String constant for LMA training. /// </summary> public const String TypeNEATGA = "neat-ga"; /// <summary> /// String constant for LMA training. /// </summary> public const String TypeEPLGA = "epl-ga"; /// <summary> /// Property for learning rate. /// </summary> /// public const String PropertyLearningRate = "LR"; /// <summary> /// Property for momentum. /// </summary> /// public const String PropertyLearningMomentum = "MOM"; /// <summary> /// Property for init update. /// </summary> /// public const String PropertyInitialUpdate = "INIT_UPDATE"; /// <summary> /// Property for max step. /// </summary> /// public const String PropertyMaxStep = "MAX_STEP"; /// <summary> /// Property for bayes reg. /// </summary> /// public const String PropertyBayesianRegularization = "BAYES_REG"; /// <summary> /// Property for gamma. /// </summary> /// public const String PropertyGamma = "GAMMA"; /// <summary> /// Property for constant. /// </summary> /// public const String PropertyC = "C"; /// <summary> /// Property for neighborhood. /// </summary> /// public const String PropertyPropertyNeighborhood = "NEIGHBORHOOD"; /// <summary> /// Property for iterations. /// </summary> /// public const String PropertyIterations = "ITERATIONS"; /// <summary> /// Property for starting learning rate. /// </summary> /// public const String PropertyStartLearningRate = "START_LR"; /// <summary> /// Property for ending learning rate. /// </summary> /// public const String PropertyEndLearningRate = "END_LR"; /// <summary> /// Property for starting radius. /// </summary> /// public const String PropertyStartRadius = "START_RADIUS"; /// <summary> /// Property for ending radius. /// </summary> /// public const String PropertyEndRadius = "END_RADIUS"; /// <summary> /// Property for neighborhood. /// </summary> /// public const String PropertyNeighborhood = "NEIGHBORHOOD"; /// <summary> /// Property for rbf type. /// </summary> /// public const String PropertyRBFType = "RBF_TYPE"; /// <summary> /// Property for dimensions. /// </summary> /// public const String PropertyDimensions = "DIM"; /// <summary> /// The number of cycles. /// </summary> /// public const String Cycles = "cycles"; /// <summary> /// The starting temperature. /// </summary> /// public const String PropertyTemperatureStart = "startTemp"; /// <summary> /// The ending temperature. /// </summary> /// public const String PropertyTemperatureStop = "stopTemp"; /// <summary> /// Use simulated annealing. /// </summary> /// public const String TypeAnneal = "anneal"; /// <summary> /// Population size. /// </summary> /// public const String PropertyPopulationSize = "population"; /// <summary> /// Percent to mutate. /// </summary> /// public const String PropertyMutation = "mutate"; /// <summary> /// Percent to mate. /// </summary> /// public const String PropertyMate = "mate"; /// <summary> /// Genetic training. /// </summary> /// public const String TypeGenetic = "genetic"; /// <summary> /// Manhattan training. /// </summary> /// public const String TypeManhattan = "manhattan"; /// <summary> /// RBF-SVD training. /// </summary> /// public const String TypeSvd = "rbf-svd"; /// <summary> /// PNN training. /// </summary> /// public const String TypePNN = "pnn"; /// <summary> /// Construct the boject. /// </summary> public MLTrainFactory() { } /// <summary> /// Create a trainer. /// </summary> /// /// <param name="method">The method to train.</param> /// <param name="training">The training data.</param> /// <param name="type">Type type of trainer.</param> /// <param name="args">The training args.</param> /// <returns>The new training method.</returns> public IMLTrain Create(IMLMethod method, IMLDataSet training, String type, String args) { foreach (EncogPluginBase plugin in EncogFramework.Instance.Plugins) { if (plugin is IEncogPluginService1) { IMLTrain result = ((IEncogPluginService1)plugin).CreateTraining( method, training, type, args); if (result != null) { return result; } } } throw new EncogError("Unknown training type: " + type); } } }
using System; using System.IO; using System.Linq; using System.Text; using System.Diagnostics; using System.Collections.Generic; using System.Threading; namespace AutoTest.CoreExtensions { public static class ProcessExtensions { private static Action<string> _logger = (msg) => {}; public static void SetLogger(this Process proc, Action<string> logger) { _logger = logger; } public static Func<string,string> GetInterpreter = (file) => null; public static void Write(this Process proc, string msg) { try { proc.StandardInput.WriteLine(msg); proc.StandardInput.Flush(); } catch { } } public static void Run(this Process proc, string command, string arguments, bool visible, string workingDir) { Run(proc, command, arguments, visible, workingDir, new KeyValuePair<string,string>[] {}); } public static void Run(this Process proc, string command, string arguments, bool visible, string workingDir, IEnumerable<KeyValuePair<string,string>> replacements) { arguments = replaceArgumentPlaceholders(arguments, replacements); prepareProcess(proc, command, arguments, visible, workingDir); proc.Start(); proc.WaitForExit(); } public static void Spawn(this Process proc, string command, string arguments, bool visible, string workingDir) { Spawn(proc, command, arguments, visible, workingDir, new KeyValuePair<string,string>[] {}); } public static void Spawn(this Process proc, string command, string arguments, bool visible, string workingDir, IEnumerable<KeyValuePair<string,string>> replacements) { arguments = replaceArgumentPlaceholders(arguments, replacements); prepareProcess(proc, command, arguments, visible, workingDir); proc.Start(); } public static IEnumerable<string> QueryAll(this Process proc, string command, string arguments, bool visible, string workingDir, out string[] errors) { return QueryAll(proc, command, arguments, visible, workingDir, new KeyValuePair<string,string>[] {}, out errors); } public static IEnumerable<string> QueryAll(this Process proc, string command, string arguments, bool visible, string workingDir, IEnumerable<KeyValuePair<string,string>> replacements, out string[] errors) { errors = new string[] {}; arguments = replaceArgumentPlaceholders(arguments, replacements); prepareProcess(proc, command, arguments, visible, workingDir); proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.Start(); var output = proc.StandardOutput.ReadToEnd(); errors = proc.StandardError.ReadToEnd() .Split(new[] { Environment.NewLine }, StringSplitOptions.None); proc.WaitForExit(); return output.Split(new[] { Environment.NewLine }, StringSplitOptions.None); } public static void Query(this Process proc, string command, string arguments, bool visible, string workingDir, Action<bool, string> onRecievedLine) { Query(proc, command, arguments, visible, workingDir, onRecievedLine, new KeyValuePair<string,string>[] {}); } public static void Query(this Process proc, string command, string arguments, bool visible, string workingDir, Action<bool, string> onRecievedLine, IEnumerable<KeyValuePair<string,string>> replacements) { _logger("Running process"); var process = proc; var retries = 0; var exitCode = 255; _logger("About to start process"); while (exitCode == 255 && retries < 5) { _logger("Running query"); exitCode = query(process, command, arguments, visible, workingDir, onRecievedLine, replacements); _logger("Done running with " + exitCode.ToString()); retries++; // Seems to happen on linux when a file is beeing executed while being modified (locked) if (exitCode == 255) { _logger("Recreating process"); process = new Process(); Thread.Sleep(100); } _logger("Done running process"); } } private static int query(this Process proc, string command, string arguments, bool visible, string workingDir, Action<bool, string> onRecievedLine, IEnumerable<KeyValuePair<string,string>> replacements) { string tempFile = null; arguments = replaceArgumentPlaceholders(arguments, replacements); if (Environment.OSVersion.Platform != PlatformID.Unix && Environment.OSVersion.Platform != PlatformID.MacOSX) { if (Path.GetExtension(command).ToLower() != ".exe") { arguments = getBatchArguments(command, arguments, ref tempFile); command = "cmd.exe"; } } prepareProcess(proc, command, arguments, visible, workingDir); proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; DataReceivedEventHandler onOutputLine = (s, data) => { if (data.Data != null) onRecievedLine(false, data.Data); }; DataReceivedEventHandler onErrorLine = (s, data) => { if (data.Data != null) onRecievedLine(true, data.Data); }; proc.OutputDataReceived += onOutputLine; proc.ErrorDataReceived += onErrorLine; if (proc.Start()) { proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.WaitForExit(); } proc.OutputDataReceived -= onOutputLine; proc.ErrorDataReceived -= onErrorLine; if (tempFile != null && File.Exists(tempFile)) File.Delete(tempFile); return proc.ExitCode; } private static bool processExists(int id) { return Process.GetProcesses().Any(x => x.Id == id); } private static string getBatchArguments(string command, string arguments, ref string tempFile) { var illagalChars = new[] {"&", "<", ">", "(", ")", "@", "^", "|"}; if (command.Contains(" ") || illagalChars.Any(x => arguments.Contains(x))) { // Windows freaks when getting the | character // Have it run a temporary bat file with command as contents tempFile = Path.GetTempFileName() + ".bat"; if (File.Exists(tempFile)) File.Delete(tempFile); File.WriteAllText(tempFile, "\"" + command + "\" " + arguments); arguments = "/c " + tempFile; } else { arguments = "/c " + "^\"" + batchEscape(command) + "^\" " + batchEscape(arguments); } return arguments; } private static string batchEscape(string text) { foreach (var str in new[] { "^", " ", "&", "(", ")", "[", "]", "{", "}", "=", ";", "!", "'", "+", ",", "`", "~", "\"" }) text = text.Replace(str, "^" + str); return text; } private static string replaceArgumentPlaceholders(string arg, IEnumerable<KeyValuePair<string,string>> replacements) { foreach (var replacement in replacements) arg = arg.Replace(replacement.Key, replacement.Value); return arg; } private static void prepareProcess( Process proc, string command, string arguments, bool visible, string workingDir) { var info = new ProcessStartInfo(command, arguments); info.CreateNoWindow = !visible; if (!visible) info.WindowStyle = ProcessWindowStyle.Hidden; info.WorkingDirectory = workingDir; proc.StartInfo = info; } } }
using System; using System.IO; using System.Collections.Generic; using System.Threading; using DarkMultiPlayerCommon; namespace DarkMultiPlayer { public class UniverseSyncCache { private static UniverseSyncCache singleton = new UniverseSyncCache(); public string cacheDirectory { get { return Path.Combine(Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), "DarkMultiPlayer"), "Cache"); } } private AutoResetEvent incomingEvent = new AutoResetEvent(false); private Queue<byte[]> incomingQueue = new Queue<byte[]>(); private Dictionary<string, long> fileLengths = new Dictionary<string, long>(); private Dictionary<string, DateTime> fileCreationTimes = new Dictionary<string, DateTime>(); public long currentCacheSize { get; private set; } public UniverseSyncCache() { Thread processingThread = new Thread(new ThreadStart(ProcessingThreadMain)); processingThread.IsBackground = true; processingThread.Start(); } public static UniverseSyncCache fetch { get { return singleton; } } private void ProcessingThreadMain() { while (true) { if (incomingQueue.Count == 0) { incomingEvent.WaitOne(500); } else { byte[] incomingBytes; lock (incomingQueue) { incomingBytes = incomingQueue.Dequeue(); } SaveToCache(incomingBytes); } } } private string[] GetCachedFiles() { return Directory.GetFiles(cacheDirectory); } public string[] GetCachedObjects() { string[] cacheFiles = GetCachedFiles(); string[] cacheObjects = new string[cacheFiles.Length]; for (int i = 0; i < cacheFiles.Length; i++) { cacheObjects[i] = Path.GetFileNameWithoutExtension(cacheFiles[i]); } return cacheObjects; } public void ExpireCache() { DarkLog.Debug("Expiring cache!"); //No folder, no delete. if (!Directory.Exists(Path.Combine(cacheDirectory, "Incoming"))) { DarkLog.Debug("No sync cache folder, skipping expire."); return; } //Delete partial incoming files string[] incomingFiles = Directory.GetFiles(Path.Combine(cacheDirectory, "Incoming")); foreach (string incomingFile in incomingFiles) { DarkLog.Debug("Deleting partially cached object " + incomingFile); File.Delete(incomingFile); } //Delete old files string[] cacheObjects = GetCachedObjects(); currentCacheSize = 0; foreach (string cacheObject in cacheObjects) { if (!string.IsNullOrEmpty(cacheObject)) { string cacheFile = Path.Combine(cacheDirectory, cacheObject + ".txt"); //If the file is older than a week, delete it. if (File.GetCreationTime(cacheFile).AddDays(7d) < DateTime.Now) { DarkLog.Debug("Deleting cached object " + cacheObject + ", reason: Expired!"); File.Delete(cacheFile); } else { FileInfo fi = new FileInfo(cacheFile); fileCreationTimes[cacheObject] = fi.CreationTime; fileLengths[cacheObject] = fi.Length; currentCacheSize += fi.Length; } } } //While the directory is over (cacheSize) MB while (currentCacheSize > (Settings.fetch.cacheSize * 1024 * 1024)) { string deleteObject = null; //Find oldest file foreach (KeyValuePair<string, DateTime> testFile in fileCreationTimes) { if (deleteObject == null) { deleteObject = testFile.Key; } if (testFile.Value < fileCreationTimes[deleteObject]) { deleteObject = testFile.Key; } } DarkLog.Debug("Deleting cached object " + deleteObject + ", reason: Cache full!"); string deleteFile = Path.Combine(cacheDirectory, deleteObject + ".txt"); File.Delete(deleteFile); currentCacheSize -= fileLengths[deleteObject]; if (fileCreationTimes.ContainsKey(deleteObject)) { fileCreationTimes.Remove(deleteObject); } if (fileLengths.ContainsKey(deleteObject)) { fileLengths.Remove(deleteObject); } } } /// <summary> /// Queues to cache. This method is non-blocking, using SaveToCache for a blocking method. /// </summary> /// <param name="fileData">File data.</param> public void QueueToCache(byte[] fileData) { lock (incomingQueue) { incomingQueue.Enqueue(fileData); } incomingEvent.Set(); } /// <summary> /// Saves to cache. This method is blocking, use QueueToCache for a non-blocking method. /// </summary> /// <param name="fileData">File data.</param> public void SaveToCache(byte[] fileData) { if (fileData == null || fileData.Length == 0) { //Don't save 0 byte data. return; } string objectName = Common.CalculateSHA256Hash(fileData); string objectFile = Path.Combine(cacheDirectory, objectName + ".txt"); string incomingFile = Path.Combine(Path.Combine(cacheDirectory, "Incoming"), objectName + ".txt"); if (!File.Exists(objectFile)) { File.WriteAllBytes(incomingFile, fileData); File.Move(incomingFile, objectFile); currentCacheSize += fileData.Length; fileLengths[objectName] = fileData.Length; fileCreationTimes[objectName] = new FileInfo(objectFile).CreationTime; } else { File.SetCreationTime(objectFile, DateTime.Now); fileCreationTimes[objectName] = new FileInfo(objectFile).CreationTime; } } public byte[] GetFromCache(string objectName) { string objectFile = Path.Combine(cacheDirectory, objectName + ".txt"); if (File.Exists(objectFile)) { return File.ReadAllBytes(objectFile); } else { throw new IOException("Cached object " + objectName + " does not exist"); } } public void DeleteCache() { DarkLog.Debug("Deleting cache!"); foreach (string cacheFile in GetCachedFiles()) { File.Delete(cacheFile); } fileLengths = new Dictionary<string, long>(); fileCreationTimes = new Dictionary<string, DateTime>(); currentCacheSize = 0; } } }
// 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.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.InlineTemporary { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InlineTemporary), Shared] internal partial class InlineTemporaryCodeRefactoringProvider : CodeRefactoringProvider { internal static readonly SyntaxAnnotation DefinitionAnnotation = new SyntaxAnnotation(); internal static readonly SyntaxAnnotation ReferenceAnnotation = new SyntaxAnnotation(); internal static readonly SyntaxAnnotation InitializerAnnotation = new SyntaxAnnotation(); internal static readonly SyntaxAnnotation ExpressionToInlineAnnotation = new SyntaxAnnotation(); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var document = context.Document; var textSpan = context.Span; var cancellationToken = context.CancellationToken; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(textSpan.Start); if (!token.Span.Contains(textSpan)) { return; } var node = token.Parent; if (!node.IsKind(SyntaxKind.VariableDeclarator) || !node.IsParentKind(SyntaxKind.VariableDeclaration) || !node.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement)) { return; } var variableDeclarator = (VariableDeclaratorSyntax)node; var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent; var localDeclarationStatement = (LocalDeclarationStatementSyntax)variableDeclaration.Parent; if (variableDeclarator.Identifier != token || variableDeclarator.Initializer == null || variableDeclarator.Initializer.Value.IsMissing || variableDeclarator.Initializer.Value.IsKind(SyntaxKind.StackAllocArrayCreationExpression)) { return; } if (localDeclarationStatement.ContainsDiagnostics) { return; } var references = await GetReferencesAsync(document, variableDeclarator, cancellationToken).ConfigureAwait(false); if (!references.Any()) { return; } context.RegisterRefactoring( new MyCodeAction( CSharpFeaturesResources.InlineTemporaryVariable, (c) => this.InlineTemporaryAsync(document, variableDeclarator, c))); } private async Task<IEnumerable<ReferenceLocation>> GetReferencesAsync( Document document, VariableDeclaratorSyntax variableDeclarator, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var local = semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken); if (local != null) { var findReferencesResult = await SymbolFinder.FindReferencesAsync(local, document.Project.Solution, cancellationToken).ConfigureAwait(false); var locations = findReferencesResult.Single(r => r.Definition == local).Locations; if (!locations.Any(loc => semanticModel.SyntaxTree.OverlapsHiddenPosition(loc.Location.SourceSpan, cancellationToken))) { return locations; } } return SpecializedCollections.EmptyEnumerable<ReferenceLocation>(); } private static bool HasConflict(IdentifierNameSyntax identifier, VariableDeclaratorSyntax variableDeclarator) { // TODO: Check for more conflict types. if (identifier.SpanStart < variableDeclarator.SpanStart) { return true; } var identifierNode = identifier .Ancestors() .TakeWhile(n => n.Kind() == SyntaxKind.ParenthesizedExpression || n.Kind() == SyntaxKind.CastExpression) .LastOrDefault(); if (identifierNode == null) { identifierNode = identifier; } if (identifierNode.IsParentKind(SyntaxKind.Argument)) { var argument = (ArgumentSyntax)identifierNode.Parent; if (argument.RefOrOutKeyword.Kind() != SyntaxKind.None) { return true; } } else if (identifierNode.Parent.IsKind( SyntaxKind.PreDecrementExpression, SyntaxKind.PreIncrementExpression, SyntaxKind.PostDecrementExpression, SyntaxKind.PostIncrementExpression, SyntaxKind.AddressOfExpression)) { return true; } else if (identifierNode.Parent is AssignmentExpressionSyntax) { var binaryExpression = (AssignmentExpressionSyntax)identifierNode.Parent; if (binaryExpression.Left == identifierNode) { return true; } } return false; } private static SyntaxAnnotation CreateConflictAnnotation() { return ConflictAnnotation.Create(CSharpFeaturesResources.ConflictsDetected); } private async Task<Document> InlineTemporaryAsync(Document document, VariableDeclaratorSyntax declarator, CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; // Annotate the variable declarator so that we can get back to it later. var updatedDocument = await document.ReplaceNodeAsync(declarator, declarator.WithAdditionalAnnotations(DefinitionAnnotation), cancellationToken).ConfigureAwait(false); var semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var variableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false); // Create the expression that we're actually going to inline. var expressionToInline = await CreateExpressionToInlineAsync(variableDeclarator, updatedDocument, cancellationToken).ConfigureAwait(false); // Collect the identifier names for each reference. var local = (ILocalSymbol)semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken); var symbolRefs = await SymbolFinder.FindReferencesAsync(local, updatedDocument.Project.Solution, cancellationToken).ConfigureAwait(false); var references = symbolRefs.Single(r => r.Definition == local).Locations; var syntaxRoot = await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Collect the topmost parenting expression for each reference. var nonConflictingIdentifierNodes = references .Select(loc => (IdentifierNameSyntax)syntaxRoot.FindToken(loc.Location.SourceSpan.Start).Parent) .Where(ident => !HasConflict(ident, variableDeclarator)); // Add referenceAnnotations to identifier nodes being replaced. updatedDocument = await updatedDocument.ReplaceNodesAsync( nonConflictingIdentifierNodes, (o, n) => n.WithAdditionalAnnotations(ReferenceAnnotation), cancellationToken).ConfigureAwait(false); semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); variableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false); // Get the annotated reference nodes. nonConflictingIdentifierNodes = await FindReferenceAnnotatedNodesAsync(updatedDocument, cancellationToken).ConfigureAwait(false); var topmostParentingExpressions = nonConflictingIdentifierNodes .Select(ident => GetTopMostParentingExpression(ident)) .Distinct(); var originalInitializerSymbolInfo = semanticModel.GetSymbolInfo(variableDeclarator.Initializer.Value, cancellationToken); // Make each topmost parenting statement or Equals Clause Expressions semantically explicit. updatedDocument = await updatedDocument.ReplaceNodesAsync(topmostParentingExpressions, (o, n) => Simplifier.Expand(n, semanticModel, workspace, cancellationToken: cancellationToken), cancellationToken).ConfigureAwait(false); semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var semanticModelBeforeInline = semanticModel; variableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false); var scope = GetScope(variableDeclarator); var newScope = ReferenceRewriter.Visit(semanticModel, scope, variableDeclarator, expressionToInline, cancellationToken); updatedDocument = await updatedDocument.ReplaceNodeAsync(scope, newScope, cancellationToken).ConfigureAwait(false); semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); variableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false); newScope = GetScope(variableDeclarator); var conflicts = newScope.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind); var declaratorConflicts = variableDeclarator.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind); // Note that we only remove the local declaration if there weren't any conflicts, // unless those conflicts are inside the local declaration. if (conflicts.Count() == declaratorConflicts.Count()) { // Certain semantic conflicts can be detected only after the reference rewriter has inlined the expression var newDocument = await DetectSemanticConflicts(updatedDocument, semanticModel, semanticModelBeforeInline, originalInitializerSymbolInfo, cancellationToken).ConfigureAwait(false); if (updatedDocument == newDocument) { // No semantic conflicts, we can remove the definition. updatedDocument = await updatedDocument.ReplaceNodeAsync(newScope, RemoveDeclaratorFromScope(variableDeclarator, newScope), cancellationToken).ConfigureAwait(false); } else { // There were some semantic conflicts, don't remove the definition. updatedDocument = newDocument; } } return updatedDocument; } private static async Task<VariableDeclaratorSyntax> FindDeclaratorAsync(Document document, CancellationToken cancellationToken) { return await FindNodeWithAnnotationAsync<VariableDeclaratorSyntax>(document, DefinitionAnnotation, cancellationToken).ConfigureAwait(false); } private static async Task<ExpressionSyntax> FindInitializerAsync(Document document, CancellationToken cancellationToken) { return await FindNodeWithAnnotationAsync<ExpressionSyntax>(document, InitializerAnnotation, cancellationToken).ConfigureAwait(false); } private static async Task<T> FindNodeWithAnnotationAsync<T>(Document document, SyntaxAnnotation annotation, CancellationToken cancellationToken) where T : SyntaxNode { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return root .GetAnnotatedNodesAndTokens(annotation) .Single() .AsNode() as T; } private static async Task<IEnumerable<IdentifierNameSyntax>> FindReferenceAnnotatedNodesAsync(Document document, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return FindReferenceAnnotatedNodes(root); } private static IEnumerable<IdentifierNameSyntax> FindReferenceAnnotatedNodes(SyntaxNode root) { var annotatedNodesAndTokens = root.GetAnnotatedNodesAndTokens(ReferenceAnnotation); foreach (var nodeOrToken in annotatedNodesAndTokens) { if (nodeOrToken.IsNode && nodeOrToken.AsNode().IsKind(SyntaxKind.IdentifierName)) { yield return (IdentifierNameSyntax)nodeOrToken.AsNode(); } } } private SyntaxNode GetScope(VariableDeclaratorSyntax variableDeclarator) { var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent; var localDeclaration = (LocalDeclarationStatementSyntax)variableDeclaration.Parent; var scope = localDeclaration.Parent; while (scope.IsKind(SyntaxKind.LabeledStatement)) { scope = scope.Parent; } var parentExpressions = scope.AncestorsAndSelf().OfType<ExpressionSyntax>(); if (parentExpressions.Any()) { scope = parentExpressions.LastOrDefault().Parent; } return scope; } private VariableDeclaratorSyntax FindDeclarator(SyntaxNode node) { var annotatedNodesOrTokens = node.GetAnnotatedNodesAndTokens(DefinitionAnnotation).ToList(); Contract.Requires(annotatedNodesOrTokens.Count == 1, "Only a single variable declarator should have been annotated."); return (VariableDeclaratorSyntax)annotatedNodesOrTokens.First().AsNode(); } private SyntaxTriviaList GetTriviaToPreserve(SyntaxTriviaList syntaxTriviaList) { return ShouldPreserve(syntaxTriviaList) ? syntaxTriviaList : default(SyntaxTriviaList); } private static bool ShouldPreserve(SyntaxTriviaList trivia) { return trivia.Any( t => t.Kind() == SyntaxKind.SingleLineCommentTrivia || t.Kind() == SyntaxKind.MultiLineCommentTrivia || t.IsDirective); } private SyntaxNode RemoveDeclaratorFromVariableList(VariableDeclaratorSyntax variableDeclarator, VariableDeclarationSyntax variableDeclaration) { Debug.Assert(variableDeclaration.Variables.Count > 1); Debug.Assert(variableDeclaration.Variables.Contains(variableDeclarator)); var localDeclaration = (LocalDeclarationStatementSyntax)variableDeclaration.Parent; var scope = GetScope(variableDeclarator); var newLocalDeclaration = localDeclaration.RemoveNode(variableDeclarator, SyntaxRemoveOptions.KeepNoTrivia) .WithAdditionalAnnotations(Formatter.Annotation); return scope.ReplaceNode(localDeclaration, newLocalDeclaration); } private SyntaxNode RemoveDeclaratorFromScope(VariableDeclaratorSyntax variableDeclarator, SyntaxNode scope) { var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent; // If there is more than one variable declarator, remove this one from the variable declaration. if (variableDeclaration.Variables.Count > 1) { return RemoveDeclaratorFromVariableList(variableDeclarator, variableDeclaration); } var localDeclaration = (LocalDeclarationStatementSyntax)variableDeclaration.Parent; // There's only one variable declarator, so we'll remove the local declaration // statement entirely. This means that we'll concatenate the leading and trailing // trivia of this declaration and move it to the next statement. var leadingTrivia = localDeclaration .GetLeadingTrivia() .Reverse() .SkipWhile(t => t.MatchesKind(SyntaxKind.WhitespaceTrivia)) .Reverse() .ToSyntaxTriviaList(); var trailingTrivia = localDeclaration .GetTrailingTrivia() .SkipWhile(t => t.MatchesKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia)) .ToSyntaxTriviaList(); var newLeadingTrivia = leadingTrivia.Concat(trailingTrivia); var nextToken = localDeclaration.GetLastToken().GetNextTokenOrEndOfFile(); var newNextToken = nextToken.WithPrependedLeadingTrivia(newLeadingTrivia) .WithAdditionalAnnotations(Formatter.Annotation); var newScope = scope.ReplaceToken(nextToken, newNextToken); var newLocalDeclaration = (LocalDeclarationStatementSyntax)FindDeclarator(newScope).Parent.Parent; // If the local is parented by a label statement, we can't remove this statement. Instead, // we'll replace the local declaration with an empty expression statement. if (newLocalDeclaration.IsParentKind(SyntaxKind.LabeledStatement)) { var labeledStatement = (LabeledStatementSyntax)newLocalDeclaration.Parent; var newLabeledStatement = labeledStatement.ReplaceNode(newLocalDeclaration, SyntaxFactory.ParseStatement("")); return newScope.ReplaceNode(labeledStatement, newLabeledStatement); } return newScope.RemoveNode(newLocalDeclaration, SyntaxRemoveOptions.KeepNoTrivia); } private ExpressionSyntax SkipRedundantExteriorParentheses(ExpressionSyntax expression) { while (expression.IsKind(SyntaxKind.ParenthesizedExpression)) { var parenthesized = (ParenthesizedExpressionSyntax)expression; if (parenthesized.Expression == null || parenthesized.Expression.IsMissing) { break; } if (parenthesized.Expression.IsKind(SyntaxKind.ParenthesizedExpression) || parenthesized.Expression.IsKind(SyntaxKind.IdentifierName)) { expression = parenthesized.Expression; } else { break; } } return expression; } private async Task<ExpressionSyntax> CreateExpressionToInlineAsync( VariableDeclaratorSyntax variableDeclarator, Document document, CancellationToken cancellationToken) { var updatedDocument = document; var expression = SkipRedundantExteriorParentheses(variableDeclarator.Initializer.Value); var semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken); var newExpression = InitializerRewriter.Visit(expression, localSymbol, semanticModel); // If this is an array initializer, we need to transform it into an array creation // expression for inlining. if (newExpression.Kind() == SyntaxKind.ArrayInitializerExpression) { var arrayType = (ArrayTypeSyntax)localSymbol.Type.GenerateTypeSyntax(); var arrayInitializer = (InitializerExpressionSyntax)newExpression; // Add any non-whitespace trailing trivia from the equals clause to the type. var equalsToken = variableDeclarator.Initializer.EqualsToken; if (equalsToken.HasTrailingTrivia) { var trailingTrivia = equalsToken.TrailingTrivia.SkipInitialWhitespace(); if (trailingTrivia.Any()) { arrayType = arrayType.WithTrailingTrivia(trailingTrivia); } } newExpression = SyntaxFactory.ArrayCreationExpression(arrayType, arrayInitializer); } newExpression = newExpression.WithAdditionalAnnotations(InitializerAnnotation); updatedDocument = await updatedDocument.ReplaceNodeAsync(variableDeclarator.Initializer.Value, newExpression, cancellationToken).ConfigureAwait(false); semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); newExpression = await FindInitializerAsync(updatedDocument, cancellationToken).ConfigureAwait(false); var newVariableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false); localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(newVariableDeclarator, cancellationToken); bool wasCastAdded; var explicitCastExpression = newExpression.CastIfPossible(localSymbol.Type, newVariableDeclarator.SpanStart, semanticModel, out wasCastAdded); if (wasCastAdded) { updatedDocument = await updatedDocument.ReplaceNodeAsync(newExpression, explicitCastExpression, cancellationToken).ConfigureAwait(false); semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); newVariableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false); } // Now that the variable declarator is normalized, make its initializer // value semantically explicit. newExpression = await Simplifier.ExpandAsync(newVariableDeclarator.Initializer.Value, updatedDocument, cancellationToken: cancellationToken).ConfigureAwait(false); return newExpression.WithAdditionalAnnotations(ExpressionToInlineAnnotation); } private static SyntaxNode GetTopMostParentingExpression(ExpressionSyntax expression) { return expression.AncestorsAndSelf().OfType<ExpressionSyntax>().Last(); } private static async Task<Document> DetectSemanticConflicts( Document inlinedDocument, SemanticModel newSemanticModelForInlinedDocument, SemanticModel semanticModelBeforeInline, SymbolInfo originalInitializerSymbolInfo, CancellationToken cancellationToken) { // In this method we detect if inlining the expression introduced the following semantic change: // The symbol info associated with any of the inlined expressions does not match the symbol info for original initializer expression prior to inline. // If any semantic changes were introduced by inlining, we update the document with conflict annotations. // Otherwise we return the given inlined document without any changes. var syntaxRootBeforeInline = await semanticModelBeforeInline.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); // Get all the identifier nodes which were replaced with inlined expression. var originalIdentifierNodes = FindReferenceAnnotatedNodes(syntaxRootBeforeInline); if (originalIdentifierNodes.IsEmpty()) { // No conflicts return inlinedDocument; } // Get all the inlined expression nodes. var syntaxRootAfterInline = await inlinedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var inlinedExprNodes = syntaxRootAfterInline.GetAnnotatedNodesAndTokens(ExpressionToInlineAnnotation); Debug.Assert(originalIdentifierNodes.Count() == inlinedExprNodes.Count()); Dictionary<SyntaxNode, SyntaxNode> replacementNodesWithChangedSemantics = null; using (var originalNodesEnum = originalIdentifierNodes.GetEnumerator()) { using (var inlinedNodesOrTokensEnum = inlinedExprNodes.GetEnumerator()) { while (originalNodesEnum.MoveNext()) { inlinedNodesOrTokensEnum.MoveNext(); var originalNode = originalNodesEnum.Current; // expressionToInline is Parenthesized prior to replacement, so get the parenting parenthesized expression. var inlinedNode = (ExpressionSyntax)inlinedNodesOrTokensEnum.Current.Parent; Debug.Assert(inlinedNode.IsKind(SyntaxKind.ParenthesizedExpression)); // inlinedNode is the expanded form of the actual initializer expression in the original document. // We have annotated the inner initializer with a special syntax annotation "InitializerAnnotation". // Get this annotated node and compute the symbol info for this node in the inlined document. var innerInitializerInInlineNodeorToken = inlinedNode.GetAnnotatedNodesAndTokens(InitializerAnnotation).First(); ExpressionSyntax innerInitializerInInlineNode = (ExpressionSyntax)(innerInitializerInInlineNodeorToken.IsNode ? innerInitializerInInlineNodeorToken.AsNode() : innerInitializerInInlineNodeorToken.AsToken().Parent); var newInitializerSymbolInfo = newSemanticModelForInlinedDocument.GetSymbolInfo(innerInitializerInInlineNode, cancellationToken); // Verification: The symbol info associated with any of the inlined expressions does not match the symbol info for original initializer expression prior to inline. if (!SpeculationAnalyzer.SymbolInfosAreCompatible(originalInitializerSymbolInfo, newInitializerSymbolInfo, performEquivalenceCheck: true)) { newInitializerSymbolInfo = newSemanticModelForInlinedDocument.GetSymbolInfo(inlinedNode, cancellationToken); if (!SpeculationAnalyzer.SymbolInfosAreCompatible(originalInitializerSymbolInfo, newInitializerSymbolInfo, performEquivalenceCheck: true)) { if (replacementNodesWithChangedSemantics == null) { replacementNodesWithChangedSemantics = new Dictionary<SyntaxNode, SyntaxNode>(); } replacementNodesWithChangedSemantics.Add(inlinedNode, originalNode); } } } } } if (replacementNodesWithChangedSemantics == null) { // No conflicts. return inlinedDocument; } // Replace the conflicting inlined nodes with the original nodes annotated with conflict annotation. Func<SyntaxNode, SyntaxNode, SyntaxNode> conflictAnnotationAdder = (SyntaxNode oldNode, SyntaxNode newNode) => newNode.WithAdditionalAnnotations(ConflictAnnotation.Create(CSharpFeaturesResources.ConflictsDetected)); return await inlinedDocument.ReplaceNodesAsync(replacementNodesWithChangedSemantics.Keys, conflictAnnotationAdder, cancellationToken).ConfigureAwait(false); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument) { } } } }
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System; namespace Spine { internal class Triangulator { private readonly ExposedList<ExposedList<float>> convexPolygons = new ExposedList<ExposedList<float>>(); private readonly ExposedList<ExposedList<int>> convexPolygonsIndices = new ExposedList<ExposedList<int>>(); private readonly ExposedList<int> indicesArray = new ExposedList<int>(); private readonly ExposedList<bool> isConcaveArray = new ExposedList<bool>(); private readonly ExposedList<int> triangles = new ExposedList<int>(); private readonly Pool<ExposedList<float>> polygonPool = new Pool<ExposedList<float>>(); private readonly Pool<ExposedList<int>> polygonIndicesPool = new Pool<ExposedList<int>>(); public ExposedList<int> Triangulate (ExposedList<float> verticesArray) { var vertices = verticesArray.Items; int vertexCount = verticesArray.Count >> 1; var indicesArray = this.indicesArray; indicesArray.Clear(); int[] indices = indicesArray.Resize(vertexCount).Items; for (int i = 0; i < vertexCount; i++) indices[i] = i; var isConcaveArray = this.isConcaveArray; bool[] isConcave = isConcaveArray.Resize(vertexCount).Items; for (int i = 0, n = vertexCount; i < n; ++i) isConcave[i] = IsConcave(i, vertexCount, vertices, indices); var triangles = this.triangles; triangles.Clear(); triangles.EnsureCapacity(Math.Max(0, vertexCount - 2) << 2); while (vertexCount > 3) { // Find ear tip. int previous = vertexCount - 1, i = 0, next = 1; // outer: while (true) { if (!isConcave[i]) { int p1 = indices[previous] << 1, p2 = indices[i] << 1, p3 = indices[next] << 1; float p1x = vertices[p1], p1y = vertices[p1 + 1]; float p2x = vertices[p2], p2y = vertices[p2 + 1]; float p3x = vertices[p3], p3y = vertices[p3 + 1]; for (int ii = (next + 1) % vertexCount; ii != previous; ii = (ii + 1) % vertexCount) { if (!isConcave[ii]) continue; int v = indices[ii] << 1; float vx = vertices[v], vy = vertices[v + 1]; if (PositiveArea(p3x, p3y, p1x, p1y, vx, vy)) { if (PositiveArea(p1x, p1y, p2x, p2y, vx, vy)) { if (PositiveArea(p2x, p2y, p3x, p3y, vx, vy)) goto outer; // break outer; } } } break; } outer: if (next == 0) { do { if (!isConcave[i]) break; i--; } while (i > 0); break; } previous = i; i = next; next = (next + 1) % vertexCount; } // Cut ear tip. triangles.Add(indices[(vertexCount + i - 1) % vertexCount]); triangles.Add(indices[i]); triangles.Add(indices[(i + 1) % vertexCount]); indicesArray.RemoveAt(i); isConcaveArray.RemoveAt(i); vertexCount--; int previousIndex = (vertexCount + i - 1) % vertexCount; int nextIndex = i == vertexCount ? 0 : i; isConcave[previousIndex] = IsConcave(previousIndex, vertexCount, vertices, indices); isConcave[nextIndex] = IsConcave(nextIndex, vertexCount, vertices, indices); } if (vertexCount == 3) { triangles.Add(indices[2]); triangles.Add(indices[0]); triangles.Add(indices[1]); } return triangles; } public ExposedList<ExposedList<float>> Decompose (ExposedList<float> verticesArray, ExposedList<int> triangles) { var vertices = verticesArray.Items; var convexPolygons = this.convexPolygons; for (int i = 0, n = convexPolygons.Count; i < n; i++) { polygonPool.Free(convexPolygons.Items[i]); } convexPolygons.Clear(); var convexPolygonsIndices = this.convexPolygonsIndices; for (int i = 0, n = convexPolygonsIndices.Count; i < n; i++) { polygonIndicesPool.Free(convexPolygonsIndices.Items[i]); } convexPolygonsIndices.Clear(); var polygonIndices = polygonIndicesPool.Obtain(); polygonIndices.Clear(); var polygon = polygonPool.Obtain(); polygon.Clear(); // Merge subsequent triangles if they form a triangle fan. int fanBaseIndex = -1, lastWinding = 0; int[] trianglesItems = triangles.Items; for (int i = 0, n = triangles.Count; i < n; i += 3) { int t1 = trianglesItems[i] << 1, t2 = trianglesItems[i + 1] << 1, t3 = trianglesItems[i + 2] << 1; float x1 = vertices[t1], y1 = vertices[t1 + 1]; float x2 = vertices[t2], y2 = vertices[t2 + 1]; float x3 = vertices[t3], y3 = vertices[t3 + 1]; // If the base of the last triangle is the same as this triangle, check if they form a convex polygon (triangle fan). var merged = false; if (fanBaseIndex == t1) { int o = polygon.Count - 4; float[] p = polygon.Items; int winding1 = Winding(p[o], p[o + 1], p[o + 2], p[o + 3], x3, y3); int winding2 = Winding(x3, y3, p[0], p[1], p[2], p[3]); if (winding1 == lastWinding && winding2 == lastWinding) { polygon.Add(x3); polygon.Add(y3); polygonIndices.Add(t3); merged = true; } } // Otherwise make this triangle the new base. if (!merged) { if (polygon.Count > 0) { convexPolygons.Add(polygon); convexPolygonsIndices.Add(polygonIndices); } else { polygonPool.Free(polygon); polygonIndicesPool.Free(polygonIndices); } polygon = polygonPool.Obtain(); polygon.Clear(); polygon.Add(x1); polygon.Add(y1); polygon.Add(x2); polygon.Add(y2); polygon.Add(x3); polygon.Add(y3); polygonIndices = polygonIndicesPool.Obtain(); polygonIndices.Clear(); polygonIndices.Add(t1); polygonIndices.Add(t2); polygonIndices.Add(t3); lastWinding = Winding(x1, y1, x2, y2, x3, y3); fanBaseIndex = t1; } } if (polygon.Count > 0) { convexPolygons.Add(polygon); convexPolygonsIndices.Add(polygonIndices); } // Go through the list of polygons and try to merge the remaining triangles with the found triangle fans. for (int i = 0, n = convexPolygons.Count; i < n; i++) { polygonIndices = convexPolygonsIndices.Items[i]; if (polygonIndices.Count == 0) continue; int firstIndex = polygonIndices.Items[0]; int lastIndex = polygonIndices.Items[polygonIndices.Count - 1]; polygon = convexPolygons.Items[i]; int o = polygon.Count - 4; float[] p = polygon.Items; float prevPrevX = p[o], prevPrevY = p[o + 1]; float prevX = p[o + 2], prevY = p[o + 3]; float firstX = p[0], firstY = p[1]; float secondX = p[2], secondY = p[3]; int winding = Winding(prevPrevX, prevPrevY, prevX, prevY, firstX, firstY); for (int ii = 0; ii < n; ii++) { if (ii == i) continue; var otherIndices = convexPolygonsIndices.Items[ii]; if (otherIndices.Count != 3) continue; int otherFirstIndex = otherIndices.Items[0]; int otherSecondIndex = otherIndices.Items[1]; int otherLastIndex = otherIndices.Items[2]; var otherPoly = convexPolygons.Items[ii]; float x3 = otherPoly.Items[otherPoly.Count - 2], y3 = otherPoly.Items[otherPoly.Count - 1]; if (otherFirstIndex != firstIndex || otherSecondIndex != lastIndex) continue; int winding1 = Winding(prevPrevX, prevPrevY, prevX, prevY, x3, y3); int winding2 = Winding(x3, y3, firstX, firstY, secondX, secondY); if (winding1 == winding && winding2 == winding) { otherPoly.Clear(); otherIndices.Clear(); polygon.Add(x3); polygon.Add(y3); polygonIndices.Add(otherLastIndex); prevPrevX = prevX; prevPrevY = prevY; prevX = x3; prevY = y3; ii = 0; } } } // Remove empty polygons that resulted from the merge step above. for (int i = convexPolygons.Count - 1; i >= 0; i--) { polygon = convexPolygons.Items[i]; if (polygon.Count == 0) { convexPolygons.RemoveAt(i); polygonPool.Free(polygon); polygonIndices = convexPolygonsIndices.Items[i]; convexPolygonsIndices.RemoveAt(i); polygonIndicesPool.Free(polygonIndices); } } return convexPolygons; } static private bool IsConcave (int index, int vertexCount, float[] vertices, int[] indices) { int previous = indices[(vertexCount + index - 1) % vertexCount] << 1; int current = indices[index] << 1; int next = indices[(index + 1) % vertexCount] << 1; return !PositiveArea(vertices[previous], vertices[previous + 1], vertices[current], vertices[current + 1], vertices[next], vertices[next + 1]); } static private bool PositiveArea (float p1x, float p1y, float p2x, float p2y, float p3x, float p3y) { return p1x * (p3y - p2y) + p2x * (p1y - p3y) + p3x * (p2y - p1y) >= 0; } static private int Winding (float p1x, float p1y, float p2x, float p2y, float p3x, float p3y) { float px = p2x - p1x, py = p2y - p1y; return p3x * py - p3y * px + px * p1y - p1x * py >= 0 ? 1 : -1; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Text; using TypeCode = Google.Cloud.Spanner.V1.TypeCode; namespace Google.Cloud.Spanner.Connection { internal sealed class SchemaProvider { private static readonly List<string> DataTypes = Enum.GetValues(typeof(TypeCode)).Cast<TypeCode>().Select(t => t.ToString()).ToList(); private readonly SpannerRetriableConnection _connection; private readonly Dictionary<string, Tuple<Action<DataTable, string[]>, int>> _schemaCollections; private static readonly string[] TableRestrictions = { "TABLE_CATALOG", "TABLE_SCHEMA", "TABLE_NAME", "TABLE_TYPE" }; private static readonly string[] ColumnRestrictions = { "TABLE_CATALOG", "TABLE_SCHEMA", "TABLE_NAME", "COLUMN_NAME" }; private static readonly string[] ViewRestrictions = { "TABLE_CATALOG", "TABLE_SCHEMA", "TABLE_NAME" }; private static readonly string[] IndexRestrictions = { "TABLE_CATALOG", "TABLE_SCHEMA", "TABLE_NAME", "INDEX_NAME" }; private static readonly string[] IndexColumnRestrictions = { "TABLE_CATALOG", "TABLE_SCHEMA", "TABLE_NAME", "INDEX_NAME", "COLUMN_NAME" }; public SchemaProvider(SpannerRetriableConnection connection) { _connection = connection; _schemaCollections = new Dictionary<string, Tuple<Action<DataTable, string[]>, int>>(StringComparer.OrdinalIgnoreCase) { { DbMetaDataCollectionNames.MetaDataCollections, new Tuple<Action<DataTable, string[]>, int>(FillMetadataCollections, 0) }, { DbMetaDataCollectionNames.ReservedWords, new Tuple<Action<DataTable, string[]>, int>(FillReservedWords, 0) }, { DbMetaDataCollectionNames.DataTypes, new Tuple<Action<DataTable, string[]>, int>(FillDataTypes, 0) }, { DbMetaDataCollectionNames.Restrictions, new Tuple<Action<DataTable, string[]>, int>(FillRestrictions, 0) }, { "Columns", new Tuple<Action<DataTable, string[]>, int>(FillColumns, 4) }, { "ColumnOptions", new Tuple<Action<DataTable, string[]>, int>(FillColumnOptions, 0) }, { "Indexes", new Tuple<Action<DataTable, string[]>, int>(FillIndexes, 4) }, { "IndexColumns", new Tuple<Action<DataTable, string[]>, int>(FillIndexColumns, 5) }, { "KeyColumnUsage", new Tuple<Action<DataTable, string[]>, int>(FillKeyColumnUsage, 0) }, { "Tables", new Tuple<Action<DataTable, string[]>, int>(FillTables, 4) }, { "ReferentialConstraints", new Tuple<Action<DataTable, string[]>, int>(FillReferentialConstraints, 0) }, { "TableConstraints", new Tuple<Action<DataTable, string[]>, int>(FillTableConstraints, 0) }, { "Views", new Tuple<Action<DataTable, string[]>, int>(FillViews, 3) }, }; } public DataTable GetSchema() => GetSchema(DbMetaDataCollectionNames.MetaDataCollections); public DataTable GetSchema(string collectionName, string[] restrictionValues = null) { GaxPreconditions.CheckNotNull(collectionName, nameof(collectionName)); GaxPreconditions.CheckArgument(_schemaCollections.ContainsKey(collectionName), nameof(collectionName), $"Unknown collection name: {collectionName}"); var dataTable = new DataTable(collectionName); _schemaCollections[collectionName].Item1(dataTable, restrictionValues); return dataTable; } private void FillMetadataCollections(DataTable dataTable, string[] restrictionValues = null) { dataTable.Columns.AddRange(new [] { new DataColumn(DbMetaDataColumnNames.CollectionName, typeof(string)), new DataColumn(DbMetaDataColumnNames.NumberOfRestrictions, typeof(int)), new DataColumn(DbMetaDataColumnNames.NumberOfIdentifierParts, typeof(int)), }); _ = _schemaCollections.Select(entry => dataTable.Rows.Add(entry.Key, 0, 0)); } private void FillReservedWords(DataTable dataTable, string[] restrictionValues = null) { dataTable.Columns.AddRange(new [] { new DataColumn(DbMetaDataColumnNames.ReservedWord, typeof(string)), }); _ = Keywords.ReservedKeywords.Select(w => dataTable.Rows.Add(w)); } private void FillDataTypes(DataTable dataTable, string[] restrictionValues = null) { dataTable.Columns.AddRange(new [] { new DataColumn(DbMetaDataColumnNames.DataType, typeof(string)), }); _ = DataTypes.Select(w => dataTable.Rows.Add(w)); } private void FillRestrictions(DataTable dataTable, string[] restrictionValues = null) { dataTable.Columns.AddRange(new [] { new DataColumn("CollectionName", typeof(string)), new DataColumn("RestrictionName", typeof(string)), new DataColumn("RestrictionDefault", typeof(string)), new DataColumn("RestrictionNumber", typeof(int)), }); dataTable.Rows.Add("Tables", "Catalog", "TABLE_CATALOG", 1); dataTable.Rows.Add("Tables", "Schema", "TABLE_SCHEMA", 2); dataTable.Rows.Add("Tables", "Table", "TABLE_NAME", 3); dataTable.Rows.Add("Tables", "TableType", "TABLE_TYPE", 4); dataTable.Rows.Add("Columns", "Catalog", "TABLE_CATALOG", 1); dataTable.Rows.Add("Columns", "Schema", "TABLE_SCHEMA", 2); dataTable.Rows.Add("Columns", "TableName", "TABLE_NAME", 3); dataTable.Rows.Add("Columns", "Column", "COLUMN_NAME", 4); dataTable.Rows.Add("Views", "Catalog", "TABLE_CATALOG", 1); dataTable.Rows.Add("Views", "Schema", "TABLE_SCHEMA", 2); dataTable.Rows.Add("Views", "Table", "TABLE_NAME", 3); dataTable.Rows.Add("Indexes", "Catalog", "TABLE_CATALOG", 1); dataTable.Rows.Add("Indexes", "Schema", "TABLE_SCHEMA", 2); dataTable.Rows.Add("Indexes", "Table", "TABLE_NAME", 3); dataTable.Rows.Add("Indexes", "Index", "INDEX_NAME", 4); dataTable.Rows.Add("IndexColumns", "Catalog", "TABLE_CATALOG", 1); dataTable.Rows.Add("IndexColumns", "Schema", "TABLE_SCHEMA", 2); dataTable.Rows.Add("IndexColumns", "Table", "TABLE_NAME", 3); dataTable.Rows.Add("IndexColumns", "Index", "INDEX_NAME", 4); dataTable.Rows.Add("IndexColumns", "Column", "COLUMN_NAME", 5); } private void FillColumns(DataTable dataTable, string[] restrictionValues = null) { dataTable.Columns.AddRange(new [] { new DataColumn("TABLE_CATALOG", typeof(string)), new DataColumn("TABLE_SCHEMA", typeof(string)), new DataColumn("TABLE_NAME", typeof(string)), new DataColumn("ORDINAL_POSITION", typeof(long)), new DataColumn("COLUMN_NAME", typeof(string)), new DataColumn("COLUMN_DEFAULT", typeof(string)), new DataColumn("DATA_TYPE", typeof(string)), new DataColumn("IS_NULLABLE", typeof(string)), new DataColumn("SPANNER_TYPE", typeof(string)), new DataColumn("IS_GENERATED", typeof(string)), new DataColumn("GENERATION_EXPRESSION", typeof(string)), new DataColumn("IS_STORED", typeof(string)), new DataColumn("SPANNER_STATE", typeof(string)), }); FillDataTable(dataTable, "COLUMNS", ColumnRestrictions, restrictionValues); } private void FillColumnOptions(DataTable dataTable, string[] restrictionValues = null) { dataTable.Columns.AddRange(new [] { new DataColumn("TABLE_CATALOG", typeof(string)), new DataColumn("TABLE_SCHEMA", typeof(string)), new DataColumn("TABLE_NAME", typeof(string)), new DataColumn("COLUMN_NAME", typeof(string)), new DataColumn("OPTION_NAME", typeof(string)), new DataColumn("OPTION_TYPE", typeof(string)), new DataColumn("OPTION_VALUE", typeof(string)), }); FillDataTable(dataTable, "COLUMN_OPTIONS", null, restrictionValues); } private void FillKeyColumnUsage(DataTable dataTable, string[] restrictionValues = null) { dataTable.Columns.AddRange(new [] { new DataColumn("CONSTRAINT_CATALOG", typeof(string)), new DataColumn("CONSTRAINT_SCHEMA", typeof(string)), new DataColumn("CONSTRAINT_NAME", typeof(string)), new DataColumn("TABLE_CATALOG", typeof(string)), new DataColumn("TABLE_SCHEMA", typeof(string)), new DataColumn("TABLE_NAME", typeof(string)), new DataColumn("COLUMN_NAME", typeof(string)), new DataColumn("ORDINAL_POSITION", typeof(long)), new DataColumn("POSITION_IN_UNIQUE_CONSTRAINT", typeof(string)), }); FillDataTable(dataTable, "KEY_COLUMN_USAGE", null, restrictionValues); } private void FillReferentialConstraints(DataTable dataTable, string[] restrictionValues = null) { dataTable.Columns.AddRange(new [] { new DataColumn("CONSTRAINT_CATALOG", typeof(string)), new DataColumn("CONSTRAINT_SCHEMA", typeof(string)), new DataColumn("CONSTRAINT_NAME", typeof(string)), new DataColumn("UNIQUE_CONSTRAINT_CATALOG", typeof(string)), new DataColumn("UNIQUE_CONSTRAINT_SCHEMA", typeof(string)), new DataColumn("UNIQUE_CONSTRAINT_NAME", typeof(string)), new DataColumn("MATCH_OPTION", typeof(string)), new DataColumn("UPDATE_RULE", typeof(string)), new DataColumn("DELETE_RULE", typeof(string)), new DataColumn("SPANNER_STATE", typeof(string)), }); FillDataTable(dataTable, "REFERENTIAL_CONSTRAINTS", null, restrictionValues); } private void FillIndexes(DataTable dataTable, string[] restrictionValues = null) { dataTable.Columns.AddRange(new [] { new DataColumn("TABLE_CATALOG", typeof(string)), new DataColumn("TABLE_SCHEMA", typeof(string)), new DataColumn("TABLE_NAME", typeof(string)), new DataColumn("INDEX_NAME", typeof(string)), new DataColumn("INDEX_TYPE", typeof(string)), new DataColumn("PARENT_TABLE_NAME", typeof(string)), new DataColumn("IS_UNIQUE", typeof(bool)), new DataColumn("IS_NULL_FILTERED", typeof(bool)), new DataColumn("INDEX_STATE", typeof(string)), new DataColumn("SPANNER_IS_MANAGED", typeof(bool)), }); FillDataTable(dataTable, "INDEXES", IndexRestrictions, restrictionValues); } private void FillIndexColumns(DataTable dataTable, string[] restrictionValues = null) { dataTable.Columns.AddRange(new [] { new DataColumn("TABLE_CATALOG", typeof(string)), new DataColumn("TABLE_SCHEMA", typeof(string)), new DataColumn("TABLE_NAME", typeof(string)), new DataColumn("INDEX_NAME", typeof(string)), new DataColumn("INDEX_TYPE", typeof(string)), new DataColumn("COLUMN_NAME", typeof(string)), new DataColumn("ORDINAL_POSITION", typeof(long)), new DataColumn("COLUMN_ORDERING", typeof(string)), new DataColumn("IS_NULLABLE", typeof(string)), new DataColumn("SPANNER_TYPE", typeof(string)), }); FillDataTable(dataTable, "INDEX_COLUMNS", IndexColumnRestrictions, restrictionValues); } private void FillTables(DataTable dataTable, string[] restrictionValues = null) { dataTable.Columns.AddRange(new [] { new DataColumn("TABLE_CATALOG", typeof(string)), new DataColumn("TABLE_SCHEMA", typeof(string)), new DataColumn("TABLE_NAME", typeof(string)), new DataColumn("PARENT_TABLE_NAME", typeof(string)), new DataColumn("ON_DELETE_ACTION", typeof(string)), new DataColumn("SPANNER_STATE", typeof(string)), }); FillDataTable(dataTable, "TABLES", TableRestrictions, restrictionValues); } private void FillTableConstraints(DataTable dataTable, string[] restrictionValues = null) { dataTable.Columns.AddRange(new [] { new DataColumn("CONSTRAINT_CATALOG", typeof(string)), new DataColumn("CONSTRAINT_SCHEMA", typeof(string)), new DataColumn("CONSTRAINT_NAME", typeof(string)), new DataColumn("TABLE_SCHEMA", typeof(string)), new DataColumn("TABLE_NAME", typeof(string)), new DataColumn("CONSTRAINT_TYPE", typeof(string)), new DataColumn("IS_DEFERRABLE", typeof(string)), new DataColumn("INITIALLY_DEFERRED", typeof(string)), new DataColumn("ENFORCED", typeof(string)), }); FillDataTable(dataTable, "TABLE_CONSTRAINTS", null, restrictionValues); } private void FillViews(DataTable dataTable, string[] restrictionValues = null) { dataTable.Columns.AddRange(new [] { new DataColumn("TABLE_CATALOG", typeof(string)), new DataColumn("TABLE_SCHEMA", typeof(string)), new DataColumn("TABLE_NAME", typeof(string)), new DataColumn("VIEW_DEFINITION", typeof(string)), }); FillDataTable(dataTable, "VIEWS", ViewRestrictions, restrictionValues); } private void FillDataTable(DataTable dataTable, string tableName, string[] restrictionColumns, string[] restrictionValues) { Action close = null; if (_connection.State != ConnectionState.Open) { _connection.Open(); close = _connection.Close; } using (var command = _connection.CreateCommand()) { command.CommandText = $"SELECT {string.Join(", ", dataTable.Columns.Cast<DataColumn>().Select(x => x!.ColumnName.Replace("COLUMN_DEFAULT", "CAST(COLUMN_DEFAULT AS STRING) AS COLUMN_DEFAULT")))}\n" + $"FROM INFORMATION_SCHEMA.{tableName}\n" + BuildWhereClause(command, restrictionColumns, restrictionValues) + $"ORDER BY {string.Join(", ", dataTable.Columns.Cast<DataColumn>().Select(x => x!.ColumnName))}"; using var reader = command.ExecuteReader(); while (reader.Read()) { var rowValues = new object[dataTable.Columns.Count]; reader.GetValues(rowValues); dataTable.Rows.Add(rowValues); } } close?.Invoke(); } private static string BuildWhereClause(DbCommand command, string[] restrictionColumns, string[] restrictionValues) { if (restrictionValues == null || restrictionColumns == null || restrictionValues.Length == 0) { return ""; } GaxPreconditions.CheckArgument(restrictionColumns.Length >= restrictionValues.Length, nameof(restrictionValues), $"Unsupported number of restriction values supplied: {restrictionValues.Length}. Expected at most {restrictionColumns.Length} values."); var builder = new StringBuilder(); var first = true; for (var i = 0; i < restrictionValues.Length; i++) { if (restrictionValues[i] != null) { builder.Append(first ? "WHERE " : "AND "); builder.Append(restrictionColumns[i]).Append("=@p").Append(i).Append("\n"); first = false; var param = command.CreateParameter(); param.ParameterName = $"@p{i}"; param.Value = restrictionValues[i]; command.Parameters.Add(param); } } return builder.ToString(); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.IO; using System.Globalization; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json { /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data. /// </summary> public abstract class JsonReader : IDisposable { /// <summary> /// Specifies the state of the reader. /// </summary> protected internal enum State { /// <summary> /// The Read method has not been called. /// </summary> Start, /// <summary> /// The end of the file has been reached successfully. /// </summary> Complete, /// <summary> /// Reader is at a property. /// </summary> Property, /// <summary> /// Reader is at the start of an object. /// </summary> ObjectStart, /// <summary> /// Reader is in an object. /// </summary> Object, /// <summary> /// Reader is at the start of an array. /// </summary> ArrayStart, /// <summary> /// Reader is in an array. /// </summary> Array, /// <summary> /// The Close method has been called. /// </summary> Closed, /// <summary> /// Reader has just read a value. /// </summary> PostValue, /// <summary> /// Reader is at the start of a constructor. /// </summary> ConstructorStart, /// <summary> /// Reader in a constructor. /// </summary> Constructor, /// <summary> /// An error occurred that prevents the read operation from continuing. /// </summary> Error, /// <summary> /// The end of the file has been reached successfully. /// </summary> Finished } // current Token data private JsonToken _tokenType; private object _value; internal char _quoteChar; internal State _currentState; internal ReadType _readType; private JsonPosition _currentPosition; private CultureInfo _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string _dateFormatString; private readonly List<JsonPosition> _stack; /// <summary> /// Gets the current reader state. /// </summary> /// <value>The current reader state.</value> protected State CurrentState { get { return _currentState; } } /// <summary> /// Gets or sets a value indicating whether the underlying stream or /// <see cref="TextReader"/> should be closed when the reader is closed. /// </summary> /// <value> /// true to close the underlying stream or <see cref="TextReader"/> when /// the reader is closed; otherwise false. The default is true. /// </value> public bool CloseInput { get; set; } /// <summary> /// Gets or sets a value indicating whether multiple pieces of JSON content can /// be read from a continuous stream without erroring. /// </summary> /// <value> /// true to support reading multiple pieces of JSON content; otherwise false. The default is false. /// </value> public bool SupportMultipleContent { get; set; } /// <summary> /// Gets the quotation mark character used to enclose the value of a string. /// </summary> public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> time zones are handling when reading JSON. /// </summary> public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { _dateTimeZoneHandling = value; } } /// <summary> /// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. /// </summary> public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { _dateParseHandling = value; } } /// <summary> /// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. /// </summary> public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { _floatParseHandling = value; } } /// <summary> /// Get or set how custom date formatted strings are parsed when reading JSON. /// </summary> public string DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } /// <summary> /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>. /// </summary> public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) throw new ArgumentException("Value must be positive.", "value"); _maxDepth = value; } } /// <summary> /// Gets the type of the current JSON token. /// </summary> public virtual JsonToken TokenType { get { return _tokenType; } } /// <summary> /// Gets the text value of the current JSON token. /// </summary> public virtual object Value { get { return _value; } } /// <summary> /// Gets The Common Language Runtime (CLR) type for the current JSON token. /// </summary> public virtual Type ValueType { get { return (_value != null) ? _value.GetType() : null; } } /// <summary> /// Gets the depth of the current token in the JSON document. /// </summary> /// <value>The depth of the current token in the JSON document.</value> public virtual int Depth { get { int depth = _stack.Count; if (IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) return depth; else return depth + 1; } } /// <summary> /// Gets the path of the current JSON token. /// </summary> public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) return string.Empty; bool insideContainer = (_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart); IEnumerable<JsonPosition> positions = (!insideContainer) ? _stack : _stack.Concat(new[] { _currentPosition }); return JsonPosition.BuildPath(positions); } } /// <summary> /// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } internal JsonPosition GetPosition(int depth) { if (depth < _stack.Count) return _stack[depth]; return _currentPosition; } /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> protected JsonReader() { _currentState = State.Start; _stack = new List<JsonPosition>(4); _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); } else { _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); // this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth) { _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } } } private JsonContainerType Pop() { JsonPosition oldPosition; if (_stack.Count > 0) { oldPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { oldPosition = _currentPosition; _currentPosition = new JsonPosition(); } if (_maxDepth != null && Depth <= _maxDepth) _hasExceededMaxDepth = false; return oldPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns> public abstract bool Read(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>. /// </summary> /// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract int? ReadAsInt32(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="String"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract string ReadAsString(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Byte"/>[]. /// </summary> /// <returns>A <see cref="Byte"/>[] or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns> public abstract byte[] ReadAsBytes(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract decimal? ReadAsDecimal(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract DateTime? ReadAsDateTime(); #if !NET20 /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract DateTimeOffset? ReadAsDateTimeOffset(); #endif internal virtual bool ReadInternal() { throw new NotImplementedException(); } #if !NET20 internal DateTimeOffset? ReadAsDateTimeOffsetInternal() { _readType = ReadType.ReadAsDateTimeOffset; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.Date) { if (Value is DateTime) SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value), false); return (DateTimeOffset)Value; } if (t == JsonToken.Null) return null; if (t == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } object temp; DateTimeOffset dt; if (DateTimeUtils.TryParseDateTime(s, DateParseHandling.DateTimeOffset, DateTimeZoneHandling, _dateFormatString, Culture, out temp)) { dt = (DateTimeOffset)temp; SetToken(JsonToken.Date, dt, false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } #endif internal byte[] ReadAsBytesInternal() { _readType = ReadType.ReadAsBytes; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (IsWrappedInTypeObject()) { byte[] data = ReadAsBytes(); ReadInternal(); SetToken(JsonToken.Bytes, data, false); return data; } // attempt to convert possible base 64 string to bytes if (t == JsonToken.String) { string s = (string)Value; byte[] data; Guid g; if (s.Length == 0) { data = new byte[0]; } else if (ConvertUtils.TryConvertGuid(s, out g)) { data = g.ToByteArray(); } else { data = Convert.FromBase64String(s); } SetToken(JsonToken.Bytes, data, false); return data; } if (t == JsonToken.Null) return null; if (t == JsonToken.Bytes) { if (ValueType == typeof(Guid)) { byte[] data = ((Guid)Value).ToByteArray(); SetToken(JsonToken.Bytes, data, false); return data; } return (byte[])Value; } if (t == JsonToken.StartArray) { List<byte> data = new List<byte>(); while (ReadInternal()) { t = TokenType; switch (t) { case JsonToken.Integer: data.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); break; case JsonToken.EndArray: byte[] d = data.ToArray(); SetToken(JsonToken.Bytes, d, false); return d; case JsonToken.Comment: // skip break; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } } throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal decimal? ReadAsDecimalInternal() { _readType = ReadType.ReadAsDecimal; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.Integer || t == JsonToken.Float) { if (!(Value is decimal)) SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture), false); return (decimal)Value; } if (t == JsonToken.Null) return null; if (t == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } decimal d; if (decimal.TryParse(s, NumberStyles.Number, Culture, out d)) { SetToken(JsonToken.Float, d, false); return d; } else { throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal int? ReadAsInt32Internal() { _readType = ReadType.ReadAsInt32; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.Integer || t == JsonToken.Float) { if (!(Value is int)) SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture), false); return (int)Value; } if (t == JsonToken.Null) return null; int i; if (t == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out i)) { SetToken(JsonToken.Integer, i, false); return i; } else { throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } internal string ReadAsStringInternal() { _readType = ReadType.ReadAsString; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.String) return (string)Value; if (t == JsonToken.Null) return null; if (IsPrimitiveToken(t)) { if (Value != null) { string s; if (Value is IFormattable) s = ((IFormattable)Value).ToString(null, Culture); else s = Value.ToString(); SetToken(JsonToken.String, s, false); return s; } } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal DateTime? ReadAsDateTimeInternal() { _readType = ReadType.ReadAsDateTime; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } } while (TokenType == JsonToken.Comment); if (TokenType == JsonToken.Date) return (DateTime)Value; if (TokenType == JsonToken.Null) return null; if (TokenType == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } DateTime dt; object temp; if (DateTimeUtils.TryParseDateTime(s, DateParseHandling.DateTime, DateTimeZoneHandling, _dateFormatString, Culture, out temp)) { dt = (DateTime)temp; dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } if (TokenType == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } private bool IsWrappedInTypeObject() { _readType = ReadType.Read; if (TokenType == JsonToken.StartObject) { if (!ReadInternal()) throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); if (Value.ToString() == JsonTypeReflector.TypePropertyName) { ReadInternal(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReadInternal(); if (Value.ToString() == JsonTypeReflector.ValuePropertyName) { return true; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } return false; } /// <summary> /// Skips the children of the current token. /// </summary> public void Skip() { if (TokenType == JsonToken.PropertyName) Read(); if (IsStartToken(TokenType)) { int depth = Depth; while (Read() && (depth < Depth)) { } } } /// <summary> /// Sets the current token. /// </summary> /// <param name="newToken">The new token.</param> protected void SetToken(JsonToken newToken) { SetToken(newToken, null, true); } /// <summary> /// Sets the current token and value. /// </summary> /// <param name="newToken">The new token.</param> /// <param name="value">The value.</param> protected void SetToken(JsonToken newToken, object value) { SetToken(newToken, value, true); } internal void SetToken(JsonToken newToken, object value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Undefined: case JsonToken.Integer: case JsonToken.Float: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Date: case JsonToken.String: case JsonToken.Raw: case JsonToken.Bytes: SetPostValueState(updateIndex); break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != JsonContainerType.None) _currentState = State.PostValue; else SetFinished(); if (updateIndex) UpdateScopeWithFinishedValue(); } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) _currentPosition.Position++; } private void ValidateEnd(JsonToken endToken) { JsonContainerType currentObject = Pop(); if (GetTypeForCloseToken(endToken) != currentObject) throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); if (Peek() != JsonContainerType.None) _currentState = State.PostValue; else SetFinished(); } /// <summary> /// Sets the state based on current token type. /// </summary> protected void SetStateBasedOnCurrent() { JsonContainerType currentObject = Peek(); switch (currentObject) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject)); } } private void SetFinished() { if (SupportMultipleContent) _currentState = State.Start; else _currentState = State.Finished; } internal static bool IsPrimitiveToken(JsonToken token) { switch (token) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Undefined: case JsonToken.Null: case JsonToken.Date: case JsonToken.Bytes: return true; default: return false; } } internal static bool IsStartToken(JsonToken token) { switch (token) { case JsonToken.StartObject: case JsonToken.StartArray: case JsonToken.StartConstructor: return true; default: return false; } } private JsonContainerType GetTypeForCloseToken(JsonToken token) { switch (token) { case JsonToken.EndObject: return JsonContainerType.Object; case JsonToken.EndArray: return JsonContainerType.Array; case JsonToken.EndConstructor: return JsonContainerType.Constructor; default: throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> void IDisposable.Dispose() { Dispose(true); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) Close(); } /// <summary> /// Changes the <see cref="State"/> to Closed. /// </summary> public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } } }
/* * 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 log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Capabilities.Handlers; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System; using System.Reflection; using Caps = OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Region.ClientStack.Linden { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UploadBakedTextureModule")] public class UploadBakedTextureModule : INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// For historical reasons this is fixed, but there /// </summary> private static readonly string m_uploadBakedTexturePath = "0010/";// This is in the LandManagementModule. private Scene m_scene; private bool m_persistBakedTextures; private IBakedTextureModule m_BakedTextureModule; public void Initialise(IConfigSource source) { IConfig appearanceConfig = source.Configs["Appearance"]; if (appearanceConfig != null) m_persistBakedTextures = appearanceConfig.GetBoolean("PersistBakedTextures", m_persistBakedTextures); } public void AddRegion(Scene s) { m_scene = s; } public void RemoveRegion(Scene s) { s.EventManager.OnRegisterCaps -= RegisterCaps; s.EventManager.OnNewPresence -= RegisterNewPresence; s.EventManager.OnRemovePresence -= DeRegisterPresence; m_BakedTextureModule = null; m_scene = null; } public void RegionLoaded(Scene s) { m_scene.EventManager.OnRegisterCaps += RegisterCaps; m_scene.EventManager.OnNewPresence += RegisterNewPresence; m_scene.EventManager.OnRemovePresence += DeRegisterPresence; } private void DeRegisterPresence(UUID agentId) { ScenePresence presence = null; if (m_scene.TryGetScenePresence(agentId, out presence)) { presence.ControllingClient.OnSetAppearance -= CaptureAppearanceSettings; } } private void RegisterNewPresence(ScenePresence presence) { presence.ControllingClient.OnSetAppearance += CaptureAppearanceSettings; } private void CaptureAppearanceSettings(IClientAPI remoteClient, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems) { int maxCacheitemsLoop = cacheItems.Length; if (maxCacheitemsLoop > AvatarWearable.MAX_WEARABLES) { maxCacheitemsLoop = AvatarWearable.MAX_WEARABLES; m_log.WarnFormat("[CACHEDBAKES]: Too Many Cache items Provided {0}, the max is {1}. Truncating!", cacheItems.Length, AvatarWearable.MAX_WEARABLES); } m_BakedTextureModule = m_scene.RequestModuleInterface<IBakedTextureModule>(); if (cacheItems.Length > 0) { // m_log.Debug("[Cacheitems]: " + cacheItems.Length); // for (int iter = 0; iter < maxCacheitemsLoop; iter++) // { // m_log.Debug("[Cacheitems] {" + iter + "/" + cacheItems[iter].TextureIndex + "}: c-" + cacheItems[iter].CacheId + ", t-" + // cacheItems[iter].TextureID); // } ScenePresence p = null; if (m_scene.TryGetScenePresence(remoteClient.AgentId, out p)) { WearableCacheItem[] existingitems = p.Appearance.WearableCacheItems; if (existingitems == null) { if (m_BakedTextureModule != null) { WearableCacheItem[] savedcache = null; try { if (p.Appearance.WearableCacheItemsDirty) { savedcache = m_BakedTextureModule.Get(p.UUID); p.Appearance.WearableCacheItems = savedcache; p.Appearance.WearableCacheItemsDirty = false; } } /* * The following Catch types DO NOT WORK with m_BakedTextureModule.Get * it jumps to the General Packet Exception Handler if you don't catch Exception! * catch (System.Net.Sockets.SocketException) { cacheItems = null; } catch (WebException) { cacheItems = null; } catch (InvalidOperationException) { cacheItems = null; } */ catch (Exception) { // The service logs a sufficient error message. } if (savedcache != null) existingitems = savedcache; } } // Existing items null means it's a fully new appearance if (existingitems == null) { for (int i = 0; i < maxCacheitemsLoop; i++) { if (textureEntry.FaceTextures.Length > cacheItems[i].TextureIndex) { Primitive.TextureEntryFace face = textureEntry.FaceTextures[cacheItems[i].TextureIndex]; if (face == null) { textureEntry.CreateFace(cacheItems[i].TextureIndex); textureEntry.FaceTextures[cacheItems[i].TextureIndex].TextureID = AppearanceManager.DEFAULT_AVATAR_TEXTURE; continue; } cacheItems[i].TextureID =face.TextureID; if (m_scene.AssetService != null) cacheItems[i].TextureAsset = m_scene.AssetService.GetCached(cacheItems[i].TextureID.ToString()); } else { m_log.WarnFormat("[CACHEDBAKES]: Invalid Texture Index Provided, Texture doesn't exist or hasn't been uploaded yet {0}, the max is {1}. Skipping!", cacheItems[i].TextureIndex, textureEntry.FaceTextures.Length); } } } else { // for each uploaded baked texture for (int i = 0; i < maxCacheitemsLoop; i++) { if (textureEntry.FaceTextures.Length > cacheItems[i].TextureIndex) { Primitive.TextureEntryFace face = textureEntry.FaceTextures[cacheItems[i].TextureIndex]; if (face == null) { textureEntry.CreateFace(cacheItems[i].TextureIndex); textureEntry.FaceTextures[cacheItems[i].TextureIndex].TextureID = AppearanceManager.DEFAULT_AVATAR_TEXTURE; continue; } cacheItems[i].TextureID = face.TextureID; } else { m_log.WarnFormat("[CACHEDBAKES]: Invalid Texture Index Provided, Texture doesn't exist or hasn't been uploaded yet {0}, the max is {1}. Skipping!", cacheItems[i].TextureIndex, textureEntry.FaceTextures.Length); } } for (int i = 0; i < maxCacheitemsLoop; i++) { if (cacheItems[i].TextureAsset == null) { cacheItems[i].TextureAsset = m_scene.AssetService.GetCached(cacheItems[i].TextureID.ToString()); } } } p.Appearance.WearableCacheItems = cacheItems; if (m_BakedTextureModule != null) { m_BakedTextureModule.Store(remoteClient.AgentId, cacheItems); p.Appearance.WearableCacheItemsDirty = true; } } } } public void PostInitialise() { } public void Close() { } public string Name { get { return "UploadBakedTextureModule"; } } public Type ReplaceableInterface { get { return null; } } public void RegisterCaps(UUID agentID, Caps caps) { UploadBakedTextureHandler avatarhandler = new UploadBakedTextureHandler( caps, m_scene.AssetService, m_persistBakedTextures); caps.RegisterHandler( "UploadBakedTexture", new RestStreamHandler( "POST", "/CAPS/" + caps.CapsObjectPath + m_uploadBakedTexturePath, avatarhandler.UploadBakedTexture, "UploadBakedTexture", agentID.ToString())); } } }
/********************************************************************++ * Copyright (c) Microsoft Corporation. All rights reserved. * --********************************************************************/ using System.Collections.Generic; using System.Management.Automation.Remoting; using System.Management.Automation.Runspaces; using System.Management.Automation.Remoting.Server; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation { /// <summary> /// Handles all data structure handler communication with the client /// runspace pool /// </summary> internal class ServerRunspacePoolDataStructureHandler { #region Constructors /// <summary> /// Constructor which takes a server runspace pool driver and /// creates an associated ServerRunspacePoolDataStructureHandler /// </summary> /// <param name="driver"></param> /// <param name="transportManager"></param> internal ServerRunspacePoolDataStructureHandler(ServerRunspacePoolDriver driver, AbstractServerSessionTransportManager transportManager) { _clientRunspacePoolId = driver.InstanceId; _transportManager = transportManager; } #endregion Constructors #region Data Structure Handler Methods /// <summary> /// Send a message with application private data to the client /// </summary> /// <param name="applicationPrivateData">applicationPrivateData to send</param> /// <param name="serverCapability">server capability negotiated during initial exchange of remoting messages / session capabilities of client and server</param> internal void SendApplicationPrivateDataToClient(PSPrimitiveDictionary applicationPrivateData, RemoteSessionCapability serverCapability) { // make server's PSVersionTable available to the client using ApplicationPrivateData PSPrimitiveDictionary applicationPrivateDataWithVersionTable = PSPrimitiveDictionary.CloneAndAddPSVersionTable(applicationPrivateData); // override the hardcoded version numbers with the stuff that was reported to the client during negotiation PSPrimitiveDictionary versionTable = (PSPrimitiveDictionary)applicationPrivateDataWithVersionTable[PSVersionInfo.PSVersionTableName]; versionTable[PSVersionInfo.PSRemotingProtocolVersionName] = serverCapability.ProtocolVersion; versionTable[PSVersionInfo.SerializationVersionName] = serverCapability.SerializationVersion; // Pass back the true PowerShell version to the client via application private data. versionTable[PSVersionInfo.PSVersionName] = PSVersionInfo.PSVersion; RemoteDataObject data = RemotingEncoder.GenerateApplicationPrivateData( _clientRunspacePoolId, applicationPrivateDataWithVersionTable); SendDataAsync(data); } /// <summary> /// Send a message with the RunspacePoolStateInfo to the client /// </summary> /// <param name="stateInfo">state info to send</param> internal void SendStateInfoToClient(RunspacePoolStateInfo stateInfo) { RemoteDataObject data = RemotingEncoder.GenerateRunspacePoolStateInfo( _clientRunspacePoolId, stateInfo); SendDataAsync(data); } /// <summary> /// Send a message with the PSEventArgs to the client /// </summary> /// <param name="e">event to send</param> internal void SendPSEventArgsToClient(PSEventArgs e) { RemoteDataObject data = RemotingEncoder.GeneratePSEventArgs(_clientRunspacePoolId, e); SendDataAsync(data); } /// <summary> /// called when session is connected from a new client /// call into the sessionconnect handlers for each associated powershell dshandler /// </summary> internal void ProcessConnect() { List<ServerPowerShellDataStructureHandler> dsHandlers; lock (_associationSyncObject) { dsHandlers = new List<ServerPowerShellDataStructureHandler>(_associatedShells.Values); } foreach (var dsHandler in dsHandlers) { dsHandler.ProcessConnect(); } } /// <summary> /// Process the data received from the runspace pool on /// the server /// </summary> /// <param name="receivedData">data received</param> internal void ProcessReceivedData(RemoteDataObject<PSObject> receivedData) { if (receivedData == null) { throw PSTraceSource.NewArgumentNullException("receivedData"); } Dbg.Assert(receivedData.TargetInterface == RemotingTargetInterface.RunspacePool, "RemotingTargetInterface must be Runspace"); switch (receivedData.DataType) { case RemotingDataType.CreatePowerShell: { Dbg.Assert(CreateAndInvokePowerShell != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); CreateAndInvokePowerShell.SafeInvoke(this, new RemoteDataEventArgs<RemoteDataObject<PSObject>>(receivedData)); } break; case RemotingDataType.GetCommandMetadata: { Dbg.Assert(GetCommandMetadata != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); GetCommandMetadata.SafeInvoke(this, new RemoteDataEventArgs<RemoteDataObject<PSObject>>(receivedData)); } break; case RemotingDataType.RemoteRunspaceHostResponseData: { Dbg.Assert(HostResponseReceived != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); RemoteHostResponse remoteHostResponse = RemoteHostResponse.Decode(receivedData.Data); //part of host message robustness algo. Now the host response is back, report to transport that // execution status is back to running _transportManager.ReportExecutionStatusAsRunning(); HostResponseReceived.SafeInvoke(this, new RemoteDataEventArgs<RemoteHostResponse>(remoteHostResponse)); } break; case RemotingDataType.SetMaxRunspaces: { Dbg.Assert(SetMaxRunspacesReceived != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); SetMaxRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data)); } break; case RemotingDataType.SetMinRunspaces: { Dbg.Assert(SetMinRunspacesReceived != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); SetMinRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data)); } break; case RemotingDataType.AvailableRunspaces: { Dbg.Assert(GetAvailableRunspacesReceived != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); GetAvailableRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data)); } break; case RemotingDataType.ResetRunspaceState: { Dbg.Assert(ResetRunspaceState != null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events."); ResetRunspaceState.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data)); } break; } // switch... } /// <summary> /// Creates a powershell data structure handler from this runspace pool /// </summary> /// <param name="instanceId">powershell instance id</param> /// <param name="runspacePoolId">runspace pool id</param> /// <param name="remoteStreamOptions">remote stream options</param> /// <param name="localPowerShell">local PowerShell object</param> /// <returns>ServerPowerShellDataStructureHandler</returns> internal ServerPowerShellDataStructureHandler CreatePowerShellDataStructureHandler( Guid instanceId, Guid runspacePoolId, RemoteStreamOptions remoteStreamOptions, PowerShell localPowerShell) { // start with pool's transport manager. AbstractServerTransportManager cmdTransportManager = _transportManager; if (instanceId != Guid.Empty) { cmdTransportManager = _transportManager.GetCommandTransportManager(instanceId); Dbg.Assert(cmdTransportManager.TypeTable != null, "This should be already set in managed C++ code"); } ServerPowerShellDataStructureHandler dsHandler = new ServerPowerShellDataStructureHandler(instanceId, runspacePoolId, remoteStreamOptions, cmdTransportManager, localPowerShell); lock (_associationSyncObject) { _associatedShells.Add(dsHandler.PowerShellId, dsHandler); } dsHandler.RemoveAssociation += new EventHandler(HandleRemoveAssociation); return dsHandler; } /// <summary> /// Returns the currently active PowerShell datastructure handler. /// </summary> /// <returns> /// ServerPowerShellDataStructureHandler if one is present, null otherwise. /// </returns> internal ServerPowerShellDataStructureHandler GetPowerShellDataStructureHandler() { lock (_associationSyncObject) { if (_associatedShells.Count > 0) { foreach (object o in _associatedShells.Values) { ServerPowerShellDataStructureHandler result = o as ServerPowerShellDataStructureHandler; if (result != null) { return result; } } } } return null; } /// <summary> /// dispatch the message to the associated powershell data structure handler /// </summary> /// <param name="rcvdData">message to dispatch</param> internal void DispatchMessageToPowerShell(RemoteDataObject<PSObject> rcvdData) { ServerPowerShellDataStructureHandler dsHandler = GetAssociatedPowerShellDataStructureHandler(rcvdData.PowerShellId); // if data structure handler is not found, then association has already been // removed, discard message if (dsHandler != null) { dsHandler.ProcessReceivedData(rcvdData); } } /// <summary> /// Send the specified response to the client. The client call will /// be blocked on the same /// </summary> /// <param name="callId">call id on the client</param> /// <param name="response">response to send</param> internal void SendResponseToClient(long callId, object response) { RemoteDataObject message = RemotingEncoder.GenerateRunspacePoolOperationResponse(_clientRunspacePoolId, response, callId); SendDataAsync(message); } /// <summary> /// TypeTable used for Serialization/Deserialization. /// </summary> internal TypeTable TypeTable { get { return _transportManager.TypeTable; } set { _transportManager.TypeTable = value; } } #endregion Data Structure Handler Methods #region Data Structure Handler events /// <summary> /// This event is raised whenever there is a request from the /// client to create a powershell on the server and invoke it /// </summary> internal event EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>> CreateAndInvokePowerShell; /// <summary> /// This event is raised whenever there is a request from the /// client to run command discovery pipeline /// </summary> internal event EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>> GetCommandMetadata; /// <summary> /// This event is raised when a host call response is received /// </summary> internal event EventHandler<RemoteDataEventArgs<RemoteHostResponse>> HostResponseReceived; /// <summary> /// This event is raised when there is a request to modify the /// maximum runspaces in the runspace pool /// </summary> internal event EventHandler<RemoteDataEventArgs<PSObject>> SetMaxRunspacesReceived; /// <summary> /// This event is raised when there is a request to modify the /// minimum runspaces in the runspace pool /// </summary> internal event EventHandler<RemoteDataEventArgs<PSObject>> SetMinRunspacesReceived; /// <summary> /// This event is raised when there is a request to get the /// available runspaces in the runspace pool /// </summary> internal event EventHandler<RemoteDataEventArgs<PSObject>> GetAvailableRunspacesReceived; /// <summary> /// This event is raised when the client requests the runspace state /// to be reset. /// </summary> internal event EventHandler<RemoteDataEventArgs<PSObject>> ResetRunspaceState; #endregion Data Structure Handler events #region Private Methods /// <summary> /// Send the data specified as a RemoteDataObject asynchronously /// to the runspace pool on the remote session /// </summary> /// <param name="data">data to send</param> /// <remarks>This overload takes a RemoteDataObject and should /// be the one thats used to send data from within this /// data structure handler class</remarks> private void SendDataAsync(RemoteDataObject data) { Dbg.Assert(null != data, "Cannot send null object."); _transportManager.SendDataToClient(data, true); } /// <summary> /// Get the associated powershell data structure handler for the specified /// powershell id /// </summary> /// <param name="clientPowerShellId">powershell id for the /// powershell data structure handler</param> /// <returns>ServerPowerShellDataStructureHandler</returns> internal ServerPowerShellDataStructureHandler GetAssociatedPowerShellDataStructureHandler (Guid clientPowerShellId) { ServerPowerShellDataStructureHandler dsHandler = null; lock (_associationSyncObject) { bool success = _associatedShells.TryGetValue(clientPowerShellId, out dsHandler); if (!success) { dsHandler = null; } } return dsHandler; } /// <summary> /// Remove the association of the powershell from the runspace pool /// </summary> /// <param name="sender">sender of this event</param> /// <param name="e">unused</param> private void HandleRemoveAssociation(object sender, EventArgs e) { Dbg.Assert(sender is ServerPowerShellDataStructureHandler, @"sender of the event must be ServerPowerShellDataStructureHandler"); ServerPowerShellDataStructureHandler dsHandler = sender as ServerPowerShellDataStructureHandler; lock (_associationSyncObject) { _associatedShells.Remove(dsHandler.PowerShellId); } // let session transport manager remove its association of command transport manager. _transportManager.RemoveCommandTransportManager(dsHandler.PowerShellId); } #endregion Private Methods #region Private Members private Guid _clientRunspacePoolId; // transport manager using which this // runspace pool driver handles all client // communication private AbstractServerSessionTransportManager _transportManager; private Dictionary<Guid, ServerPowerShellDataStructureHandler> _associatedShells = new Dictionary<Guid, ServerPowerShellDataStructureHandler>(); // powershell data structure handlers associated with this // runspace pool data structure handler private object _associationSyncObject = new object(); // object to synchronize operations to above #endregion Private Members } /// <summary> /// Handles all PowerShell data structure handler communication /// with the client side PowerShell /// </summary> internal class ServerPowerShellDataStructureHandler { #region Private Members // transport manager using which this // powershell driver handles all client // communication private AbstractServerTransportManager _transportManager; private Guid _clientRunspacePoolId; private Guid _clientPowerShellId; private RemoteStreamOptions _streamSerializationOptions; private Runspace _rsUsedToInvokePowerShell; #endregion Private Members #region Constructors /// <summary> /// Default constructor for creating ServerPowerShellDataStructureHandler /// instance /// </summary> /// <param name="instanceId">powershell instance id</param> /// <param name="runspacePoolId">runspace pool id</param> /// <param name="remoteStreamOptions">remote stream options</param> /// <param name="transportManager">transport manager</param> /// <param name="localPowerShell">local powershell object</param> internal ServerPowerShellDataStructureHandler(Guid instanceId, Guid runspacePoolId, RemoteStreamOptions remoteStreamOptions, AbstractServerTransportManager transportManager, PowerShell localPowerShell) { _clientPowerShellId = instanceId; _clientRunspacePoolId = runspacePoolId; _transportManager = transportManager; _streamSerializationOptions = remoteStreamOptions; transportManager.Closing += HandleTransportClosing; if (localPowerShell != null) { localPowerShell.RunspaceAssigned += new EventHandler<PSEventArgs<Runspace>>(LocalPowerShell_RunspaceAssigned); } } private void LocalPowerShell_RunspaceAssigned(object sender, PSEventArgs<Runspace> e) { _rsUsedToInvokePowerShell = e.Args; } #endregion Constructors #region Data Structure Handler Methods /// <summary> /// Prepare transport manager to send data to client. /// </summary> internal void Prepare() { // When Guid.Empty is used, PowerShell must be using pool's transport manager // to send data to client. so we dont need to prepare command transport manager if (_clientPowerShellId != Guid.Empty) { _transportManager.Prepare(); } } /// <summary> /// Send the state information to the client /// </summary> /// <param name="stateInfo">state information to be /// sent to the client</param> internal void SendStateChangedInformationToClient(PSInvocationStateInfo stateInfo) { Dbg.Assert((stateInfo.State == PSInvocationState.Completed) || (stateInfo.State == PSInvocationState.Failed) || (stateInfo.State == PSInvocationState.Stopped), "SendStateChangedInformationToClient should be called to notify a termination state"); SendDataAsync(RemotingEncoder.GeneratePowerShellStateInfo( stateInfo, _clientPowerShellId, _clientRunspacePoolId)); // Close the transport manager only if the PowerShell Guid != Guid.Empty. // When Guid.Empty is used, PowerShell must be using pool's transport manager // to send data to client. if (_clientPowerShellId != Guid.Empty) { // no need to listen for closing events as we are initiating the close _transportManager.Closing -= HandleTransportClosing; // if terminal state is reached close the transport manager instead of letting // the client intiate the close. _transportManager.Close(null); } } /// <summary> /// Send the output data to the client /// </summary> /// <param name="data">data to send</param> internal void SendOutputDataToClient(PSObject data) { SendDataAsync(RemotingEncoder.GeneratePowerShellOutput(data, _clientPowerShellId, _clientRunspacePoolId)); } /// <summary> /// Send the error record to client /// </summary> /// <param name="errorRecord">error record to send</param> internal void SendErrorRecordToClient(ErrorRecord errorRecord) { errorRecord.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToErrorRecord) != 0; SendDataAsync(RemotingEncoder.GeneratePowerShellError( errorRecord, _clientRunspacePoolId, _clientPowerShellId)); } /// <summary> /// Send the specified warning record to client /// </summary> /// <param name="record">warning record</param> internal void SendWarningRecordToClient(WarningRecord record) { record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToWarningRecord) != 0; SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellWarning)); } /// <summary> /// Send the specified debug record to client /// </summary> /// <param name="record">debug record</param> internal void SendDebugRecordToClient(DebugRecord record) { record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToDebugRecord) != 0; SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellDebug)); } /// <summary> /// Send the specified verbose record to client /// </summary> /// <param name="record">warning record</param> internal void SendVerboseRecordToClient(VerboseRecord record) { record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToVerboseRecord) != 0; SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellVerbose)); } /// <summary> /// Send the specified progress record to client /// </summary> /// <param name="record">progress record</param> internal void SendProgressRecordToClient(ProgressRecord record) { SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( record, _clientRunspacePoolId, _clientPowerShellId)); } /// <summary> /// Send the specified information record to client /// </summary> /// <param name="record">information record</param> internal void SendInformationRecordToClient(InformationRecord record) { SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( record, _clientRunspacePoolId, _clientPowerShellId)); } /// <summary> /// called when session is connected from a new client /// calls into observers of this event. /// observers include corrensponding driver that shutsdown /// input stream is present /// </summary> internal void ProcessConnect() { OnSessionConnected.SafeInvoke(this, EventArgs.Empty); } /// <summary> /// Process the data received from the powershell on /// the client /// </summary> /// <param name="receivedData">data received</param> internal void ProcessReceivedData(RemoteDataObject<PSObject> receivedData) { if (receivedData == null) { throw PSTraceSource.NewArgumentNullException("receivedData"); } Dbg.Assert(receivedData.TargetInterface == RemotingTargetInterface.PowerShell, "RemotingTargetInterface must be PowerShell"); switch (receivedData.DataType) { case RemotingDataType.StopPowerShell: { Dbg.Assert(StopPowerShellReceived != null, "ServerPowerShellDriver should subscribe to all data structure handler events"); StopPowerShellReceived.SafeInvoke(this, EventArgs.Empty); } break; case RemotingDataType.PowerShellInput: { Dbg.Assert(InputReceived != null, "ServerPowerShellDriver should subscribe to all data structure handler events"); InputReceived.SafeInvoke(this, new RemoteDataEventArgs<object>(receivedData.Data)); } break; case RemotingDataType.PowerShellInputEnd: { Dbg.Assert(InputEndReceived != null, "ServerPowerShellDriver should subscribe to all data structure handler events"); InputEndReceived.SafeInvoke(this, EventArgs.Empty); } break; case RemotingDataType.RemotePowerShellHostResponseData: { Dbg.Assert(HostResponseReceived != null, "ServerPowerShellDriver should subscribe to all data strucutre handler events"); RemoteHostResponse remoteHostResponse = RemoteHostResponse.Decode(receivedData.Data); //part of host message robustness algo. Now the host response is back, report to transport that // execution status is back to running _transportManager.ReportExecutionStatusAsRunning(); HostResponseReceived.SafeInvoke(this, new RemoteDataEventArgs<RemoteHostResponse>(remoteHostResponse)); } break; } // switch ... } /// <summary> /// Raise a remove association event. This is raised /// when the powershell has gone into a terminal state /// and the runspace pool need not maintain any further /// associations /// </summary> internal void RaiseRemoveAssociationEvent() { Dbg.Assert(RemoveAssociation != null, @"The ServerRunspacePoolDataStructureHandler should subscribe to the RemoveAssociation event of ServerPowerShellDataStructureHandler"); RemoveAssociation.SafeInvoke(this, EventArgs.Empty); } /// <summary> /// Creates a ServerRemoteHost which is associated with this powershell. /// </summary> /// <param name="powerShellHostInfo">Host information about the host associated /// PowerShell object on the client.</param> /// <param name="runspaceServerRemoteHost">Host associated with the RunspacePool /// on the server.</param> /// <returns>A new ServerRemoteHost for the PowerShell.</returns> internal ServerRemoteHost GetHostAssociatedWithPowerShell( HostInfo powerShellHostInfo, ServerRemoteHost runspaceServerRemoteHost) { HostInfo hostInfo; // If host was null use the runspace's host for this powershell; otherwise, // use the HostInfo to create a proxy host of the powershell's host. if (powerShellHostInfo.UseRunspaceHost) { hostInfo = runspaceServerRemoteHost.HostInfo; } else { hostInfo = powerShellHostInfo; } // If the host was not null on the client, then the PowerShell object should // get a brand spanking new host. return new ServerRemoteHost(_clientRunspacePoolId, _clientPowerShellId, hostInfo, _transportManager, runspaceServerRemoteHost.Runspace, runspaceServerRemoteHost as ServerDriverRemoteHost); } #endregion Data Structure Handler Methods #region Data Structure Handler events /// <summary> /// this event is raised when the state of associated /// powershell is terminal and the runspace pool has /// to detach the association /// </summary> internal event EventHandler RemoveAssociation; /// <summary> /// this event is raised when the a message to stop the /// powershell is received from the client /// </summary> internal event EventHandler StopPowerShellReceived; /// <summary> /// This event is raised when an input object is received /// from the client /// </summary> internal event EventHandler<RemoteDataEventArgs<object>> InputReceived; /// <summary> /// This event is raised when end of input is received from /// the client /// </summary> internal event EventHandler InputEndReceived; /// <summary> /// raised when server session is connected from a new client /// </summary> internal event EventHandler OnSessionConnected; /// <summary> /// This event is raised when a host response is received /// </summary> internal event EventHandler<RemoteDataEventArgs<RemoteHostResponse>> HostResponseReceived; #endregion Data Structure Handler events #region Internal Methods /// <summary> /// client powershell id /// </summary> internal Guid PowerShellId { get { return _clientPowerShellId; } } /// <summary> /// Runspace used to invoke PowerShell, this is used by the steppable /// pipeline driver. /// </summary> internal Runspace RunspaceUsedToInvokePowerShell { get { return _rsUsedToInvokePowerShell; } } #endregion Internal Methods #region Private Methods /// <summary> /// Send the data specified as a RemoteDataObject asynchronously /// to the runspace pool on the remote session /// </summary> /// <param name="data">data to send</param> /// <remarks>This overload takes a RemoteDataObject and should /// be the one thats used to send data from within this /// data structure handler class</remarks> private void SendDataAsync(RemoteDataObject data) { Dbg.Assert(null != data, "Cannot send null object."); // this is from a command execution..let transport manager collect // as much data as possible and send bigger buffer to client. _transportManager.SendDataToClient(data, false); } /// <summary> /// Handle transport manager's closing event. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void HandleTransportClosing(object sender, EventArgs args) { StopPowerShellReceived.SafeInvoke(this, args); } #endregion Private Methods } }
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using NSubstitute; using Octokit.Tests.Helpers; using Xunit; namespace Octokit.Tests.Clients { /// <summary> /// Client tests mostly just need to make sure they call the IApiConnection with the correct /// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs. /// </summary> public class RepositoriesClientTests { public class TheConstructor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>(() => new RepositoriesClient(null)); } } public class TheCreateMethodForUser { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create(null)); } [Fact] public void UsesTheUserReposUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.Create(new NewRepository("aName")); connection.Received().Post<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Any<NewRepository>()); } [Fact] public void TheNewRepositoryDescription() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var newRepository = new NewRepository("aName"); client.Create(newRepository); connection.Received().Post<Repository>(Args.Uri, newRepository); } [Fact] public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForCurrentUser() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var credentials = new Credentials("haacked", "pwd"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Connection.Credentials.Returns(credentials); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<RepositoryExistsException>( () => client.Create(newRepository)); Assert.False(exception.OwnerIsOrganization); Assert.Null(exception.Organization); Assert.Equal("aName", exception.RepositoryName); Assert.Null(exception.ExistingRepositoryWebUrl); } [Fact] public async Task ThrowsExceptionWhenPrivateRepositoryQuotaExceeded() { var newRepository = new NewRepository("aName") { Private = true }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":" + @"""name can't be private. You are over your quota.""}]}"); var credentials = new Credentials("haacked", "pwd"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Connection.Credentials.Returns(credentials); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<PrivateRepositoryQuotaExceededException>( () => client.Create(newRepository)); Assert.NotNull(exception); } } public class TheCreateMethodForOrganization { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create(null, new NewRepository("aName"))); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create("aLogin", null)); } [Fact] public async Task UsesTheOrganizatinosReposUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Create("theLogin", new NewRepository("aName")); connection.Received().Post<Repository>( Arg.Is<Uri>(u => u.ToString() == "orgs/theLogin/repos"), Args.NewRepository); } [Fact] public async Task TheNewRepositoryDescription() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var newRepository = new NewRepository("aName"); await client.Create("aLogin", newRepository); connection.Received().Post<Repository>(Args.Uri, newRepository); } [Fact] public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForSpecifiedOrg() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<RepositoryExistsException>( () => client.Create("illuminati", newRepository)); Assert.True(exception.OwnerIsOrganization); Assert.Equal("illuminati", exception.Organization); Assert.Equal("aName", exception.RepositoryName); Assert.Equal(new Uri("https://github.com/illuminati/aName"), exception.ExistingRepositoryWebUrl); Assert.Equal("There is already a repository named 'aName' in the organization 'illuminati'.", exception.Message); } [Fact] public async Task ThrowsValidationException() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<ApiValidationException>( () => client.Create("illuminati", newRepository)); Assert.Null(exception as RepositoryExistsException); } [Fact] public async Task ThrowsRepositoryExistsExceptionForEnterpriseInstance() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(new Uri("https://example.com")); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<RepositoryExistsException>( () => client.Create("illuminati", newRepository)); Assert.Equal("aName", exception.RepositoryName); Assert.Equal(new Uri("https://example.com/illuminati/aName"), exception.ExistingRepositoryWebUrl); } } public class TheDeleteMethod { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Delete(null, "aRepoName")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Delete("anOwner", null)); } [Fact] public async Task RequestsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Delete("theOwner", "theRepoName"); connection.Received().Delete(Arg.Is<Uri>(u => u.ToString() == "repos/theOwner/theRepoName")); } } public class TheGetMethod { [Fact] public void RequestsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.Get("fake", "repo"); connection.Received().Get<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo")); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "name")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null)); } } public class TheGetAllPublicMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllPublic(); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "/repositories")); } } public class TheGetAllPublicSinceMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllPublic(new PublicRepositoryRequest(364)); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "/repositories?since=364")); } [Fact] public void SendsTheCorrectParameter() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllPublic(new PublicRepositoryRequest(364)); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "/repositories?since=364")); } } public class TheGetAllForCurrentMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllForCurrent(); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos")); } [Fact] public void CanFilterByType() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Type = RepositoryType.All }; client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["type"] == "all")); } [Fact] public void CanFilterBySort() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Type = RepositoryType.Private, Sort = RepositorySort.FullName }; client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["type"] == "private" && d["sort"] == "full_name")); } [Fact] public void CanFilterBySortDirection() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Type = RepositoryType.Member, Sort = RepositorySort.Updated, Direction = SortDirection.Ascending }; client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["type"] == "member" && d["sort"] == "updated" && d["direction"] == "asc")); } [Fact] public void CanFilterByVisibility() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Visibility = RepositoryVisibility.Private }; client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["visibility"] == "private")); } [Fact] public void CanFilterByAffiliation() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Affiliation = RepositoryAffiliation.Owner, Sort = RepositorySort.FullName }; client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["affiliation"] == "owner" && d["sort"] == "full_name")); } } public class TheGetAllForUserMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllForUser("username"); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "users/username/repos")); } [Fact] public async Task EnsuresNonNullArguments() { var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForUser(null)); } } public class TheGetAllForOrgMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllForOrg("orgname"); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "orgs/orgname/repos")); } [Fact] public async Task EnsuresNonNullArguments() { var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForOrg(null)); } } public class TheGetAllBranchesMethod { [Fact] public void ReturnsBranches() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllBranches("owner", "name"); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json"); } [Fact] public async Task EnsuresArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("owner", "")); } } public class TheGetAllContributorsMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllContributors("owner", "name"); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Any<IDictionary<string, string>>()); } [Fact] public async Task EnsuresArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("owner", "")); } } public class TheGetAllLanguagesMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllLanguages("owner", "name"); connection.Received() .Get<Dictionary<string, long>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/languages")); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllLanguages(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllLanguages("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllLanguages("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllLanguages("owner", "")); } } public class TheGetAllTeamsMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllTeams("owner", "name"); connection.Received() .GetAll<Team>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/teams")); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("owner", "")); } } public class TheGetAllTagsMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllTags("owner", "name"); connection.Received() .GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/tags")); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("owner", "")); } } public class TheGetBranchMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetBranch("owner", "repo", "branch"); connection.Received() .Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), null, "application/vnd.github.loki-preview+json"); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("owner", "repo", "")); } } public class TheEditMethod { [Fact] public void PatchesCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new RepositoryUpdate(); client.Edit("owner", "repo", update); connection.Received() .Patch<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo"), Arg.Any<RepositoryUpdate>()); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); var update = new RepositoryUpdate(); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(null, "repo", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("", "repo", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("owner", "", update)); } } public class TheCompareMethod { [Fact] public async Task EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare(null, "repo", "base", "head")); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("", "repo", "base", "head")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", null, "base", "head")); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "", "base", "head")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", "repo", null, "head")); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "repo", "", "head")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", "repo", "base", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "repo", "base", "")); } [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Compare("owner", "repo", "base", "head"); connection.Received() .Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...head")); } [Fact] public void EncodesUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Compare("owner", "repo", "base", "shiftkey/my-cool-branch"); connection.Received() .Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...shiftkey%2Fmy-cool-branch")); } } public class TheGetCommitMethod { [Fact] public async Task EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "repo", "reference")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("", "repo", "reference")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null, "reference")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "", "reference")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "repo", "")); } [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Get("owner", "name", "reference"); connection.Received() .Get<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits/reference")); } } public class TheGetAllCommitsMethod { [Fact] public async Task EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", "")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", "repo", null)); } [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.GetAll("owner", "name"); connection.Received() .GetAll<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits"), Arg.Any<Dictionary<string, string>>()); } } public class TheEditBranchMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new BranchUpdate(); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.EditBranch("owner", "repo", "branch", update); connection.Received() .Patch<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), Arg.Any<BranchUpdate>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); var update = new BranchUpdate(); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch(null, "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", null, "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", "repo", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("", "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("owner", "", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("owner", "repo", "", update)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Data.Common; using System.Diagnostics; using System.Globalization; namespace System.Data.OleDb { public sealed class OleDbCommandBuilder : DbCommandBuilder { public OleDbCommandBuilder() : base() { GC.SuppressFinalize(this); } public OleDbCommandBuilder(OleDbDataAdapter adapter) : this() { DataAdapter = adapter; } [DefaultValue(null)] public new OleDbDataAdapter DataAdapter { get { return (base.DataAdapter as OleDbDataAdapter); } set { base.DataAdapter = value; } } private void OleDbRowUpdatingHandler(object sender, OleDbRowUpdatingEventArgs ruevent) { RowUpdatingHandler(ruevent); } public new OleDbCommand GetInsertCommand() { return (OleDbCommand)base.GetInsertCommand(); } public new OleDbCommand GetInsertCommand(bool useColumnsForParameterNames) { return (OleDbCommand)base.GetInsertCommand(useColumnsForParameterNames); } public new OleDbCommand GetUpdateCommand() { return (OleDbCommand)base.GetUpdateCommand(); } public new OleDbCommand GetUpdateCommand(bool useColumnsForParameterNames) { return (OleDbCommand)base.GetUpdateCommand(useColumnsForParameterNames); } public new OleDbCommand GetDeleteCommand() { return (OleDbCommand)base.GetDeleteCommand(); } public new OleDbCommand GetDeleteCommand(bool useColumnsForParameterNames) { return (OleDbCommand)base.GetDeleteCommand(useColumnsForParameterNames); } protected override string GetParameterName(int parameterOrdinal) { return "p" + parameterOrdinal.ToString(System.Globalization.CultureInfo.InvariantCulture); } protected override string GetParameterName(string parameterName) { return parameterName; } protected override string GetParameterPlaceholder(int parameterOrdinal) { return "?"; } protected override void ApplyParameterInfo(DbParameter parameter, DataRow datarow, StatementType statementType, bool whereClause) { OleDbParameter p = (OleDbParameter)parameter; object valueType = datarow[SchemaTableColumn.ProviderType]; p.OleDbType = (OleDbType)valueType; object bvalue = datarow[SchemaTableColumn.NumericPrecision]; if (DBNull.Value != bvalue) { byte bval = (byte)(short)bvalue; p.PrecisionInternal = ((0xff != bval) ? bval : (byte)0); } bvalue = datarow[SchemaTableColumn.NumericScale]; if (DBNull.Value != bvalue) { byte bval = (byte)(short)bvalue; p.ScaleInternal = ((0xff != bval) ? bval : (byte)0); } } public static void DeriveParameters(OleDbCommand command) { if (null == command) { throw ADP.ArgumentNull("command"); } switch (command.CommandType) { case System.Data.CommandType.Text: throw ADP.DeriveParametersNotSupported(command); case System.Data.CommandType.StoredProcedure: break; case System.Data.CommandType.TableDirect: // CommandType.TableDirect - do nothing, parameters are not supported throw ADP.DeriveParametersNotSupported(command); default: throw ADP.InvalidCommandType(command.CommandType); } if (ADP.IsEmpty(command.CommandText)) { throw ADP.CommandTextRequired(ADP.DeriveParameters); } OleDbConnection connection = command.Connection; if (null == connection) { throw ADP.ConnectionRequired(ADP.DeriveParameters); } ConnectionState state = connection.State; if (ConnectionState.Open != state) { throw ADP.OpenConnectionRequired(ADP.DeriveParameters, state); } OleDbParameter[] list = DeriveParametersFromStoredProcedure(connection, command); OleDbParameterCollection parameters = command.Parameters; parameters.Clear(); for (int i = 0; i < list.Length; ++i) { parameters.Add(list[i]); } } // known difference: when getting the parameters for a sproc, the // return value gets marked as a return value but for a sql stmt // the return value gets marked as an output parameter. private static OleDbParameter[] DeriveParametersFromStoredProcedure(OleDbConnection connection, OleDbCommand command) { OleDbParameter[] plist = Array.Empty<OleDbParameter>(); if (connection.SupportSchemaRowset(OleDbSchemaGuid.Procedure_Parameters)) { string quotePrefix, quoteSuffix; connection.GetLiteralQuotes(ADP.DeriveParameters, out quotePrefix, out quoteSuffix); object[] parsed = MultipartIdentifier.ParseMultipartIdentifier(command.CommandText, quotePrefix, quoteSuffix, '.', 4, true, SR.OLEDB_OLEDBCommandText, false); if (null == parsed[3]) { throw ADP.NoStoredProcedureExists(command.CommandText); } object[] restrictions = new object[4]; object value; // Parse returns an enforced 4 part array // 0) Server - ignored but removal would be a run-time breaking change from V1.0 // 1) Catalog // 2) Schema // 3) ProcedureName // Restrictions array which is passed to OleDb API expects: // 0) Catalog // 1) Schema // 2) ProcedureName // 3) ParameterName (leave null) // Copy from Parse format to OleDb API format Array.Copy(parsed, 1, restrictions, 0, 3); //if (cmdConnection.IsServer_msdaora) { // restrictions[1] = Convert.ToString(cmdConnection.UserId).ToUpper(); //} DataTable table = connection.GetSchemaRowset(OleDbSchemaGuid.Procedure_Parameters, restrictions); if (null != table) { DataColumnCollection columns = table.Columns; DataColumn parameterName = null; DataColumn parameterDirection = null; DataColumn dataType = null; DataColumn maxLen = null; DataColumn numericPrecision = null; DataColumn numericScale = null; DataColumn backendtype = null; int index = columns.IndexOf(ODB.PARAMETER_NAME); if (-1 != index) parameterName = columns[index]; index = columns.IndexOf(ODB.PARAMETER_TYPE); if (-1 != index) parameterDirection = columns[index]; index = columns.IndexOf(ODB.DATA_TYPE); if (-1 != index) dataType = columns[index]; index = columns.IndexOf(ODB.CHARACTER_MAXIMUM_LENGTH); if (-1 != index) maxLen = columns[index]; index = columns.IndexOf(ODB.NUMERIC_PRECISION); if (-1 != index) numericPrecision = columns[index]; index = columns.IndexOf(ODB.NUMERIC_SCALE); if (-1 != index) numericScale = columns[index]; index = columns.IndexOf(ODB.TYPE_NAME); if (-1 != index) backendtype = columns[index]; DataRow[] dataRows = table.Select(null, ODB.ORDINAL_POSITION_ASC, DataViewRowState.CurrentRows); plist = new OleDbParameter[dataRows.Length]; for (index = 0; index < dataRows.Length; ++index) { DataRow dataRow = dataRows[index]; OleDbParameter parameter = new OleDbParameter(); if ((null != parameterName) && !dataRow.IsNull(parameterName, DataRowVersion.Default)) { // $CONSIDER - not trimming the @ from the beginning but to left the designer do that parameter.ParameterName = Convert.ToString(dataRow[parameterName, DataRowVersion.Default], CultureInfo.InvariantCulture).TrimStart(new char[] { '@', ' ', ':' }); } if ((null != parameterDirection) && !dataRow.IsNull(parameterDirection, DataRowVersion.Default)) { short direction = Convert.ToInt16(dataRow[parameterDirection, DataRowVersion.Default], CultureInfo.InvariantCulture); parameter.Direction = ConvertToParameterDirection(direction); } if ((null != dataType) && !dataRow.IsNull(dataType, DataRowVersion.Default)) { // need to ping FromDBType, otherwise WChar->WChar when the user really wants VarWChar short wType = Convert.ToInt16(dataRow[dataType, DataRowVersion.Default], CultureInfo.InvariantCulture); parameter.OleDbType = NativeDBType.FromDBType(wType, false, false).enumOleDbType; } if ((null != maxLen) && !dataRow.IsNull(maxLen, DataRowVersion.Default)) { parameter.Size = Convert.ToInt32(dataRow[maxLen, DataRowVersion.Default], CultureInfo.InvariantCulture); } switch (parameter.OleDbType) { case OleDbType.Decimal: case OleDbType.Numeric: case OleDbType.VarNumeric: if ((null != numericPrecision) && !dataRow.IsNull(numericPrecision, DataRowVersion.Default)) { // @devnote: unguarded cast from Int16 to Byte parameter.PrecisionInternal = (byte)Convert.ToInt16(dataRow[numericPrecision], CultureInfo.InvariantCulture); } if ((null != numericScale) && !dataRow.IsNull(numericScale, DataRowVersion.Default)) { // @devnote: unguarded cast from Int16 to Byte parameter.ScaleInternal = (byte)Convert.ToInt16(dataRow[numericScale], CultureInfo.InvariantCulture); } break; case OleDbType.VarBinary: case OleDbType.VarChar: case OleDbType.VarWChar: value = dataRow[backendtype, DataRowVersion.Default]; if (value is string) { string backendtypename = ((string)value).ToLower(CultureInfo.InvariantCulture); switch (backendtypename) { case "binary": parameter.OleDbType = OleDbType.Binary; break; //case "varbinary": // parameter.OleDbType = OleDbType.VarBinary; // break; case "image": parameter.OleDbType = OleDbType.LongVarBinary; break; case "char": parameter.OleDbType = OleDbType.Char; break; //case "varchar": //case "varchar2": // parameter.OleDbType = OleDbType.VarChar; // break; case "text": parameter.OleDbType = OleDbType.LongVarChar; break; case "nchar": parameter.OleDbType = OleDbType.WChar; break; //case "nvarchar": // parameter.OleDbType = OleDbType.VarWChar; case "ntext": parameter.OleDbType = OleDbType.LongVarWChar; break; } } break; } //if (AdapterSwitches.OleDbSql.TraceVerbose) { // ADP.Trace_Parameter("StoredProcedure", parameter); //} plist[index] = parameter; } } if ((0 == plist.Length) && connection.SupportSchemaRowset(OleDbSchemaGuid.Procedures)) { restrictions = new object[4] { null, null, command.CommandText, null }; table = connection.GetSchemaRowset(OleDbSchemaGuid.Procedures, restrictions); if (0 == table.Rows.Count) { throw ADP.NoStoredProcedureExists(command.CommandText); } } } else if (connection.SupportSchemaRowset(OleDbSchemaGuid.Procedures)) { object[] restrictions = new object[4] { null, null, command.CommandText, null }; DataTable table = connection.GetSchemaRowset(OleDbSchemaGuid.Procedures, restrictions); if (0 == table.Rows.Count) { throw ADP.NoStoredProcedureExists(command.CommandText); } // we don't ever expect a procedure with 0 parameters, they should have at least a return value throw ODB.NoProviderSupportForSProcResetParameters(connection.Provider); } else { throw ODB.NoProviderSupportForSProcResetParameters(connection.Provider); } return plist; } private static ParameterDirection ConvertToParameterDirection(int value) => value switch { ODB.DBPARAMTYPE_INPUT => System.Data.ParameterDirection.Input, ODB.DBPARAMTYPE_INPUTOUTPUT => System.Data.ParameterDirection.InputOutput, ODB.DBPARAMTYPE_OUTPUT => System.Data.ParameterDirection.Output, ODB.DBPARAMTYPE_RETURNVALUE => System.Data.ParameterDirection.ReturnValue, _ => System.Data.ParameterDirection.Input, }; public override string QuoteIdentifier(string unquotedIdentifier) { return QuoteIdentifier(unquotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */); } public string QuoteIdentifier(string unquotedIdentifier, OleDbConnection connection) { ADP.CheckArgumentNull(unquotedIdentifier, "unquotedIdentifier"); // if the user has specificed a prefix use the user specified prefix and suffix // otherwise get them from the provider string quotePrefix = QuotePrefix; string quoteSuffix = QuoteSuffix; if (ADP.IsEmpty(quotePrefix) == true) { if (connection == null) { // Use the adapter's connection if QuoteIdentifier was called from // DbCommandBuilder instance (which does not have an overload that gets connection object) connection = DataAdapter?.SelectCommand?.Connection; if (connection == null) { throw ADP.QuotePrefixNotSet(ADP.QuoteIdentifier); } } connection.GetLiteralQuotes(ADP.QuoteIdentifier, out quotePrefix, out quoteSuffix); // if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec // IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.) if (quoteSuffix == null) { quoteSuffix = quotePrefix; } } return ADP.BuildQuotedString(quotePrefix, quoteSuffix, unquotedIdentifier); } protected override void SetRowUpdatingHandler(DbDataAdapter adapter) { Debug.Assert(adapter is OleDbDataAdapter, "!OleDbDataAdapter"); if (adapter == base.DataAdapter) { // removal case ((OleDbDataAdapter)adapter).RowUpdating -= OleDbRowUpdatingHandler; } else { // adding case ((OleDbDataAdapter)adapter).RowUpdating += OleDbRowUpdatingHandler; } } public override string UnquoteIdentifier(string quotedIdentifier) { return UnquoteIdentifier(quotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */); } public string UnquoteIdentifier(string quotedIdentifier, OleDbConnection connection) { ADP.CheckArgumentNull(quotedIdentifier, "quotedIdentifier"); // if the user has specificed a prefix use the user specified prefix and suffix // otherwise get them from the provider string quotePrefix = QuotePrefix; string quoteSuffix = QuoteSuffix; if (ADP.IsEmpty(quotePrefix) == true) { if (connection == null) { // Use the adapter's connection if UnquoteIdentifier was called from // DbCommandBuilder instance (which does not have an overload that gets connection object) connection = DataAdapter?.SelectCommand?.Connection; if (connection == null) { throw ADP.QuotePrefixNotSet(ADP.UnquoteIdentifier); } } connection.GetLiteralQuotes(ADP.UnquoteIdentifier, out quotePrefix, out quoteSuffix); // if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec // IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.) if (quoteSuffix == null) { quoteSuffix = quotePrefix; } } string unquotedIdentifier; // ignoring the return value because it is acceptable for the quotedString to not be quoted in this // context. ADP.RemoveStringQuotes(quotePrefix, quoteSuffix, quotedIdentifier, out unquotedIdentifier); return unquotedIdentifier; } } }
// InflaterHuffmanTree.cs // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. #if CONFIG_COMPRESSION using System; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; namespace ICSharpCode.SharpZipLib.Zip.Compression { internal class InflaterHuffmanTree { private static int MAX_BITLEN = 15; private short[] tree; public static InflaterHuffmanTree defLitLenTree, defDistTree; static InflaterHuffmanTree() { try { byte[] codeLengths = new byte[288]; int i = 0; while (i < 144) { codeLengths[i++] = 8; } while (i < 256) { codeLengths[i++] = 9; } while (i < 280) { codeLengths[i++] = 7; } while (i < 288) { codeLengths[i++] = 8; } defLitLenTree = new InflaterHuffmanTree(codeLengths); codeLengths = new byte[32]; i = 0; while (i < 32) { codeLengths[i++] = 5; } defDistTree = new InflaterHuffmanTree(codeLengths); } catch (Exception) { throw new ApplicationException("InflaterHuffmanTree: static tree length illegal"); } } /// <summary> /// Constructs a Huffman tree from the array of code lengths. /// </summary> /// <param name = "codeLengths"> /// the array of code lengths /// </param> public InflaterHuffmanTree(byte[] codeLengths) { BuildTree(codeLengths); } private void BuildTree(byte[] codeLengths) { int[] blCount = new int[MAX_BITLEN + 1]; int[] nextCode = new int[MAX_BITLEN + 1]; for (int i = 0; i < codeLengths.Length; i++) { int bits = codeLengths[i]; if (bits > 0) blCount[bits]++; } int code = 0; int treeSize = 512; for (int bits = 1; bits <= MAX_BITLEN; bits++) { nextCode[bits] = code; code += blCount[bits] << (16 - bits); if (bits >= 10) { /* We need an extra table for bit lengths >= 10. */ int start = nextCode[bits] & 0x1ff80; int end = code & 0x1ff80; treeSize += (end - start) >> (16 - bits); } } if (code != 65536) { throw new Exception("Code lengths don't add up properly."); } /* Now create and fill the extra tables from longest to shortest * bit len. This way the sub trees will be aligned. */ tree = new short[treeSize]; int treePtr = 512; for (int bits = MAX_BITLEN; bits >= 10; bits--) { int end = code & 0x1ff80; code -= blCount[bits] << (16 - bits); int start = code & 0x1ff80; for (int i = start; i < end; i += 1 << 7) { tree[DeflaterHuffman.BitReverse(i)] = (short) ((-treePtr << 4) | bits); treePtr += 1 << (bits-9); } } for (int i = 0; i < codeLengths.Length; i++) { int bits = codeLengths[i]; if (bits == 0) { continue; } code = nextCode[bits]; int revcode = DeflaterHuffman.BitReverse(code); if (bits <= 9) { do { tree[revcode] = (short) ((i << 4) | bits); revcode += 1 << bits; } while (revcode < 512); } else { int subTree = tree[revcode & 511]; int treeLen = 1 << (subTree & 15); subTree = -(subTree >> 4); do { tree[subTree | (revcode >> 9)] = (short) ((i << 4) | bits); revcode += 1 << bits; } while (revcode < treeLen); } nextCode[bits] = code + (1 << (16 - bits)); } } /// <summary> /// Reads the next symbol from input. The symbol is encoded using the /// huffman tree. /// </summary> /// <param name="input"> /// input the input source. /// </param> /// <returns> /// the next symbol, or -1 if not enough input is available. /// </returns> public int GetSymbol(StreamManipulator input) { int lookahead, symbol; if ((lookahead = input.PeekBits(9)) >= 0) { if ((symbol = tree[lookahead]) >= 0) { input.DropBits(symbol & 15); return symbol >> 4; } int subtree = -(symbol >> 4); int bitlen = symbol & 15; if ((lookahead = input.PeekBits(bitlen)) >= 0) { symbol = tree[subtree | (lookahead >> 9)]; input.DropBits(symbol & 15); return symbol >> 4; } else { int bits = input.AvailableBits; lookahead = input.PeekBits(bits); symbol = tree[subtree | (lookahead >> 9)]; if ((symbol & 15) <= bits) { input.DropBits(symbol & 15); return symbol >> 4; } else { return -1; } } } else { int bits = input.AvailableBits; lookahead = input.PeekBits(bits); symbol = tree[lookahead]; if (symbol >= 0 && (symbol & 15) <= bits) { input.DropBits(symbol & 15); return symbol >> 4; } else { return -1; } } } } } #endif // CONFIG_COMPRESSION
// 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.ObjectModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime; using System.Runtime.Versioning; namespace System.Collections.Generic { // Implements a variable-size List that uses an array of objects to store the // elements. A List has a capacity, which is the allocated length // of the internal array. As elements are added to a List, the capacity // of the List is automatically increased as required by reallocating the // internal array. // [DebuggerTypeProxy(typeof(ICollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T> { private const int _defaultCapacity = 4; private T[] _items; [ContractPublicPropertyName("Count")] private int _size; private int _version; [NonSerialized] private object _syncRoot; private static readonly T[] s_emptyArray = new T[0]; // Constructs a List. The list is initially empty and has a capacity // of zero. Upon adding the first element to the list the capacity is // increased to _defaultCapacity, and then increased in multiples of two // as required. public List() { _items = s_emptyArray; } // Constructs a List with a given initial capacity. The list is // initially empty, but will have room for the given number of elements // before any reallocations are required. // public List(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (capacity == 0) _items = s_emptyArray; else _items = new T[capacity]; } // Constructs a List, copying the contents of the given collection. The // size and capacity of the new list will both be equal to the size of the // given collection. // public List(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); Contract.EndContractBlock(); ICollection<T> c = collection as ICollection<T>; if (c != null) { int count = c.Count; if (count == 0) { _items = s_emptyArray; } else { _items = new T[count]; c.CopyTo(_items, 0); _size = count; } } else { _size = 0; _items = s_emptyArray; // This enumerable could be empty. Let Add allocate a new array, if needed. // Note it will also go to _defaultCapacity first, not 1, then 2, etc. using (IEnumerator<T> en = collection.GetEnumerator()) { while (en.MoveNext()) { Add(en.Current); } } } } // Gets and sets the capacity of this list. The capacity is the size of // the internal array used to hold items. When set, the internal // array of the list is reallocated to the given capacity. // public int Capacity { get { Contract.Ensures(Contract.Result<int>() >= 0); return _items.Length; } set { if (value < _size) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_SmallCapacity); } Contract.EndContractBlock(); if (value != _items.Length) { if (value > 0) { var items = new T[value]; Array.Copy(_items, 0, items, 0, _size); _items = items; } else { _items = s_emptyArray; } } } } // Read-only property describing how many elements are in the List. public int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); return _size; } } bool System.Collections.IList.IsFixedSize { get { return false; } } // Is this List read-only? bool ICollection<T>.IsReadOnly { get { return false; } } bool System.Collections.IList.IsReadOnly { get { return false; } } // Is this List synchronized (thread-safe)? bool System.Collections.ICollection.IsSynchronized { get { return false; } } // Synchronization root for this object. object System.Collections.ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null); } return _syncRoot; } } // Sets or Gets the element at the given index. public T this[int index] { get { // Following trick can reduce the range check by one if ((uint)index >= (uint)_size) { throw new ArgumentOutOfRangeException(); } Contract.EndContractBlock(); return _items[index]; } set { if ((uint)index >= (uint)_size) { throw new ArgumentOutOfRangeException(); } Contract.EndContractBlock(); _items[index] = value; _version++; } } private static bool IsCompatibleObject(object value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable<U>. // Note that default(T) is not equal to null for value types except when T is Nullable<U>. return ((value is T) || (value == null && default(T) == null)); } object System.Collections.IList.this[int index] { get { return this[index]; } set { if (value == null && !(default(T) == null)) throw new ArgumentNullException(nameof(value)); try { this[index] = (T)value; } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(T)), nameof(value)); } } } // Adds the given object to the end of this list. The size of the list is // increased by one. If required, the capacity of the list is doubled // before adding the new element. public void Add(T item) { if (_size == _items.Length) EnsureCapacity(_size + 1); _items[_size++] = item; _version++; } int System.Collections.IList.Add(object item) { if (item == null && !(default(T) == null)) throw new ArgumentNullException(nameof(item)); try { Add((T)item); } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, item, typeof(T)), nameof(item)); } return Count - 1; } // Adds the elements of the given collection to the end of this list. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. public void AddRange(IEnumerable<T> collection) { Contract.Ensures(Count >= Contract.OldValue(Count)); InsertRange(_size, collection); } public ReadOnlyCollection<T> AsReadOnly() { return new ReadOnlyCollection<T>(this); } // Searches a section of the list for a given element using a binary search // algorithm. Elements of the list are compared to the search value using // the given IComparer interface. If comparer is null, elements of // the list are compared to the search value using the IComparable // interface, which in that case must be implemented by all elements of the // list and the given search value. This method assumes that the given // section of the list is already sorted; if this is not the case, the // result will be incorrect. // // The method returns the index of the given value in the list. If the // list does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. This is also the index at which // the search value should be inserted into the list in order for the list // to remain sorted. // // The method uses the Array.BinarySearch method to perform the // search. public int BinarySearch(int index, int count, T item, IComparer<T> comparer) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.Ensures(Contract.Result<int>() <= index + count); Contract.EndContractBlock(); return Array.BinarySearch<T>(_items, index, count, item, comparer); } public int BinarySearch(T item) { Contract.Ensures(Contract.Result<int>() <= Count); return BinarySearch(0, Count, item, null); } public int BinarySearch(T item, IComparer<T> comparer) { Contract.Ensures(Contract.Result<int>() <= Count); return BinarySearch(0, Count, item, comparer); } // Clears the contents of List. public void Clear() { if (_size > 0) { Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; } _version++; } // Contains returns true if the specified element is in the List. // It does a linear, O(n) search. Equality is determined by calling // EqualityComparer<T>.Default.Equals(). public bool Contains(T item) { // PERF: IndexOf calls Array.IndexOf, which internally // calls EqualityComparer<T>.Default.IndexOf, which // is specialized for different types. This // boosts performance since instead of making a // virtual method call each iteration of the loop, // via EqualityComparer<T>.Default.Equals, we // only make one virtual call to EqualityComparer.IndexOf. return _size != 0 && IndexOf(item) != -1; } bool System.Collections.IList.Contains(object item) { if (IsCompatibleObject(item)) { return Contains((T)item); } return false; } public List<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter) { if (converter == null) { throw new ArgumentNullException(nameof(converter)); } Contract.EndContractBlock(); List<TOutput> list = new List<TOutput>(_size); for (int i = 0; i < _size; i++) { list._items[i] = converter(_items[i]); } list._size = _size; return list; } // Copies this List into array, which must be of a // compatible array type. public void CopyTo(T[] array) { CopyTo(array, 0); } // Copies this List into array, which must be of a // compatible array type. void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) { if ((array != null) && (array.Rank != 1)) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } Contract.EndContractBlock(); try { // Array.Copy will check for NULL. Array.Copy(_items, 0, array, arrayIndex, _size); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } // Copies a section of this list to the given array at the given index. // // The method uses the Array.Copy method to copy the elements. public void CopyTo(int index, T[] array, int arrayIndex, int count) { if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } Contract.EndContractBlock(); // Delegate rest of error checking to Array.Copy. Array.Copy(_items, index, array, arrayIndex, count); } public void CopyTo(T[] array, int arrayIndex) { // Delegate rest of error checking to Array.Copy. Array.Copy(_items, 0, array, arrayIndex, _size); } // Ensures that the capacity of this list is at least the given minimum // value. If the current capacity of the list is less than min, the // capacity is increased to twice the current capacity or to min, // whichever is larger. private void EnsureCapacity(int min) { if (_items.Length < min) { int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast //if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength; if (newCapacity < min) newCapacity = min; Capacity = newCapacity; } } public bool Exists(Predicate<T> match) { return FindIndex(match) != -1; } public T Find(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); for (int i = 0; i < _size; i++) { if (match(_items[i])) { return _items[i]; } } return default(T); } public List<T> FindAll(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); List<T> list = new List<T>(); for (int i = 0; i < _size; i++) { if (match(_items[i])) { list.Add(_items[i]); } } return list; } public int FindIndex(Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return FindIndex(0, _size, match); } public int FindIndex(int startIndex, Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < startIndex + Count); return FindIndex(startIndex, _size - startIndex, match); } public int FindIndex(int startIndex, int count, Predicate<T> match) { if ((uint)startIndex > (uint)_size) { throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > _size - count) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count); } if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < startIndex + count); Contract.EndContractBlock(); int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) { if (match(_items[i])) return i; } return -1; } public T FindLast(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); for (int i = _size - 1; i >= 0; i--) { if (match(_items[i])) { return _items[i]; } } return default(T); } public int FindLastIndex(Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return FindLastIndex(_size - 1, _size, match); } public int FindLastIndex(int startIndex, Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() <= startIndex); return FindLastIndex(startIndex, startIndex + 1, match); } public int FindLastIndex(int startIndex, int count, Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() <= startIndex); Contract.EndContractBlock(); if (_size == 0) { // Special case for 0 length List if (startIndex != -1) { throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, SR.ArgumentOutOfRange_Index); } } else if ((uint)startIndex >= (uint)_size) // Make sure we're not out of range { throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, SR.ArgumentOutOfRange_Index); } // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count); } int endIndex = startIndex - count; for (int i = startIndex; i > endIndex; i--) { if (match(_items[i])) { return i; } } return -1; } public void ForEach(Action<T> action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } int version = _version; for (int i = 0; i < _size; i++) { if (version != _version) { break; } action(_items[i]); } if (version != _version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } // Returns an enumerator for this list with the given // permission for removal of elements. If modifications made to the list // while an enumeration is in progress, the MoveNext and // GetObject methods of the enumerator will throw an exception. public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } public List<T> GetRange(int index, int count) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } Contract.Ensures(Contract.Result<List<T>>() != null); Contract.EndContractBlock(); List<T> list = new List<T>(count); Array.Copy(_items, index, list._items, 0, count); list._size = count; return list; } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards from beginning to end. // The elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. public int IndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return Array.IndexOf(_items, item, 0, _size); } int System.Collections.IList.IndexOf(object item) { if (IsCompatibleObject(item)) { return IndexOf((T)item); } return -1; } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // index and ending at count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. public int IndexOf(T item, int index) { if (index > _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); Contract.EndContractBlock(); return Array.IndexOf(_items, item, index, _size - index); } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // index and upto count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. public int IndexOf(T item, int index, int count) { if (index > _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); if (count < 0 || index > _size - count) throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); Contract.EndContractBlock(); return Array.IndexOf(_items, item, index, count); } // Inserts an element into this list at a given index. The size of the list // is increased by one. If required, the capacity of the list is doubled // before inserting the new element. public void Insert(int index, T item) { // Note that insertions at the end are legal. if ((uint)index > (uint)_size) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_BiggerThanCollection); } Contract.EndContractBlock(); if (_size == _items.Length) EnsureCapacity(_size + 1); if (index < _size) { Array.Copy(_items, index, _items, index + 1, _size - index); } _items[index] = item; _size++; _version++; } void System.Collections.IList.Insert(int index, object item) { if (item == null && !(default(T) == null)) throw new ArgumentNullException(nameof(item)); try { Insert(index, (T)item); } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, item, typeof(T)), nameof(item)); } } // Inserts the elements of the given collection at a given index. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. Ranges may be added // to the end of the list by setting index to the List's size. public void InsertRange(int index, IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if ((uint)index > (uint)_size) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } Contract.EndContractBlock(); ICollection<T> c = collection as ICollection<T>; if (c != null) { // if collection is ICollection<T> int count = c.Count; if (count > 0) { EnsureCapacity(_size + count); if (index < _size) { Array.Copy(_items, index, _items, index + count, _size - index); } // If we're inserting a List into itself, we want to be able to deal with that. if (this == c) { // Copy first part of _items to insert location Array.Copy(_items, 0, _items, index, index); // Copy last part of _items back to inserted location Array.Copy(_items, index + count, _items, index * 2, _size - index); } else { c.CopyTo(_items, index); } _size += count; } } else { using (IEnumerator<T> en = collection.GetEnumerator()) { while (en.MoveNext()) { Insert(index++, en.Current); } } } _version++; } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at the end // and ending at the first element in the list. The elements of the list // are compared to the given value using the Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. public int LastIndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); if (_size == 0) { // Special case for empty list return -1; } else { return LastIndexOf(item, _size - 1, _size); } } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // index and ending at the first element in the list. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. public int LastIndexOf(T item, int index) { if (index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index))); Contract.EndContractBlock(); return LastIndexOf(item, index, index + 1); } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // index and upto count elements. The elements of // the list are compared to the given value using the Object.Equals // method. // // This method uses the Array.LastIndexOf method to perform the // search. public int LastIndexOf(T item, int index, int count) { if ((Count != 0) && (index < 0)) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if ((Count != 0) && (count < 0)) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index))); Contract.EndContractBlock(); if (_size == 0) { // Special case for empty list return -1; } if (index >= _size) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } if (count > index + 1) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count); } return Array.LastIndexOf(_items, item, index, count); } // Removes the element at the given index. The size of the list is // decreased by one. public bool Remove(T item) { int index = IndexOf(item); if (index >= 0) { RemoveAt(index); return true; } return false; } void System.Collections.IList.Remove(object item) { if (IsCompatibleObject(item)) { Remove((T)item); } } // This method removes all items which matches the predicate. // The complexity is O(n). public int RemoveAll(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count)); Contract.EndContractBlock(); int freeIndex = 0; // the first free slot in items array // Find the first item which needs to be removed. while (freeIndex < _size && !match(_items[freeIndex])) freeIndex++; if (freeIndex >= _size) return 0; int current = freeIndex + 1; while (current < _size) { // Find the first item which needs to be kept. while (current < _size && match(_items[current])) current++; if (current < _size) { // copy item to the free slot. _items[freeIndex++] = _items[current++]; } } Array.Clear(_items, freeIndex, _size - freeIndex); int result = _size - freeIndex; _size = freeIndex; _version++; return result; } // Removes the element at the given index. The size of the list is // decreased by one. public void RemoveAt(int index) { if ((uint)index >= (uint)_size) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } Contract.EndContractBlock(); _size--; if (index < _size) { Array.Copy(_items, index + 1, _items, index, _size - index); } _items[_size] = default(T); _version++; } // Removes a range of elements from this list. public void RemoveRange(int index, int count) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (count > 0) { int i = _size; _size -= count; if (index < _size) { Array.Copy(_items, index + count, _items, index, _size - index); } Array.Clear(_items, _size, count); _version++; } } // Reverses the elements in this list. public void Reverse() { Reverse(0, Count); } // Reverses the elements in a range of this list. Following a call to this // method, an element in the range given by index and count // which was previously located at index i will now be located at // index index + (index + count - i - 1). public void Reverse(int index, int count) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // The non-generic Array.Reverse is not used because it does not perform // well for non-primitive value types. // If/when a generic Array.Reverse<T> becomes available, the below code // can be deleted and replaced with a call to Array.Reverse<T>. int i = index; int j = index + count - 1; T[] array = _items; while (i < j) { T temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } _version++; } // Sorts the elements in this list. Uses the default comparer and // Array.Sort. public void Sort() { Sort(0, Count, null); } // Sorts the elements in this list. Uses Array.Sort with the // provided comparer. public void Sort(IComparer<T> comparer) { Sort(0, Count, comparer); } // Sorts the elements in a section of this list. The sort compares the // elements to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented by all // elements of the list. // // This method uses the Array.Sort method to sort the elements. public void Sort(int index, int count, IComparer<T> comparer) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (count > 1) { Array.Sort<T>(_items, index, count, comparer); } _version++; } public void Sort(Comparison<T> comparison) { if (comparison == null) { throw new ArgumentNullException(nameof(comparison)); } Contract.EndContractBlock(); if (_size > 1) { ArraySortHelper<T>.Sort(_items, 0, _size, comparison); } _version++; } // ToArray returns a new Object array containing the contents of the List. // This requires copying the List, which is an O(n) operation. public T[] ToArray() { Contract.Ensures(Contract.Result<T[]>() != null); Contract.Ensures(Contract.Result<T[]>().Length == Count); if (_size == 0) { return s_emptyArray; } T[] array = new T[_size]; Array.Copy(_items, 0, array, 0, _size); return array; } // Sets the capacity of this list to the size of the list. This method can // be used to minimize a list's memory overhead once it is known that no // new elements will be added to the list. To completely clear a list and // release all memory referenced by the list, execute the following // statements: // // list.Clear(); // list.TrimExcess(); public void TrimExcess() { int threshold = (int)(((double)_items.Length) * 0.9); if (_size < threshold) { Capacity = _size; } } public bool TrueForAll(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); for (int i = 0; i < _size; i++) { if (!match(_items[i])) { return false; } } return true; } public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private List<T> _list; private int _index; private int _version; private T _current; internal Enumerator(List<T> list) { _list = list; _index = 0; _version = list._version; _current = default(T); } public void Dispose() { } public bool MoveNext() { List<T> localList = _list; if (_version == localList._version && ((uint)_index < (uint)localList._size)) { _current = localList._items[_index]; _index++; return true; } return MoveNextRare(); } private bool MoveNextRare() { if (_version != _list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = _list._size + 1; _current = default(T); return false; } public T Current { get { return _current; } } object System.Collections.IEnumerator.Current { get { if (_index == 0 || _index == _list._size + 1) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return Current; } } void System.Collections.IEnumerator.Reset() { if (_version != _list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = 0; _current = default(T); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Threading; using Microsoft.Internal; using Microsoft.Internal.Collections; using System.ComponentModel.Composition.Hosting; namespace System.ComponentModel.Composition.ReflectionModel { internal class ReflectionComposablePartDefinition : ComposablePartDefinition, ICompositionElement { private readonly IReflectionPartCreationInfo _creationInfo; private volatile ImportDefinition[] _imports; private volatile ExportDefinition[] _exports; private volatile IDictionary<string, object> _metadata; private volatile ConstructorInfo _constructor; private object _lock = new object(); public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo) { Assumes.NotNull(creationInfo); _creationInfo = creationInfo; } public Type GetPartType() { return _creationInfo.GetPartType(); } public Lazy<Type> GetLazyPartType() { return _creationInfo.GetLazyPartType(); } public ConstructorInfo GetConstructor() { if (_constructor == null) { ConstructorInfo constructor = _creationInfo.GetConstructor(); lock (_lock) { if (_constructor == null) { _constructor = constructor; } } } return _constructor; } private ExportDefinition[] ExportDefinitionsInternal { get { if (_exports == null) { ExportDefinition[] exports = _creationInfo.GetExports().ToArray(); lock (_lock) { if (_exports == null) { _exports = exports; } } } return _exports; } } public override IEnumerable<ExportDefinition> ExportDefinitions { get { return ExportDefinitionsInternal; } } public override IEnumerable<ImportDefinition> ImportDefinitions { get { if (_imports == null) { ImportDefinition[] imports = _creationInfo.GetImports().ToArray(); lock (_lock) { if (_imports == null) { _imports = imports; } } } return _imports; } } public override IDictionary<string, object> Metadata { get { if (_metadata == null) { IDictionary<string, object> metadata = _creationInfo.GetMetadata().AsReadOnly(); lock (_lock) { if (_metadata == null) { _metadata = metadata; } } } return _metadata; } } internal bool IsDisposalRequired { get { return _creationInfo.IsDisposalRequired; } } [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public override ComposablePart CreatePart() { if (IsDisposalRequired) { return new DisposableReflectionComposablePart(this); } else { return new ReflectionComposablePart(this); } } internal override ComposablePartDefinition GetGenericPartDefinition() { GenericSpecializationPartCreationInfo genericCreationInfo = _creationInfo as GenericSpecializationPartCreationInfo; if (genericCreationInfo != null) { return genericCreationInfo.OriginalPart; } return null; } internal override bool TryGetExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches) { if (this.IsGeneric()) { singleMatch = null; multipleMatches = null; List<Tuple<ComposablePartDefinition, ExportDefinition>> exports = null; var genericParameters = (definition.Metadata.Count > 0) ? definition.Metadata.GetValue<IEnumerable<object>>(CompositionConstants.GenericParametersMetadataName) : null; // if and only if generic parameters have been supplied can we attempt to "close" the generic if (genericParameters != null) { Type[] genericTypeParameters = null; // we only understand types if (TryGetGenericTypeParameters(genericParameters, out genericTypeParameters)) { HashSet<ComposablePartDefinition> candidates = null; ComposablePartDefinition candidatePart = null; ComposablePartDefinition previousPart = null; // go through all orders of generic parameters that part exports allows foreach (Type[] candidateParameters in GetCandidateParameters(genericTypeParameters)) { if (TryMakeGenericPartDefinition(candidateParameters, out candidatePart)) { bool alreadyProcessed = false; if(candidates == null) { if(previousPart != null) { if(candidatePart.Equals(previousPart)) { alreadyProcessed = true; } else { candidates = new HashSet<ComposablePartDefinition>(); candidates.Add(previousPart); candidates.Add(candidatePart); } } else { previousPart = candidatePart; } } else { if(candidates.Contains(candidatePart)) { alreadyProcessed = true; } else { candidates.Add(candidatePart); } } if(!alreadyProcessed) { Tuple<ComposablePartDefinition, ExportDefinition> candidateSingleMatch; IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> candidateMultipleMatches; if (candidatePart.TryGetExports(definition, out candidateSingleMatch, out candidateMultipleMatches)) { exports = exports.FastAppendToListAllowNulls(candidateSingleMatch, candidateMultipleMatches); } } } } } } if (exports != null) { multipleMatches = exports; return true; } else { return false; } } else { return TryGetNonGenericExports(definition, out singleMatch, out multipleMatches); } } // Optimised for local as array case private bool TryGetNonGenericExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches) { singleMatch = null; multipleMatches = null; List<Tuple<ComposablePartDefinition, ExportDefinition>> multipleExports = null; Tuple<ComposablePartDefinition, ExportDefinition> singleExport = null; bool matchesFound = false; foreach (var export in ExportDefinitionsInternal) { if (definition.IsConstraintSatisfiedBy(export)) { matchesFound = true; if (singleExport == null) { singleExport = new Tuple<ComposablePartDefinition, ExportDefinition>(this, export); } else { if (multipleExports == null) { multipleExports = new List<Tuple<ComposablePartDefinition, ExportDefinition>>(); multipleExports.Add(singleExport); } multipleExports.Add(new Tuple<ComposablePartDefinition, ExportDefinition>(this, export)); } } } if (!matchesFound) { return false; } if (multipleExports != null) { multipleMatches = multipleExports; } else { singleMatch = singleExport; } return true; } private IEnumerable<Type[]> GetCandidateParameters(Type[] genericParameters) { // we iterate over all exports and find only generic ones. Assuming the arity matches, we reorder the original parameters foreach (ExportDefinition export in ExportDefinitionsInternal) { var genericParametersOrder = export.Metadata.GetValue<int[]>(CompositionConstants.GenericExportParametersOrderMetadataName); if ((genericParametersOrder != null) && (genericParametersOrder.Length == genericParameters.Length)) { yield return GenericServices.Reorder(genericParameters, genericParametersOrder); } } } private static bool TryGetGenericTypeParameters(IEnumerable<object> genericParameters, out Type[] genericTypeParameters) { genericTypeParameters = genericParameters as Type[]; if (genericTypeParameters == null) { object[] genericParametersAsArray = genericParameters.AsArray(); genericTypeParameters = new Type[genericParametersAsArray.Length]; for (int i = 0; i < genericParametersAsArray.Length; i++) { genericTypeParameters[i] = genericParametersAsArray[i] as Type; if (genericTypeParameters[i] == null) { return false; } } } return true; } internal bool TryMakeGenericPartDefinition(Type[] genericTypeParameters, out ComposablePartDefinition genericPartDefinition) { genericPartDefinition = null; if (!GenericSpecializationPartCreationInfo.CanSpecialize(Metadata, genericTypeParameters)) { return false; } genericPartDefinition = new ReflectionComposablePartDefinition(new GenericSpecializationPartCreationInfo(_creationInfo, this, genericTypeParameters)); return true; } string ICompositionElement.DisplayName { get { return _creationInfo.DisplayName; } } ICompositionElement ICompositionElement.Origin { get { return _creationInfo.Origin; } } public override string ToString() { return _creationInfo.DisplayName; } public override bool Equals(object obj) { if (_creationInfo.IsIdentityComparison) { return object.ReferenceEquals(this, obj); } else { ReflectionComposablePartDefinition that = obj as ReflectionComposablePartDefinition; if (that == null) { return false; } return _creationInfo.Equals(that._creationInfo); } } public override int GetHashCode() { if (_creationInfo.IsIdentityComparison) { return base.GetHashCode(); } else { return _creationInfo.GetHashCode(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertInt16129() { var test = new InsertScalarTest__InsertInt16129(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertScalarTest__InsertInt16129 { private struct TestStruct { public Vector128<Int16> _fld; public Int16 _scalarFldData; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)0; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); testStruct._scalarFldData = (short)2; return testStruct; } public void RunStructFldScenario(InsertScalarTest__InsertInt16129 testClass) { var result = Sse2.Insert(_fld, _scalarFldData, 129); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, _scalarFldData, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data = new Int16[Op1ElementCount]; private static Int16 _scalarClsData = (short)2; private static Vector128<Int16> _clsVar; private Vector128<Int16> _fld; private Int16 _scalarFldData = (short)2; private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable; static InsertScalarTest__InsertInt16129() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)0; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public InsertScalarTest__InsertInt16129() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)0; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)0; } _dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); var result = Sse2.Insert( Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr), (short)2, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, (short)2, _dataTable.outArrayPtr); } public unsafe void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); Int16 localData = (short)2; Int16* ptr = &localData; var result = Sse2.Insert( Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)), *ptr, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr); } public unsafe void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); Int16 localData = (short)2; Int16* ptr = &localData; var result = Sse2.Insert( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)), *ptr, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Insert), new Type[] { typeof(Vector128<Int16>), typeof(Int16), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr), (short)2, (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, (short)2, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Insert), new Type[] { typeof(Vector128<Int16>), typeof(Int16), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)), (short)2, (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, (short)2, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Insert), new Type[] { typeof(Vector128<Int16>), typeof(Int16), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)), (short)2, (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, (short)2, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Insert( _clsVar, _scalarClsData, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _scalarClsData,_dataTable.outArrayPtr); } public void RunLclVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario)); Int16 localData = (short)2; var firstOp = Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr); var result = Sse2.Insert(firstOp, localData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); Int16 localData = (short)2; var firstOp = Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)); var result = Sse2.Insert(firstOp, localData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); Int16 localData = (short)2; var firstOp = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)); var result = Sse2.Insert(firstOp, localData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertScalarTest__InsertInt16129(); var result = Sse2.Insert(test._fld, test._scalarFldData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Insert(_fld, _scalarFldData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _scalarFldData, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Insert(test._fld, test._scalarFldData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> firstOp, Int16 scalarData, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray, scalarData, outArray, method); } private void ValidateResult(void* firstOp, Int16 scalarData, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray, scalarData, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16 scalarData, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if ((i == 1 ? result[i] != scalarData : result[i] != 0)) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Insert)}<Int16>(Vector128<Int16><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using Lucene.Net.Support; namespace Lucene.Net.Util { /// <summary> An AttributeSource contains a list of different <see cref="Attribute" />s, /// and methods to add and get them. There can only be a single instance /// of an attribute in the same AttributeSource instance. This is ensured /// by passing in the actual type of the Attribute (Class&lt;Attribute&gt;) to /// the <see cref="AddAttribute{T}()" />, which then checks if an instance of /// that type is already present. If yes, it returns the instance, otherwise /// it creates a new instance and returns it. /// </summary> public class AttributeSource { /// <summary> An AttributeFactory creates instances of <see cref="Attribute" />s.</summary> public abstract class AttributeFactory { /// <summary> returns an <see cref="Attribute" /> for the supplied <see cref="IAttribute" /> interface class.</summary> public abstract Attribute CreateAttributeInstance<T>() where T : IAttribute; /// <summary> This is the default factory that creates <see cref="Attribute" />s using the /// class name of the supplied <see cref="IAttribute" /> interface class by appending <c>Impl</c> to it. /// </summary> public static readonly AttributeFactory DEFAULT_ATTRIBUTE_FACTORY = new DefaultAttributeFactory(); private sealed class DefaultAttributeFactory : AttributeFactory { // This should be WeakDictionary<T, WeakReference<TImpl>> where typeof(T) is Attribute and TImpl is typeof(AttributeImpl) private static readonly WeakDictionary<Type, WeakReference> attClassImplMap = new WeakDictionary<Type, WeakReference>(); internal DefaultAttributeFactory() { } public override Attribute CreateAttributeInstance<TAttImpl>() { try { return (Attribute)System.Activator.CreateInstance(GetClassForInterface<TAttImpl>()); } catch (System.UnauthorizedAccessException) { throw new System.ArgumentException("Could not instantiate implementing class for " + typeof(TAttImpl).FullName); } //catch (System.Exception e) //{ // throw new System.ArgumentException("Could not instantiate implementing class for " + typeof(TAttImpl).FullName); //} } private static System.Type GetClassForInterface<T>() where T : IAttribute { lock (attClassImplMap) { var attClass = typeof(T); WeakReference refz = attClassImplMap[attClass]; System.Type clazz = (refz == null) ? null : ((System.Type)refz.Target); if (clazz == null) { try { string name = attClass.FullName.Replace(attClass.Name, attClass.Name.Substring(1)) + ", " + attClass.Assembly.FullName; attClassImplMap.Add(attClass, new WeakReference(clazz = System.Type.GetType(name, true))); //OK } catch (System.TypeLoadException) // was System.Exception { throw new System.ArgumentException("Could not find implementing class for " + attClass.FullName); } } return clazz; } } } } // These two maps must always be in sync!!! // So they are private, final and read-only from the outside (read-only iterators) private GeneralKeyedCollection<Type, AttributeImplItem> attributes; private GeneralKeyedCollection<Type, AttributeImplItem> attributeImpls; private State[] currentState = null; private AttributeFactory factory; /// <summary> An AttributeSource using the default attribute factory <see cref="AttributeSource.AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY" />.</summary> public AttributeSource() : this(AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY) { } /// <summary> An AttributeSource that uses the same attributes as the supplied one.</summary> public AttributeSource(AttributeSource input) { if (input == null) { throw new System.ArgumentException("input AttributeSource must not be null"); } this.attributes = input.attributes; this.attributeImpls = input.attributeImpls; this.currentState = input.currentState; this.factory = input.factory; } /// <summary> An AttributeSource using the supplied <see cref="AttributeFactory" /> for creating new <see cref="IAttribute" /> instances.</summary> public AttributeSource(AttributeFactory factory) { this.attributes = new GeneralKeyedCollection<Type, AttributeImplItem>(att => att.Key); this.attributeImpls = new GeneralKeyedCollection<Type, AttributeImplItem>(att => att.Key); this.currentState = new State[1]; this.factory = factory; } /// <summary>Returns the used AttributeFactory.</summary> public virtual AttributeFactory Factory { get { return factory; } } /// <summary>Returns a new iterator that iterates the attribute classes /// in the same order they were added in. /// Signature for Java 1.5: <c>public Iterator&lt;Class&lt;? extends Attribute&gt;&gt; getAttributeClassesIterator()</c> /// /// Note that this return value is different from Java in that it enumerates over the values /// and not the keys /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public virtual IEnumerable<Type> GetAttributeTypesIterator() { return this.attributes.Select(item => item.Key); } /// <summary>Returns a new iterator that iterates all unique Attribute implementations. /// This iterator may contain less entries that <see cref="GetAttributeTypesIterator" />, /// if one instance implements more than one Attribute interface. /// Signature for Java 1.5: <c>public Iterator&lt;AttributeImpl&gt; getAttributeImplsIterator()</c> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public virtual IEnumerable<Attribute> GetAttributeImplsIterator() { var initState = GetCurrentState(); while (initState != null) { var att = initState.attribute; initState = initState.next; yield return att; } } /// <summary>a cache that stores all interfaces for known implementation classes for performance (slow reflection) </summary> private static readonly WeakDictionary<Type, LinkedList<WeakReference>> knownImplClasses = new WeakDictionary<Type, LinkedList<WeakReference>>(); /// <summary> /// <b>Expert:</b> Adds a custom AttributeImpl instance with one or more Attribute interfaces. /// <p><font color="red"><b>Please note:</b> It is not guaranteed, that <c>attr</c> is added to /// the <c>AttributeSource</c>, because the provided attributes may already exist. /// You should always retrieve the wanted attributes using <see cref="GetAttribute{T}"/> after adding /// with this method and cast to your class. /// The recommended way to use custom implementations is using an <see cref="AttributeFactory"/> /// </font></p> /// </summary> public virtual void AddAttributeImpl(Attribute attr) { Type attrType = attr.GetType(); if (attributeImpls.Contains(attrType)) return; LinkedList<WeakReference> foundInterfaces; lock (knownImplClasses) { foundInterfaces = knownImplClasses[attrType]; if (foundInterfaces == null) { // we have a strong reference to the class instance holding all interfaces in the list (parameter "attr"), // so all WeakReferences are never evicted by GC knownImplClasses.Add(attrType, foundInterfaces = new LinkedList<WeakReference>()); // find all interfaces that this attribute instance implements // and that extend the Attribute interface var type = attrType; do { var interfaces = type.GetInterfaces(); foreach (var curInterface in interfaces) { if (curInterface != typeof(IAttribute) && typeof(IAttribute).IsAssignableFrom(curInterface)) { foundInterfaces.AddLast(new WeakReference(curInterface)); } } type = type.BaseType; } while (type != null); } } // add all interfaces of this AttributeImpl to the maps foreach (var curInterfaceRef in foundInterfaces) { Type curInterface = (Type)curInterfaceRef.Target; System.Diagnostics.Debug.Assert(curInterface != null, "We have a strong reference on the class holding the interfaces, so they should never get evicted"); // Attribute is a superclass of this interface if (!attributes.ContainsKey(curInterface)) { // invalidate state to force recomputation in captureState() this.currentState[0] = null; attributes.Add(new AttributeImplItem(curInterface, attr)); if (!attributeImpls.ContainsKey(attrType)) { attributeImpls.Add(new AttributeImplItem(attrType, attr)); } } } } /// <summary> The caller must pass in a Class&lt;? extends Attribute&gt; value. /// This method first checks if an instance of that class is /// already in this AttributeSource and returns it. Otherwise a /// new instance is created, added to this AttributeSource and returned. /// </summary> // NOTE: Java has Class<T>, .NET has no Type<T>, this is not a perfect port public virtual T AddAttribute<T>() where T : IAttribute { var attClass = typeof(T); if (!attributes.ContainsKey(attClass)) { if (!(attClass.IsInterface && typeof(IAttribute).IsAssignableFrom(attClass))) { throw new ArgumentException( "AddAttribute() only accepts an interface that extends IAttribute, but " + attClass.FullName + " does not fulfil this contract." ); } AddAttributeImpl(this.factory.CreateAttributeInstance<T>()); } return (T)(IAttribute)attributes[attClass].Value; } /// <summary>Returns true, iff this AttributeSource has any attributes </summary> public virtual bool HasAttributes { get { return this.attributes.Count != 0; } } /// <summary> /// Returns true, iff this AttributeSource contains the passed-in attribute type. /// </summary> public bool HasAttribute<T>() where T : IAttribute { return HasAttribute(typeof(T)); } /// <summary> /// Returns true, iff this AttributeSource contains the passed-in attribute type. /// </summary> public virtual bool HasAttribute(Type attrType) { if (attrType == null) throw new ArgumentNullException("attrType"); return attributes.Contains(attrType); } /// <summary> /// The caller must pass in a Class&lt;? extends Attribute&gt; value. /// Returns the instance of the passed in Attribute contained in this AttributeSource /// </summary> /// <throws> /// ArgumentException if this AttributeSource does not contain the Attribute. /// It is recommended to always use <see cref="AddAttribute{T}" /> even in consumers /// of TokenStreams, because you cannot know if a specific TokenStream really uses /// a specific Attribute. <see cref="AddAttribute{T}" /> will automatically make the attribute /// available. If you want to only use the attribute, if it is available (to optimize /// consuming), use <see cref="HasAttribute" />. /// </throws> // NOTE: Java has Class<T>, .NET has no Type<T>, this is not a perfect port public T GetAttribute<T>() where T : IAttribute { return (T)GetAttribute(typeof(T)); } /// <summary> /// Returns the instance of the passed in attribute type contained in this AttributeSource /// </summary> /// <throws> /// ArgumentException if this AttributeSource does not contain the Attribute. /// It is recommended to always use <see cref="AddAttribute{T}" /> even in consumers /// of TokenStreams, because you cannot know if a specific TokenStream really uses /// a specific Attribute. <see cref="AddAttribute{T}" /> will automatically make the attribute /// available. If you want to only use the attribute, if it is available (to optimize /// consuming), use <see cref="HasAttribute" />. /// </throws> // NOTE: Java has Class<T>, .NET has no Type<T>, this is not a perfect port public virtual IAttribute GetAttribute(Type attrType) { if (attrType == null) throw new ArgumentNullException("attrType"); if (attributes.ContainsKey(attrType)) return attributes[attrType].Value; // This check is done after .ContainsKey to avoid the check // when called from GetAttribute<T> (where T : IAttribute), // the compiler enforces that constraint. if (!typeof(IAttribute).IsAssignableFrom(attrType)) throw new ArgumentException("The passed type is not assignable from IAttribute.", "attrType"); throw new ArgumentException("This AttributeSource does not have the attribute '" + attrType.FullName + "'."); } /// <summary> This class holds the state of an AttributeSource.</summary> /// <seealso cref="CaptureState"> /// </seealso> /// <seealso cref="RestoreState"> /// </seealso> public sealed class State : System.ICloneable { internal /*private*/ Attribute attribute; internal /*private*/ State next; public System.Object Clone() { State clone = new State(); clone.attribute = (Attribute)attribute.Clone(); if (next != null) { clone.next = (State)next.Clone(); } return clone; } } private State GetCurrentState() { var s = currentState[0]; if (s != null || !HasAttributes) { return s; } var c = s = currentState[0] = new State(); var it = attributeImpls.Values().GetEnumerator(); it.MoveNext(); c.attribute = it.Current.Value; while (it.MoveNext()) { c.next = new State(); c = c.next; c.attribute = it.Current.Value; } return s; } /// <summary> Resets all Attributes in this AttributeSource by calling /// <see cref="Attribute.Clear()" /> on each Attribute implementation. /// </summary> public virtual void ClearAttributes() { for (var state = GetCurrentState(); state != null; state = state.next) { state.attribute.Clear(); } } /// <summary> Captures the state of all Attributes. The return value can be passed to /// <see cref="RestoreState" /> to restore the state of this or another AttributeSource. /// </summary> public virtual State CaptureState() { var state = this.GetCurrentState(); return (state == null) ? null : (State)state.Clone(); } /// <summary> Restores this state by copying the values of all attribute implementations /// that this state contains into the attributes implementations of the targetStream. /// The targetStream must contain a corresponding instance for each argument /// contained in this state (e.g. it is not possible to restore the state of /// an AttributeSource containing a TermAttribute into a AttributeSource using /// a Token instance as implementation). /// /// Note that this method does not affect attributes of the targetStream /// that are not contained in this state. In other words, if for example /// the targetStream contains an OffsetAttribute, but this state doesn't, then /// the value of the OffsetAttribute remains unchanged. It might be desirable to /// reset its value to the default, in which case the caller should first /// call <see cref="AttributeSource.ClearAttributes()" /> on the targetStream. /// </summary> public virtual void RestoreState(State state) { if (state == null) return; do { if (!attributeImpls.ContainsKey(state.attribute.GetType())) { throw new System.ArgumentException("State contains an AttributeImpl that is not in this AttributeSource"); } state.attribute.CopyTo(attributeImpls[state.attribute.GetType()].Value); state = state.next; } while (state != null); } public override int GetHashCode() { var code = 0; for (var state = GetCurrentState(); state != null; state = state.next) { code = code*31 + state.attribute.GetHashCode(); } return code; } public override bool Equals(System.Object obj) { if (obj == this) { return true; } if (obj is AttributeSource) { AttributeSource other = (AttributeSource)obj; if (HasAttributes) { if (!other.HasAttributes) { return false; } if (this.attributeImpls.Count != other.attributeImpls.Count) { return false; } // it is only equal if all attribute impls are the same in the same order var thisState = this.GetCurrentState(); var otherState = other.GetCurrentState(); while (thisState != null && otherState != null) { if (otherState.attribute.GetType() != thisState.attribute.GetType() || !otherState.attribute.Equals(thisState.attribute)) { return false; } thisState = thisState.next; otherState = otherState.next; } return true; } else { return !other.HasAttributes; } } else return false; } public override System.String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder().Append('('); if (HasAttributes) { if (currentState[0] == null) { currentState[0] = GetCurrentState(); } for (var state = currentState[0]; state != null; state = state.next) { if (state != currentState[0]) sb.Append(','); sb.Append(state.attribute.ToString()); } } return sb.Append(')').ToString(); } /// <summary> Performs a clone of all <see cref="Attribute" /> instances returned in a new /// AttributeSource instance. This method can be used to e.g. create another TokenStream /// with exactly the same attributes (using <see cref="AttributeSource(AttributeSource)" />) /// </summary> public virtual AttributeSource CloneAttributes() { var clone = new AttributeSource(this.factory); // first clone the impls if (HasAttributes) { for (var state = GetCurrentState(); state != null; state = state.next) { var impl = (Attribute)state.attribute.Clone(); if (!clone.attributeImpls.ContainsKey(impl.GetType())) { clone.attributeImpls.Add(new AttributeImplItem(impl.GetType(), impl)); } } } // now the interfaces foreach (var att in this.attributes) { clone.attributes.Add(new AttributeImplItem(att.Key, clone.attributeImpls[att.Value.GetType()].Value)); } return clone; } } }
/* * Copyright 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace ZXing.Common.Detector { /// <summary> /// Detects a candidate barcode-like rectangular region within an image. It /// starts around the center of the image, increases the size of the candidate /// region until it finds a white rectangular region. By keeping track of the /// last black points it encountered, it determines the corners of the barcode. /// </summary> /// <author>David Olivier</author> public sealed class WhiteRectangleDetector { private const int INIT_SIZE = 10; private const int CORR = 1; private readonly BitMatrix image; private readonly int height; private readonly int width; private readonly int leftInit; private readonly int rightInit; private readonly int downInit; private readonly int upInit; /// <summary> /// Creates a WhiteRectangleDetector instance /// </summary> /// <param name="image">The image.</param> /// <returns>null, if image is too small, otherwise a WhiteRectangleDetector instance</returns> public static WhiteRectangleDetector Create(BitMatrix image) { if (image == null) return null; var instance = new WhiteRectangleDetector(image); if (instance.upInit < 0 || instance.leftInit < 0 || instance.downInit >= instance.height || instance.rightInit >= instance.width) { return null; } return instance; } /// <summary> /// Creates a WhiteRectangleDetector instance /// </summary> /// <param name="image">The image.</param> /// <param name="initSize">Size of the init.</param> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <returns> /// null, if image is too small, otherwise a WhiteRectangleDetector instance /// </returns> public static WhiteRectangleDetector Create(BitMatrix image, int initSize, int x, int y) { var instance = new WhiteRectangleDetector(image, initSize, x, y); if (instance.upInit < 0 || instance.leftInit < 0 || instance.downInit >= instance.height || instance.rightInit >= instance.width) { return null; } return instance; } /// <summary> /// Initializes a new instance of the <see cref="WhiteRectangleDetector"/> class. /// </summary> /// <param name="image">The image.</param> /// <exception cref="ArgumentException">if image is too small</exception> internal WhiteRectangleDetector(BitMatrix image) : this(image, INIT_SIZE, image.Width/2, image.Height/2) { } /// <summary> /// Initializes a new instance of the <see cref="WhiteRectangleDetector"/> class. /// </summary> /// <param name="image">The image.</param> /// <param name="initSize">Size of the init.</param> /// <param name="x">The x.</param> /// <param name="y">The y.</param> internal WhiteRectangleDetector(BitMatrix image, int initSize, int x, int y) { this.image = image; height = image.Height; width = image.Width; int halfsize = initSize / 2; leftInit = x - halfsize; rightInit = x + halfsize; upInit = y - halfsize; downInit = y + halfsize; } /// <summary> /// Detects a candidate barcode-like rectangular region within an image. It /// starts around the center of the image, increases the size of the candidate /// region until it finds a white rectangular region. /// </summary> /// <returns><see cref="ResultPoint" />[] describing the corners of the rectangular /// region. The first and last points are opposed on the diagonal, as /// are the second and third. The first point will be the topmost /// point and the last, the bottommost. The second point will be /// leftmost and the third, the rightmost</returns> public ResultPoint[] detect() { int left = leftInit; int right = rightInit; int up = upInit; int down = downInit; bool sizeExceeded = false; bool aBlackPointFoundOnBorder = true; bool atLeastOneBlackPointFoundOnBorder = false; bool atLeastOneBlackPointFoundOnRight = false; bool atLeastOneBlackPointFoundOnBottom = false; bool atLeastOneBlackPointFoundOnLeft = false; bool atLeastOneBlackPointFoundOnTop = false; while (aBlackPointFoundOnBorder) { aBlackPointFoundOnBorder = false; // ..... // . | // ..... bool rightBorderNotWhite = true; while ((rightBorderNotWhite || !atLeastOneBlackPointFoundOnRight) && right < width) { rightBorderNotWhite = containsBlackPoint(up, down, right, false); if (rightBorderNotWhite) { right++; aBlackPointFoundOnBorder = true; atLeastOneBlackPointFoundOnRight = true; } else if (!atLeastOneBlackPointFoundOnRight) { right++; } } if (right >= width) { sizeExceeded = true; break; } // ..... // . . // .___. bool bottomBorderNotWhite = true; while ((bottomBorderNotWhite || !atLeastOneBlackPointFoundOnBottom) && down < height) { bottomBorderNotWhite = containsBlackPoint(left, right, down, true); if (bottomBorderNotWhite) { down++; aBlackPointFoundOnBorder = true; atLeastOneBlackPointFoundOnBottom = true; } else if (!atLeastOneBlackPointFoundOnBottom) { down++; } } if (down >= height) { sizeExceeded = true; break; } // ..... // | . // ..... bool leftBorderNotWhite = true; while ((leftBorderNotWhite || !atLeastOneBlackPointFoundOnLeft) && left >= 0) { leftBorderNotWhite = containsBlackPoint(up, down, left, false); if (leftBorderNotWhite) { left--; aBlackPointFoundOnBorder = true; atLeastOneBlackPointFoundOnLeft = true; } else if (!atLeastOneBlackPointFoundOnLeft) { left--; } } if (left < 0) { sizeExceeded = true; break; } // .___. // . . // ..... bool topBorderNotWhite = true; while ((topBorderNotWhite || !atLeastOneBlackPointFoundOnTop) && up >= 0) { topBorderNotWhite = containsBlackPoint(left, right, up, true); if (topBorderNotWhite) { up--; aBlackPointFoundOnBorder = true; atLeastOneBlackPointFoundOnTop = true; } else if (!atLeastOneBlackPointFoundOnTop) { up--; } } if (up < 0) { sizeExceeded = true; break; } if (aBlackPointFoundOnBorder) { atLeastOneBlackPointFoundOnBorder = true; } } if (!sizeExceeded && atLeastOneBlackPointFoundOnBorder) { int maxSize = right - left; ResultPoint z = null; for (int i = 1; i < maxSize; i++) { z = getBlackPointOnSegment(left, down - i, left + i, down); if (z != null) { break; } } if (z == null) { return null; } ResultPoint t = null; //go down right for (int i = 1; i < maxSize; i++) { t = getBlackPointOnSegment(left, up + i, left + i, up); if (t != null) { break; } } if (t == null) { return null; } ResultPoint x = null; //go down left for (int i = 1; i < maxSize; i++) { x = getBlackPointOnSegment(right, up + i, right - i, up); if (x != null) { break; } } if (x == null) { return null; } ResultPoint y = null; //go up left for (int i = 1; i < maxSize; i++) { y = getBlackPointOnSegment(right, down - i, right - i, down); if (y != null) { break; } } if (y == null) { return null; } return centerEdges(y, z, x, t); } else { return null; } } private ResultPoint getBlackPointOnSegment(float aX, float aY, float bX, float bY) { int dist = MathUtils.round(MathUtils.distance(aX, aY, bX, bY)); float xStep = (bX - aX) / dist; float yStep = (bY - aY) / dist; for (int i = 0; i < dist; i++) { int x = MathUtils.round(aX + i * xStep); int y = MathUtils.round(aY + i * yStep); if (image[x, y]) { return new ResultPoint(x, y); } } return null; } /// <summary> /// recenters the points of a constant distance towards the center /// </summary> /// <param name="y">bottom most point</param> /// <param name="z">left most point</param> /// <param name="x">right most point</param> /// <param name="t">top most point</param> /// <returns><see cref="ResultPoint"/>[] describing the corners of the rectangular /// region. The first and last points are opposed on the diagonal, as /// are the second and third. The first point will be the topmost /// point and the last, the bottommost. The second point will be /// leftmost and the third, the rightmost</returns> private ResultPoint[] centerEdges(ResultPoint y, ResultPoint z, ResultPoint x, ResultPoint t) { // // t t // z x // x OR z // y y // float yi = y.X; float yj = y.Y; float zi = z.X; float zj = z.Y; float xi = x.X; float xj = x.Y; float ti = t.X; float tj = t.Y; if (yi < width / 2.0f) { return new[] { new ResultPoint(ti - CORR, tj + CORR), new ResultPoint(zi + CORR, zj + CORR), new ResultPoint(xi - CORR, xj - CORR), new ResultPoint(yi + CORR, yj - CORR) }; } else { return new[] { new ResultPoint(ti + CORR, tj + CORR), new ResultPoint(zi + CORR, zj - CORR), new ResultPoint(xi - CORR, xj + CORR), new ResultPoint(yi - CORR, yj - CORR) }; } } /// <summary> /// Determines whether a segment contains a black point /// </summary> /// <param name="a">min value of the scanned coordinate</param> /// <param name="b">max value of the scanned coordinate</param> /// <param name="fixed">value of fixed coordinate</param> /// <param name="horizontal">set to true if scan must be horizontal, false if vertical</param> /// <returns> /// true if a black point has been found, else false. /// </returns> private bool containsBlackPoint(int a, int b, int @fixed, bool horizontal) { if (horizontal) { for (int x = a; x <= b; x++) { if (image[x, @fixed]) { return true; } } } else { for (int y = a; y <= b; y++) { if (image[@fixed, y]) { return true; } } } return false; } } }
using System; using System.Collections; using Raksha.Crypto; using Raksha.Crypto.Digests; using Raksha.Crypto.Parameters; using Raksha.Utilities; namespace Raksha.Crypto.Signers { /// <summary> ISO9796-2 - mechanism using a hash function with recovery (scheme 1)</summary> public class Iso9796d2Signer : ISignerWithRecovery { /// <summary> /// Return a reference to the recoveredMessage message. /// </summary> /// <returns>The full/partial recoveredMessage message.</returns> /// <seealso cref="ISignerWithRecovery.GetRecoveredMessage"/> public byte[] GetRecoveredMessage() { return recoveredMessage; } public const int TrailerImplicit = 0xBC; public const int TrailerRipeMD160 = 0x31CC; public const int TrailerRipeMD128 = 0x32CC; public const int TrailerSha1 = 0x33CC; public const int TrailerSha256 = 0x34CC; public const int TrailerSha512 = 0x35CC; public const int TrailerSha384 = 0x36CC; public const int TrailerWhirlpool = 0x37CC; private static IDictionary trailerMap = Platform.CreateHashtable(); static Iso9796d2Signer() { trailerMap.Add("RIPEMD128", TrailerRipeMD128); trailerMap.Add("RIPEMD160", TrailerRipeMD160); trailerMap.Add("SHA-1", TrailerSha1); trailerMap.Add("SHA-256", TrailerSha256); trailerMap.Add("SHA-384", TrailerSha384); trailerMap.Add("SHA-512", TrailerSha512); trailerMap.Add("Whirlpool", TrailerWhirlpool); } private IDigest digest; private IAsymmetricBlockCipher cipher; private int trailer; private int keyBits; private byte[] block; private byte[] mBuf; private int messageLength; private bool fullMessage; private byte[] recoveredMessage; private byte[] preSig; private byte[] preBlock; /// <summary> /// Generate a signer for the with either implicit or explicit trailers /// for ISO9796-2. /// </summary> /// <param name="cipher">base cipher to use for signature creation/verification</param> /// <param name="digest">digest to use.</param> /// <param name="isImplicit">whether or not the trailer is implicit or gives the hash.</param> public Iso9796d2Signer( IAsymmetricBlockCipher cipher, IDigest digest, bool isImplicit) { this.cipher = cipher; this.digest = digest; if (isImplicit) { trailer = TrailerImplicit; } else { string digestName = digest.AlgorithmName; if (trailerMap.Contains(digestName)) { trailer = (int)trailerMap[digest.AlgorithmName]; } else { throw new System.ArgumentException("no valid trailer for digest"); } } } /// <summary> Constructor for a signer with an explicit digest trailer. /// /// </summary> /// <param name="cipher">cipher to use. /// </param> /// <param name="digest">digest to sign with. /// </param> public Iso9796d2Signer(IAsymmetricBlockCipher cipher, IDigest digest) : this(cipher, digest, false) { } public string AlgorithmName { get { return digest.AlgorithmName + "with" + "ISO9796-2S1"; } } public virtual void Init(bool forSigning, ICipherParameters parameters) { RsaKeyParameters kParam = (RsaKeyParameters) parameters; cipher.Init(forSigning, kParam); keyBits = kParam.Modulus.BitLength; block = new byte[(keyBits + 7) / 8]; if (trailer == TrailerImplicit) { mBuf = new byte[block.Length - digest.GetDigestSize() - 2]; } else { mBuf = new byte[block.Length - digest.GetDigestSize() - 3]; } Reset(); } /// <summary> compare two byte arrays - constant time.</summary> private bool IsSameAs(byte[] a, byte[] b) { int checkLen; if (messageLength > mBuf.Length) { if (mBuf.Length > b.Length) { return false; } checkLen = mBuf.Length; } else { if (messageLength != b.Length) { return false; } checkLen = b.Length; } bool isOkay = true; for (int i = 0; i != checkLen; i++) { if (a[i] != b[i]) { isOkay = false; } } return isOkay; } /// <summary> clear possible sensitive data</summary> private void ClearBlock( byte[] block) { Array.Clear(block, 0, block.Length); } public virtual void UpdateWithRecoveredMessage( byte[] signature) { byte[] block = cipher.ProcessBlock(signature, 0, signature.Length); if (((block[0] & 0xC0) ^ 0x40) != 0) throw new InvalidCipherTextException("malformed signature"); if (((block[block.Length - 1] & 0xF) ^ 0xC) != 0) throw new InvalidCipherTextException("malformed signature"); int delta = 0; if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0) { delta = 1; } else { int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF); string digestName = digest.AlgorithmName; if (!trailerMap.Contains(digestName)) throw new ArgumentException("unrecognised hash in signature"); if (sigTrail != (int)trailerMap[digestName]) throw new InvalidOperationException("signer initialised with wrong digest for trailer " + sigTrail); delta = 2; } // // find out how much padding we've got // int mStart = 0; for (mStart = 0; mStart != block.Length; mStart++) { if (((block[mStart] & 0x0f) ^ 0x0a) == 0) break; } mStart++; int off = block.Length - delta - digest.GetDigestSize(); // // there must be at least one byte of message string // if ((off - mStart) <= 0) throw new InvalidCipherTextException("malformed block"); // // if we contain the whole message as well, check the hash of that. // if ((block[0] & 0x20) == 0) { fullMessage = true; recoveredMessage = new byte[off - mStart]; Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length); } else { fullMessage = false; recoveredMessage = new byte[off - mStart]; Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length); } preSig = signature; preBlock = block; digest.BlockUpdate(recoveredMessage, 0, recoveredMessage.Length); messageLength = recoveredMessage.Length; } /// <summary> update the internal digest with the byte b</summary> public void Update( byte input) { digest.Update(input); if (preSig == null && messageLength < mBuf.Length) { mBuf[messageLength] = input; } messageLength++; } /// <summary> update the internal digest with the byte array in</summary> public void BlockUpdate( byte[] input, int inOff, int length) { digest.BlockUpdate(input, inOff, length); if (preSig == null && messageLength < mBuf.Length) { for (int i = 0; i < length && (i + messageLength) < mBuf.Length; i++) { mBuf[messageLength + i] = input[inOff + i]; } } messageLength += length; } /// <summary> reset the internal state</summary> public virtual void Reset() { digest.Reset(); messageLength = 0; ClearBlock(mBuf); if (recoveredMessage != null) { ClearBlock(recoveredMessage); } recoveredMessage = null; fullMessage = false; } /// <summary> Generate a signature for the loaded message using the key we were /// initialised with. /// </summary> public virtual byte[] GenerateSignature() { int digSize = digest.GetDigestSize(); int t = 0; int delta = 0; if (trailer == TrailerImplicit) { t = 8; delta = block.Length - digSize - 1; digest.DoFinal(block, delta); block[block.Length - 1] = (byte) TrailerImplicit; } else { t = 16; delta = block.Length - digSize - 2; digest.DoFinal(block, delta); block[block.Length - 2] = (byte) ((uint)trailer >> 8); block[block.Length - 1] = (byte) trailer; } byte header = 0; int x = (digSize + messageLength) * 8 + t + 4 - keyBits; if (x > 0) { int mR = messageLength - ((x + 7) / 8); header = (byte) (0x60); delta -= mR; Array.Copy(mBuf, 0, block, delta, mR); } else { header = (byte) (0x40); delta -= messageLength; Array.Copy(mBuf, 0, block, delta, messageLength); } if ((delta - 1) > 0) { for (int i = delta - 1; i != 0; i--) { block[i] = (byte) 0xbb; } block[delta - 1] ^= (byte) 0x01; block[0] = (byte) 0x0b; block[0] |= header; } else { block[0] = (byte) 0x0a; block[0] |= header; } byte[] b = cipher.ProcessBlock(block, 0, block.Length); ClearBlock(mBuf); ClearBlock(block); return b; } /// <summary> return true if the signature represents a ISO9796-2 signature /// for the passed in message. /// </summary> public virtual bool VerifySignature(byte[] signature) { byte[] block; bool updateWithRecoveredCalled; if (preSig == null) { updateWithRecoveredCalled = false; try { block = cipher.ProcessBlock(signature, 0, signature.Length); } catch (Exception) { return false; } } else { if (!Arrays.AreEqual(preSig, signature)) throw new InvalidOperationException("updateWithRecoveredMessage called on different signature"); updateWithRecoveredCalled = true; block = preBlock; preSig = null; preBlock = null; } if (((block[0] & 0xC0) ^ 0x40) != 0) return ReturnFalse(block); if (((block[block.Length - 1] & 0xF) ^ 0xC) != 0) return ReturnFalse(block); int delta = 0; if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0) { delta = 1; } else { int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF); string digestName = digest.AlgorithmName; if (!trailerMap.Contains(digestName)) throw new ArgumentException("unrecognised hash in signature"); if (sigTrail != (int)trailerMap[digestName]) throw new InvalidOperationException("signer initialised with wrong digest for trailer " + sigTrail); delta = 2; } // // find out how much padding we've got // int mStart = 0; for (; mStart != block.Length; mStart++) { if (((block[mStart] & 0x0f) ^ 0x0a) == 0) { break; } } mStart++; // // check the hashes // byte[] hash = new byte[digest.GetDigestSize()]; int off = block.Length - delta - hash.Length; // // there must be at least one byte of message string // if ((off - mStart) <= 0) { return ReturnFalse(block); } // // if we contain the whole message as well, check the hash of that. // if ((block[0] & 0x20) == 0) { fullMessage = true; // check right number of bytes passed in. if (messageLength > off - mStart) { return ReturnFalse(block); } digest.Reset(); digest.BlockUpdate(block, mStart, off - mStart); digest.DoFinal(hash, 0); bool isOkay = true; for (int i = 0; i != hash.Length; i++) { block[off + i] ^= hash[i]; if (block[off + i] != 0) { isOkay = false; } } if (!isOkay) { return ReturnFalse(block); } recoveredMessage = new byte[off - mStart]; Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length); } else { fullMessage = false; digest.DoFinal(hash, 0); bool isOkay = true; for (int i = 0; i != hash.Length; i++) { block[off + i] ^= hash[i]; if (block[off + i] != 0) { isOkay = false; } } if (!isOkay) { return ReturnFalse(block); } recoveredMessage = new byte[off - mStart]; Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length); } // // if they've input a message check what we've recovered against // what was input. // if (messageLength != 0 && !updateWithRecoveredCalled) { if (!IsSameAs(mBuf, recoveredMessage)) { // ClearBlock(recoveredMessage); return ReturnFalse(block); } } ClearBlock(mBuf); ClearBlock(block); return true; } private bool ReturnFalse(byte[] block) { ClearBlock(mBuf); ClearBlock(block); return false; } /// <summary> /// Return true if the full message was recoveredMessage. /// </summary> /// <returns> true on full message recovery, false otherwise.</returns> /// <seealso cref="ISignerWithRecovery.HasFullMessage"/> public virtual bool HasFullMessage() { return fullMessage; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using System; using System.Collections.Generic; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Rest.Chat.V1.Service; namespace Twilio.Tests.Rest.Chat.V1.Service { [TestFixture] public class RoleTest : TwilioTest { [Test] public void TestFetchRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Chat, "/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RoleResource.Fetch("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestFetchResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"channel user\",\"type\": \"channel\",\"permissions\": [\"sendMessage\",\"leaveChannel\",\"editOwnMessage\",\"deleteOwnMessage\"],\"date_created\": \"2016-03-03T19:47:15Z\",\"date_updated\": \"2016-03-03T19:47:15Z\",\"url\": \"https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = RoleResource.Fetch("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestDeleteRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Delete, Twilio.Rest.Domain.Chat, "/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RoleResource.Delete("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestDeleteResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.NoContent, "null" )); var response = RoleResource.Delete("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestCreateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Chat, "/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles", "" ); request.AddPostParam("FriendlyName", Serialize("friendly_name")); request.AddPostParam("Type", Serialize(RoleResource.RoleTypeEnum.Channel)); request.AddPostParam("Permission", Serialize("permission")); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RoleResource.Create("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "friendly_name", RoleResource.RoleTypeEnum.Channel, Promoter.ListOfOne("permission"), client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestCreateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.Created, "{\"sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"channel user\",\"type\": \"channel\",\"permissions\": [\"sendMessage\",\"leaveChannel\",\"editOwnMessage\",\"deleteOwnMessage\"],\"date_created\": \"2016-03-03T19:47:15Z\",\"date_updated\": \"2016-03-03T19:47:15Z\",\"url\": \"https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = RoleResource.Create("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "friendly_name", RoleResource.RoleTypeEnum.Channel, Promoter.ListOfOne("permission"), client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Chat, "/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RoleResource.Read("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestReadFullResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"roles\"},\"roles\": [{\"sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"channel user\",\"type\": \"channel\",\"permissions\": [\"sendMessage\",\"leaveChannel\",\"editOwnMessage\",\"deleteOwnMessage\"],\"date_created\": \"2016-03-03T19:47:15Z\",\"date_updated\": \"2016-03-03T19:47:15Z\",\"url\": \"https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}]}" )); var response = RoleResource.Read("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadEmptyResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"roles\"},\"roles\": []}" )); var response = RoleResource.Read("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestUpdateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Chat, "/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); request.AddPostParam("Permission", Serialize("permission")); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RoleResource.Update("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", Promoter.ListOfOne("permission"), client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestUpdateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"channel user\",\"type\": \"channel\",\"permissions\": [\"sendMessage\",\"leaveChannel\",\"editOwnMessage\",\"deleteOwnMessage\"],\"date_created\": \"2016-03-03T19:47:15Z\",\"date_updated\": \"2016-03-03T19:47:15Z\",\"url\": \"https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = RoleResource.Update("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", Promoter.ListOfOne("permission"), client: twilioRestClient); Assert.NotNull(response); } } }
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 SecMS.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 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org. // **************************************************************** using System; using System.IO; using System.Reflection; using System.Configuration; using System.Collections.Specialized; using System.Threading; using Microsoft.Win32; namespace NUnit.Core { /// <summary> /// Provides static methods for accessing the NUnit config /// file /// </summary> public class NUnitConfiguration { #region Public Properties #region BuildConfiguration public static string BuildConfiguration { get { #if DEBUG return "Debug"; #else return "Release"; #endif } } #endregion #region NUnitLibDirectory private static string nunitLibDirectory; /// <summary> /// Gets the path to the lib directory for the version and build /// of NUnit currently executing. /// </summary> public static string NUnitLibDirectory { get { if (nunitLibDirectory == null) { nunitLibDirectory = AssemblyHelper.GetDirectoryName(Assembly.GetExecutingAssembly()); } return nunitLibDirectory; } } #endregion #region NUnitBinDirectory private static string nunitBinDirectory; public static string NUnitBinDirectory { get { if (nunitBinDirectory == null) { nunitBinDirectory = NUnitLibDirectory; if (Path.GetFileName(nunitBinDirectory).ToLower() == "lib") nunitBinDirectory = Path.GetDirectoryName(nunitBinDirectory); } return nunitBinDirectory; } } #endregion #region NUnitDocDirectory private static string nunitDocDirectory; private static string NUnitDocDirectory { get { if (nunitDocDirectory == null) { string dir = Path.GetDirectoryName(NUnitBinDirectory); nunitDocDirectory = Path.Combine(dir, "doc"); if (!Directory.Exists(nunitDocDirectory)) { dir = Path.GetDirectoryName(dir); nunitDocDirectory = Path.Combine(dir, "doc"); } } return nunitDocDirectory; } } #endregion #region AddinDirectory private static string addinDirectory; public static string AddinDirectory { get { if (addinDirectory == null) { addinDirectory = Path.Combine(NUnitBinDirectory, "addins"); } return addinDirectory; } } #endregion #region TestAgentExePath //private static string testAgentExePath; //private static string TestAgentExePath //{ // get // { // if (testAgentExePath == null) // testAgentExePath = Path.Combine(NUnitBinDirectory, "nunit-agent.exe"); // return testAgentExePath; // } //} #endregion #region MonoExePath private static string monoExePath; public static string MonoExePath { get { if (monoExePath == null) { string[] searchNames = IsWindows() ? new string[] { "mono.bat", "mono.cmd", "mono.exe" } : new string[] { "mono", "mono.exe" }; monoExePath = FindOneOnPath(searchNames); if (monoExePath == null && IsWindows()) { RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono"); if (key != null) { string version = key.GetValue("DefaultCLR") as string; if (version != null) { key = key.OpenSubKey(version); if (key != null) { string installDir = key.GetValue("SdkInstallRoot") as string; if (installDir != null) monoExePath = Path.Combine(installDir, @"bin\mono.exe"); } } } } if (monoExePath == null) return "mono"; } return monoExePath; } } private static string FindOneOnPath(string[] names) { //foreach (string dir in Environment.GetEnvironmentVariable("path").Split(new char[] { Path.PathSeparator })) // foreach (string name in names) // { // string fullPath = Path.Combine(dir, name); // if (File.Exists(fullPath)) // return name; // } return null; } private static bool IsWindows() { return Environment.OSVersion.Platform == PlatformID.Win32NT; } #endregion #region ApplicationDataDirectory private static string applicationDirectory; public static string ApplicationDirectory { get { if (applicationDirectory == null) { applicationDirectory = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NUnit"); } return applicationDirectory; } } #endregion #region LogDirectory private static string logDirectory; public static string LogDirectory { get { if (logDirectory == null) { logDirectory = Path.Combine(ApplicationDirectory, "logs"); } return logDirectory; } } #endregion #region HelpUrl public static string HelpUrl { get { string helpUrl = "http://nunit.org"; string dir = Path.GetDirectoryName(NUnitBinDirectory); string docDir = null; while (dir != null) { docDir = Path.Combine(dir, "doc"); if (Directory.Exists(docDir)) break; dir = Path.GetDirectoryName(dir); } if (docDir != null) { string localPath = Path.Combine(docDir, "index.html"); if (File.Exists(localPath)) { UriBuilder uri = new UriBuilder(); uri.Scheme = "file"; uri.Host = "localhost"; uri.Path = localPath; helpUrl = uri.ToString(); } } return helpUrl; } } #endregion #endregion } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // .NET Compact Framework 1.0 has no support for Marshal.StringToHGlobalAnsi // SSCLI 1.0 has no support for Marshal.StringToHGlobalAnsi #if !NETCF && !SSCLI using System; using System.Runtime.InteropServices; using Ctrip.Core; using Ctrip.Appender; using Ctrip.Util; using Ctrip.Layout; namespace Ctrip.Appender { /// <summary> /// Logs events to a local syslog service. /// </summary> /// <remarks> /// <note> /// This appender uses the POSIX libc library functions <c>openlog</c>, <c>syslog</c>, and <c>closelog</c>. /// If these functions are not available on the local system then this appender will not work! /// </note> /// <para> /// The functions <c>openlog</c>, <c>syslog</c>, and <c>closelog</c> are specified in SUSv2 and /// POSIX 1003.1-2001 standards. These are used to log messages to the local syslog service. /// </para> /// <para> /// This appender talks to a local syslog service. If you need to log to a remote syslog /// daemon and you cannot configure your local syslog service to do this you may be /// able to use the <see cref="RemoteSyslogAppender"/> to log via UDP. /// </para> /// <para> /// Syslog messages must have a facility and and a severity. The severity /// is derived from the Level of the logging event. /// The facility must be chosen from the set of defined syslog /// <see cref="SyslogFacility"/> values. The facilities list is predefined /// and cannot be extended. /// </para> /// <para> /// An identifier is specified with each log message. This can be specified /// by setting the <see cref="Identity"/> property. The identity (also know /// as the tag) must not contain white space. The default value for the /// identity is the application name (from <see cref="SystemInfo.ApplicationFriendlyName"/>). /// </para> /// </remarks> /// <author>Rob Lyon</author> /// <author>Nicko Cadell</author> public class LocalSyslogAppender : AppenderSkeleton { #region Enumerations /// <summary> /// syslog severities /// </summary> /// <remarks> /// <para> /// The Ctrip Level maps to a syslog severity using the /// <see cref="LocalSyslogAppender.AddMapping"/> method and the <see cref="LevelSeverity"/> /// class. The severity is set on <see cref="LevelSeverity.Severity"/>. /// </para> /// </remarks> public enum SyslogSeverity { /// <summary> /// system is unusable /// </summary> Emergency = 0, /// <summary> /// action must be taken immediately /// </summary> Alert = 1, /// <summary> /// critical conditions /// </summary> Critical = 2, /// <summary> /// error conditions /// </summary> Error = 3, /// <summary> /// warning conditions /// </summary> Warning = 4, /// <summary> /// normal but significant condition /// </summary> Notice = 5, /// <summary> /// informational /// </summary> Informational = 6, /// <summary> /// debug-level messages /// </summary> Debug = 7 }; /// <summary> /// syslog facilities /// </summary> /// <remarks> /// <para> /// The syslog facility defines which subsystem the logging comes from. /// This is set on the <see cref="Facility"/> property. /// </para> /// </remarks> public enum SyslogFacility { /// <summary> /// kernel messages /// </summary> Kernel = 0, /// <summary> /// random user-level messages /// </summary> User = 1, /// <summary> /// mail system /// </summary> Mail = 2, /// <summary> /// system daemons /// </summary> Daemons = 3, /// <summary> /// security/authorization messages /// </summary> Authorization = 4, /// <summary> /// messages generated internally by syslogd /// </summary> Syslog = 5, /// <summary> /// line printer subsystem /// </summary> Printer = 6, /// <summary> /// network news subsystem /// </summary> News = 7, /// <summary> /// UUCP subsystem /// </summary> Uucp = 8, /// <summary> /// clock (cron/at) daemon /// </summary> Clock = 9, /// <summary> /// security/authorization messages (private) /// </summary> Authorization2 = 10, /// <summary> /// ftp daemon /// </summary> Ftp = 11, /// <summary> /// NTP subsystem /// </summary> Ntp = 12, /// <summary> /// log audit /// </summary> Audit = 13, /// <summary> /// log alert /// </summary> Alert = 14, /// <summary> /// clock daemon /// </summary> Clock2 = 15, /// <summary> /// reserved for local use /// </summary> Local0 = 16, /// <summary> /// reserved for local use /// </summary> Local1 = 17, /// <summary> /// reserved for local use /// </summary> Local2 = 18, /// <summary> /// reserved for local use /// </summary> Local3 = 19, /// <summary> /// reserved for local use /// </summary> Local4 = 20, /// <summary> /// reserved for local use /// </summary> Local5 = 21, /// <summary> /// reserved for local use /// </summary> Local6 = 22, /// <summary> /// reserved for local use /// </summary> Local7 = 23 } #endregion // Enumerations #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="LocalSyslogAppender" /> class. /// </summary> /// <remarks> /// This instance of the <see cref="LocalSyslogAppender" /> class is set up to write /// to a local syslog service. /// </remarks> public LocalSyslogAppender() { } #endregion // Public Instance Constructors #region Public Instance Properties /// <summary> /// Message identity /// </summary> /// <remarks> /// <para> /// An identifier is specified with each log message. This can be specified /// by setting the <see cref="Identity"/> property. The identity (also know /// as the tag) must not contain white space. The default value for the /// identity is the application name (from <see cref="SystemInfo.ApplicationFriendlyName"/>). /// </para> /// </remarks> public string Identity { get { return m_identity; } set { m_identity = value; } } /// <summary> /// Syslog facility /// </summary> /// <remarks> /// Set to one of the <see cref="SyslogFacility"/> values. The list of /// facilities is predefined and cannot be extended. The default value /// is <see cref="SyslogFacility.User"/>. /// </remarks> public SyslogFacility Facility { get { return m_facility; } set { m_facility = value; } } #endregion // Public Instance Properties /// <summary> /// Add a mapping of level to severity /// </summary> /// <param name="mapping">The mapping to add</param> /// <remarks> /// <para> /// Adds a <see cref="LevelSeverity"/> to this appender. /// </para> /// </remarks> public void AddMapping(LevelSeverity mapping) { m_levelMapping.Add(mapping); } #region IOptionHandler Implementation /// <summary> /// Initialize the appender based on the options set. /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #endif public override void ActivateOptions() { base.ActivateOptions(); m_levelMapping.ActivateOptions(); string identString = m_identity; if (identString == null) { // Set to app name by default identString = SystemInfo.ApplicationFriendlyName; } // create the native heap ansi string. Note this is a copy of our string // so we do not need to hold on to the string itself, holding on to the // handle will keep the heap ansi string alive. m_handleToIdentity = Marshal.StringToHGlobalAnsi(identString); // open syslog openlog(m_handleToIdentity, 1, m_facility); } #endregion // IOptionHandler Implementation #region AppenderSkeleton Implementation /// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Writes the event to a remote syslog daemon. /// </para> /// <para> /// The format of the output will depend on the appender's layout. /// </para> /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #endif [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] protected override void Append(LoggingEvent loggingEvent) { int priority = GeneratePriority(m_facility, GetSeverity(loggingEvent.Level)); string message = RenderLoggingEvent(loggingEvent); // Call the local libc syslog method // The second argument is a printf style format string syslog(priority, "%s", message); } /// <summary> /// Close the syslog when the appender is closed /// </summary> /// <remarks> /// <para> /// Close the syslog when the appender is closed /// </para> /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #endif protected override void OnClose() { base.OnClose(); try { // close syslog closelog(); } catch(DllNotFoundException) { // Ignore dll not found at this point } if (m_handleToIdentity != IntPtr.Zero) { // free global ident Marshal.FreeHGlobal(m_handleToIdentity); } } /// <summary> /// This appender requires a <see cref="AppenderSkeleton.Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="AppenderSkeleton.Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } #endregion // AppenderSkeleton Implementation #region Protected Members /// <summary> /// Translates a Ctrip level to a syslog severity. /// </summary> /// <param name="level">A Ctrip level.</param> /// <returns>A syslog severity.</returns> /// <remarks> /// <para> /// Translates a Ctrip level to a syslog severity. /// </para> /// </remarks> virtual protected SyslogSeverity GetSeverity(Level level) { LevelSeverity levelSeverity = m_levelMapping.Lookup(level) as LevelSeverity; if (levelSeverity != null) { return levelSeverity.Severity; } // // Fallback to sensible default values // if (level >= Level.Alert) { return SyslogSeverity.Alert; } else if (level >= Level.Critical) { return SyslogSeverity.Critical; } else if (level >= Level.Error) { return SyslogSeverity.Error; } else if (level >= Level.Warn) { return SyslogSeverity.Warning; } else if (level >= Level.Notice) { return SyslogSeverity.Notice; } else if (level >= Level.Info) { return SyslogSeverity.Informational; } // Default setting return SyslogSeverity.Debug; } #endregion // Protected Members #region Public Static Members /// <summary> /// Generate a syslog priority. /// </summary> /// <param name="facility">The syslog facility.</param> /// <param name="severity">The syslog severity.</param> /// <returns>A syslog priority.</returns> private static int GeneratePriority(SyslogFacility facility, SyslogSeverity severity) { return ((int)facility * 8) + (int)severity; } #endregion // Public Static Members #region Private Instances Fields /// <summary> /// The facility. The default facility is <see cref="SyslogFacility.User"/>. /// </summary> private SyslogFacility m_facility = SyslogFacility.User; /// <summary> /// The message identity /// </summary> private string m_identity; /// <summary> /// Marshaled handle to the identity string. We have to hold on to the /// string as the <c>openlog</c> and <c>syslog</c> APIs just hold the /// pointer to the ident and dereference it for each log message. /// </summary> private IntPtr m_handleToIdentity = IntPtr.Zero; /// <summary> /// Mapping from level object to syslog severity /// </summary> private LevelMapping m_levelMapping = new LevelMapping(); #endregion // Private Instances Fields #region External Members /// <summary> /// Open connection to system logger. /// </summary> [DllImport("libc")] private static extern void openlog(IntPtr ident, int option, SyslogFacility facility); /// <summary> /// Generate a log message. /// </summary> /// <remarks> /// <para> /// The libc syslog method takes a format string and a variable argument list similar /// to the classic printf function. As this type of vararg list is not supported /// by C# we need to specify the arguments explicitly. Here we have specified the /// format string with a single message argument. The caller must set the format /// string to <c>"%s"</c>. /// </para> /// </remarks> [DllImport("libc", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] private static extern void syslog(int priority, string format, string message); /// <summary> /// Close descriptor used to write to system logger. /// </summary> [DllImport("libc")] private static extern void closelog(); #endregion // External Members #region LevelSeverity LevelMapping Entry /// <summary> /// A class to act as a mapping between the level that a logging call is made at and /// the syslog severity that is should be logged at. /// </summary> /// <remarks> /// <para> /// A class to act as a mapping between the level that a logging call is made at and /// the syslog severity that is should be logged at. /// </para> /// </remarks> public class LevelSeverity : LevelMappingEntry { private SyslogSeverity m_severity; /// <summary> /// The mapped syslog severity for the specified level /// </summary> /// <remarks> /// <para> /// Required property. /// The mapped syslog severity for the specified level /// </para> /// </remarks> public SyslogSeverity Severity { get { return m_severity; } set { m_severity = value; } } } #endregion // LevelSeverity LevelMapping Entry } } #endif
#region Using #endregion namespace SharpCompress.Compressor.PPMd.I1 { /// <summary> /// The PPM context structure. This is tightly coupled with <see cref="Model"/>. /// </summary> /// <remarks> /// <para> /// This must be a structure rather than a class because several places in the associated code assume that /// <see cref="PpmContext"/> is a value type (meaning that assignment creates a completely new copy of /// the instance rather than just copying a reference to the same instance). /// </para> /// </remarks> internal partial class Model { /// <summary> /// The structure which represents the current PPM context. This is 12 bytes in size. /// </summary> internal struct PpmContext { public uint Address; public byte[] Memory; public static readonly PpmContext Zero = new PpmContext(0, null); public const int Size = 12; /// <summary> /// Initializes a new instance of the <see cref="PpmContext"/> structure. /// </summary> public PpmContext(uint address, byte[] memory) { Address = address; Memory = memory; } /// <summary> /// Gets or sets the number statistics. /// </summary> public byte NumberStatistics { get { return Memory[Address]; } set { Memory[Address] = value; } } /// <summary> /// Gets or sets the flags. /// </summary> public byte Flags { get { return Memory[Address + 1]; } set { Memory[Address + 1] = value; } } /// <summary> /// Gets or sets the summary frequency. /// </summary> public ushort SummaryFrequency { get { return (ushort) (((ushort) Memory[Address + 2]) | ((ushort) Memory[Address + 3]) << 8); } set { Memory[Address + 2] = (byte) value; Memory[Address + 3] = (byte) (value >> 8); } } /// <summary> /// Gets or sets the statistics. /// </summary> public PpmState Statistics { get { return new PpmState( ((uint) Memory[Address + 4]) | ((uint) Memory[Address + 5]) << 8 | ((uint) Memory[Address + 6]) << 16 | ((uint) Memory[Address + 7]) << 24, Memory); } set { Memory[Address + 4] = (byte) value.Address; Memory[Address + 5] = (byte) (value.Address >> 8); Memory[Address + 6] = (byte) (value.Address >> 16); Memory[Address + 7] = (byte) (value.Address >> 24); } } /// <summary> /// Gets or sets the suffix. /// </summary> public PpmContext Suffix { get { return new PpmContext( ((uint) Memory[Address + 8]) | ((uint) Memory[Address + 9]) << 8 | ((uint) Memory[Address + 10]) << 16 | ((uint) Memory[Address + 11]) << 24, Memory); } set { Memory[Address + 8] = (byte) value.Address; Memory[Address + 9] = (byte) (value.Address >> 8); Memory[Address + 10] = (byte) (value.Address >> 16); Memory[Address + 11] = (byte) (value.Address >> 24); } } /// <summary> /// The first PPM state associated with the PPM context. /// </summary> /// <remarks> /// <para> /// The first PPM state overlaps this PPM context instance (the context.SummaryFrequency and context.Statistics members /// of PpmContext use 6 bytes and so can therefore fit into the space used by the Symbol, Frequency and /// Successor members of PpmState, since they also add up to 6 bytes). /// </para> /// <para> /// PpmContext (context.SummaryFrequency and context.Statistics use 6 bytes) /// 1 context.NumberStatistics /// 1 context.Flags /// 2 context.SummaryFrequency /// 4 context.Statistics (pointer to PpmState) /// 4 context.Suffix (pointer to PpmContext) /// </para> /// <para> /// PpmState (total of 6 bytes) /// 1 Symbol /// 1 Frequency /// 4 Successor (pointer to PpmContext) /// </para> /// </remarks> /// <returns></returns> public PpmState FirstState { get { return new PpmState(Address + 2, Memory); } } /// <summary> /// Gets or sets the symbol of the first PPM state. This is provided for convenience. The same /// information can be obtained using the Symbol property on the PPM state provided by the /// <see cref="FirstState"/> property. /// </summary> public byte FirstStateSymbol { get { return Memory[Address + 2]; } set { Memory[Address + 2] = value; } } /// <summary> /// Gets or sets the frequency of the first PPM state. This is provided for convenience. The same /// information can be obtained using the Frequency property on the PPM state provided by the ///context.FirstState property. /// </summary> public byte FirstStateFrequency { get { return Memory[Address + 3]; } set { Memory[Address + 3] = value; } } /// <summary> /// Gets or sets the successor of the first PPM state. This is provided for convenience. The same /// information can be obtained using the Successor property on the PPM state provided by the /// </summary> public PpmContext FirstStateSuccessor { get { return new PpmContext( ((uint) Memory[Address + 4]) | ((uint) Memory[Address + 5]) << 8 | ((uint) Memory[Address + 6]) << 16 | ((uint) Memory[Address + 7]) << 24, Memory); } set { Memory[Address + 4] = (byte) value.Address; Memory[Address + 5] = (byte) (value.Address >> 8); Memory[Address + 6] = (byte) (value.Address >> 16); Memory[Address + 7] = (byte) (value.Address >> 24); } } /// <summary> /// Allow a pointer to be implicitly converted to a PPM context. /// </summary> /// <param name="pointer"></param> /// <returns></returns> public static implicit operator PpmContext(Pointer pointer) { return new PpmContext(pointer.Address, pointer.Memory); } /// <summary> /// Allow pointer-like addition on a PPM context. /// </summary> /// <param name="context"></param> /// <param name="offset"></param> /// <returns></returns> public static PpmContext operator +(PpmContext context, int offset) { context.Address = (uint) (context.Address + offset*Size); return context; } /// <summary> /// Allow pointer-like subtraction on a PPM context. /// </summary> /// <param name="context"></param> /// <param name="offset"></param> /// <returns></returns> public static PpmContext operator -(PpmContext context, int offset) { context.Address = (uint) (context.Address - offset*Size); return context; } /// <summary> /// Compare two PPM contexts. /// </summary> /// <param name="context1"></param> /// <param name="context2"></param> /// <returns></returns> public static bool operator <=(PpmContext context1, PpmContext context2) { return context1.Address <= context2.Address; } /// <summary> /// Compare two PPM contexts. /// </summary> /// <param name="context1"></param> /// <param name="context2"></param> /// <returns></returns> public static bool operator >=(PpmContext context1, PpmContext context2) { return context1.Address >= context2.Address; } /// <summary> /// Compare two PPM contexts. /// </summary> /// <param name="context1"></param> /// <param name="context2"></param> /// <returns></returns> public static bool operator ==(PpmContext context1, PpmContext context2) { return context1.Address == context2.Address; } /// <summary> /// Compare two PPM contexts. /// </summary> /// <param name="context1"></param> /// <param name="context2"></param> /// <returns></returns> public static bool operator !=(PpmContext context1, PpmContext context2) { return context1.Address != context2.Address; } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <returns>true if obj and this instance are the same type and represent the same value; otherwise, false.</returns> /// <param name="obj">Another object to compare to.</param> public override bool Equals(object obj) { if (obj is PpmContext) { PpmContext context = (PpmContext) obj; return context.Address == Address; } return base.Equals(obj); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A 32-bit signed integer that is the hash code for this instance.</returns> public override int GetHashCode() { return Address.GetHashCode(); } } private void EncodeBinarySymbol(int symbol, PpmContext context) { PpmState state = context.FirstState; int index1 = probabilities[state.Frequency - 1]; int index2 = numberStatisticsToBinarySummaryIndex[context.Suffix.NumberStatistics] + previousSuccess + context.Flags + ((runLength >> 26) & 0x20); if (state.Symbol == symbol) { foundState = state; state.Frequency += (byte) ((state.Frequency < 196) ? 1 : 0); Coder.LowCount = 0; Coder.HighCount = binarySummary[index1, index2]; binarySummary[index1, index2] += (ushort) (Interval - Mean(binarySummary[index1, index2], PeriodBitCount, 2)); previousSuccess = 1; runLength++; } else { Coder.LowCount = binarySummary[index1, index2]; binarySummary[index1, index2] -= (ushort) Mean(binarySummary[index1, index2], PeriodBitCount, 2); Coder.HighCount = BinaryScale; initialEscape = ExponentialEscapes[binarySummary[index1, index2] >> 10]; characterMask[state.Symbol] = escapeCount; previousSuccess = 0; numberMasked = 0; foundState = PpmState.Zero; } } private void EncodeSymbol1(int symbol, PpmContext context) { uint lowCount; uint index = context.Statistics.Symbol; PpmState state = context.Statistics; Coder.Scale = context.SummaryFrequency; if (index == symbol) { Coder.HighCount = state.Frequency; previousSuccess = (byte) ((2*Coder.HighCount >= Coder.Scale) ? 1 : 0); foundState = state; foundState.Frequency += 4; context.SummaryFrequency += 4; runLength += previousSuccess; if (state.Frequency > MaximumFrequency) Rescale(context); Coder.LowCount = 0; return; } lowCount = state.Frequency; index = context.NumberStatistics; previousSuccess = 0; while ((++state).Symbol != symbol) { lowCount += state.Frequency; if (--index == 0) { Coder.LowCount = lowCount; characterMask[state.Symbol] = escapeCount; numberMasked = context.NumberStatistics; index = context.NumberStatistics; foundState = PpmState.Zero; do { characterMask[(--state).Symbol] = escapeCount; } while (--index != 0); Coder.HighCount = Coder.Scale; return; } } Coder.HighCount = (Coder.LowCount = lowCount) + state.Frequency; Update1(state, context); } private void EncodeSymbol2(int symbol, PpmContext context) { See2Context see2Context = MakeEscapeFrequency(context); uint currentSymbol; uint lowCount = 0; uint index = (uint) (context.NumberStatistics - numberMasked); PpmState state = context.Statistics - 1; do { do { currentSymbol = state[1].Symbol; state++; } while (characterMask[currentSymbol] == escapeCount); characterMask[currentSymbol] = escapeCount; if (currentSymbol == symbol) goto SymbolFound; lowCount += state.Frequency; } while (--index != 0); Coder.LowCount = lowCount; Coder.Scale += Coder.LowCount; Coder.HighCount = Coder.Scale; see2Context.Summary += (ushort) Coder.Scale; numberMasked = context.NumberStatistics; return; SymbolFound: Coder.LowCount = lowCount; lowCount += state.Frequency; Coder.HighCount = lowCount; for (PpmState p1 = state; --index != 0;) { do { currentSymbol = p1[1].Symbol; p1++; } while (characterMask[currentSymbol] == escapeCount); lowCount += p1.Frequency; } Coder.Scale += lowCount; see2Context.Update(); Update2(state, context); } private void DecodeBinarySymbol(PpmContext context) { PpmState state = context.FirstState; int index1 = probabilities[state.Frequency - 1]; int index2 = numberStatisticsToBinarySummaryIndex[context.Suffix.NumberStatistics] + previousSuccess + context.Flags + ((runLength >> 26) & 0x20); if (Coder.RangeGetCurrentShiftCount(TotalBitCount) < binarySummary[index1, index2]) { foundState = state; state.Frequency += (byte) ((state.Frequency < 196) ? 1 : 0); Coder.LowCount = 0; Coder.HighCount = binarySummary[index1, index2]; binarySummary[index1, index2] += (ushort) (Interval - Mean(binarySummary[index1, index2], PeriodBitCount, 2)); previousSuccess = 1; runLength++; } else { Coder.LowCount = binarySummary[index1, index2]; binarySummary[index1, index2] -= (ushort) Mean(binarySummary[index1, index2], PeriodBitCount, 2); Coder.HighCount = BinaryScale; initialEscape = ExponentialEscapes[binarySummary[index1, index2] >> 10]; characterMask[state.Symbol] = escapeCount; previousSuccess = 0; numberMasked = 0; foundState = PpmState.Zero; } } private void DecodeSymbol1(PpmContext context) { uint index; uint count; uint highCount = context.Statistics.Frequency; PpmState state = context.Statistics; Coder.Scale = context.SummaryFrequency; count = Coder.RangeGetCurrentCount(); if (count < highCount) { Coder.HighCount = highCount; previousSuccess = (byte) ((2*Coder.HighCount >= Coder.Scale) ? 1 : 0); foundState = state; highCount += 4; foundState.Frequency = (byte) highCount; context.SummaryFrequency += 4; runLength += previousSuccess; if (highCount > MaximumFrequency) Rescale(context); Coder.LowCount = 0; return; } index = context.NumberStatistics; previousSuccess = 0; while ((highCount += (++state).Frequency) <= count) { if (--index == 0) { Coder.LowCount = highCount; characterMask[state.Symbol] = escapeCount; numberMasked = context.NumberStatistics; index = context.NumberStatistics; foundState = PpmState.Zero; do { characterMask[(--state).Symbol] = escapeCount; } while (--index != 0); Coder.HighCount = Coder.Scale; return; } } Coder.HighCount = highCount; Coder.LowCount = Coder.HighCount - state.Frequency; Update1(state, context); } private void DecodeSymbol2(PpmContext context) { See2Context see2Context = MakeEscapeFrequency(context); uint currentSymbol; uint count; uint highCount = 0; uint index = (uint) (context.NumberStatistics - numberMasked); uint stateIndex = 0; PpmState state = context.Statistics - 1; do { do { currentSymbol = state[1].Symbol; state++; } while (characterMask[currentSymbol] == escapeCount); highCount += state.Frequency; decodeStates[stateIndex++] = state; // note that decodeStates is a static array that is re-used on each call to this method (for performance reasons) } while (--index != 0); Coder.Scale += highCount; count = Coder.RangeGetCurrentCount(); stateIndex = 0; state = decodeStates[stateIndex]; if (count < highCount) { highCount = 0; while ((highCount += state.Frequency) <= count) state = decodeStates[++stateIndex]; Coder.HighCount = highCount; Coder.LowCount = Coder.HighCount - state.Frequency; see2Context.Update(); Update2(state, context); } else { Coder.LowCount = highCount; Coder.HighCount = Coder.Scale; index = (uint) (context.NumberStatistics - numberMasked); numberMasked = context.NumberStatistics; do { characterMask[decodeStates[stateIndex].Symbol] = escapeCount; stateIndex++; } while (--index != 0); see2Context.Summary += (ushort) Coder.Scale; } } private void Update1(PpmState state, PpmContext context) { foundState = state; foundState.Frequency += 4; context.SummaryFrequency += 4; if (state[0].Frequency > state[-1].Frequency) { Swap(state[0], state[-1]); foundState = --state; if (state.Frequency > MaximumFrequency) Rescale(context); } } private void Update2(PpmState state, PpmContext context) { foundState = state; foundState.Frequency += 4; context.SummaryFrequency += 4; if (state.Frequency > MaximumFrequency) Rescale(context); escapeCount++; runLength = initialRunLength; } private See2Context MakeEscapeFrequency(PpmContext context) { uint numberStatistics = (uint) 2*context.NumberStatistics; See2Context see2Context; if (context.NumberStatistics != 0xff) { // Note that context.Flags is always in the range 0 .. 28 (this ensures that the index used for the second // dimension of the see2Contexts array is always in the range 0 .. 31). numberStatistics = context.Suffix.NumberStatistics; int index1 = probabilities[context.NumberStatistics + 2] - 3; int index2 = ((context.SummaryFrequency > 11*(context.NumberStatistics + 1)) ? 1 : 0) + ((2*context.NumberStatistics < numberStatistics + numberMasked) ? 2 : 0) + context.Flags; see2Context = see2Contexts[index1, index2]; Coder.Scale = see2Context.Mean(); } else { see2Context = emptySee2Context; Coder.Scale = 1; } return see2Context; } private void Rescale(PpmContext context) { uint oldUnitCount; int adder; uint escapeFrequency; uint index = context.NumberStatistics; byte localSymbol; byte localFrequency; PpmContext localSuccessor; PpmState p1; PpmState state; for (state = foundState; state != context.Statistics; state--) Swap(state[0], state[-1]); state.Frequency += 4; context.SummaryFrequency += 4; escapeFrequency = (uint) (context.SummaryFrequency - state.Frequency); adder = (orderFall != 0 || method > ModelRestorationMethod.Freeze) ? 1 : 0; state.Frequency = (byte) ((state.Frequency + adder) >> 1); context.SummaryFrequency = state.Frequency; do { escapeFrequency -= (++state).Frequency; state.Frequency = (byte) ((state.Frequency + adder) >> 1); context.SummaryFrequency += state.Frequency; if (state[0].Frequency > state[-1].Frequency) { p1 = state; localSymbol = p1.Symbol; localFrequency = p1.Frequency; localSuccessor = p1.Successor; do { Copy(p1[0], p1[-1]); } while (localFrequency > (--p1)[-1].Frequency); p1.Symbol = localSymbol; p1.Frequency = localFrequency; p1.Successor = localSuccessor; } } while (--index != 0); if (state.Frequency == 0) { do { index++; } while ((--state).Frequency == 0); escapeFrequency += index; oldUnitCount = (uint) ((context.NumberStatistics + 2) >> 1); context.NumberStatistics -= (byte) index; if (context.NumberStatistics == 0) { localSymbol = context.Statistics.Symbol; localFrequency = context.Statistics.Frequency; localSuccessor = context.Statistics.Successor; localFrequency = (byte) ((2*localFrequency + escapeFrequency - 1)/escapeFrequency); if (localFrequency > MaximumFrequency/3) localFrequency = (byte) (MaximumFrequency/3); Allocator.FreeUnits(context.Statistics, oldUnitCount); context.FirstStateSymbol = localSymbol; context.FirstStateFrequency = localFrequency; context.FirstStateSuccessor = localSuccessor; context.Flags = (byte) ((context.Flags & 0x10) + ((localSymbol >= 0x40) ? 0x08 : 0x00)); foundState = context.FirstState; return; } context.Statistics = Allocator.ShrinkUnits(context.Statistics, oldUnitCount, (uint) ((context.NumberStatistics + 2) >> 1)); context.Flags &= 0xf7; index = context.NumberStatistics; state = context.Statistics; context.Flags |= (byte) ((state.Symbol >= 0x40) ? 0x08 : 0x00); do { context.Flags |= (byte) (((++state).Symbol >= 0x40) ? 0x08 : 0x00); } while (--index != 0); } escapeFrequency -= (escapeFrequency >> 1); context.SummaryFrequency += (ushort) escapeFrequency; context.Flags |= 0x04; foundState = context.Statistics; } private void Refresh(uint oldUnitCount, bool scale, PpmContext context) { int index = context.NumberStatistics; int escapeFrequency; int scaleValue = (scale ? 1 : 0); context.Statistics = Allocator.ShrinkUnits(context.Statistics, oldUnitCount, (uint) ((index + 2) >> 1)); PpmState statistics = context.Statistics; context.Flags = (byte) ((context.Flags & (0x10 + (scale ? 0x04 : 0x00))) + ((statistics.Symbol >= 0x40) ? 0x08 : 0x00)); escapeFrequency = context.SummaryFrequency - statistics.Frequency; statistics.Frequency = (byte) ((statistics.Frequency + scaleValue) >> scaleValue); context.SummaryFrequency = statistics.Frequency; do { escapeFrequency -= (++statistics).Frequency; statistics.Frequency = (byte) ((statistics.Frequency + scaleValue) >> scaleValue); context.SummaryFrequency += statistics.Frequency; context.Flags |= (byte) ((statistics.Symbol >= 0x40) ? 0x08 : 0x00); } while (--index != 0); escapeFrequency = (escapeFrequency + scaleValue) >> scaleValue; context.SummaryFrequency += (ushort) escapeFrequency; } private PpmContext CutOff(int order, PpmContext context) { int index; PpmState state; if (context.NumberStatistics == 0) { state = context.FirstState; if ((Pointer) state.Successor >= Allocator.BaseUnit) { if (order < modelOrder) state.Successor = CutOff(order + 1, state.Successor); else state.Successor = PpmContext.Zero; if (state.Successor == PpmContext.Zero && order > OrderBound) { Allocator.SpecialFreeUnits(context); return PpmContext.Zero; } return context; } else { Allocator.SpecialFreeUnits(context); return PpmContext.Zero; } } uint unitCount = (uint) ((context.NumberStatistics + 2) >> 1); context.Statistics = Allocator.MoveUnitsUp(context.Statistics, unitCount); index = context.NumberStatistics; for (state = context.Statistics + index; state >= context.Statistics; state--) { if (state.Successor < Allocator.BaseUnit) { state.Successor = PpmContext.Zero; Swap(state, context.Statistics[index--]); } else if (order < modelOrder) state.Successor = CutOff(order + 1, state.Successor); else state.Successor = PpmContext.Zero; } if (index != context.NumberStatistics && order != 0) { context.NumberStatistics = (byte) index; state = context.Statistics; if (index < 0) { Allocator.FreeUnits(state, unitCount); Allocator.SpecialFreeUnits(context); return PpmContext.Zero; } else if (index == 0) { context.Flags = (byte) ((context.Flags & 0x10) + ((state.Symbol >= 0x40) ? 0x08 : 0x00)); Copy(context.FirstState, state); Allocator.FreeUnits(state, unitCount); context.FirstStateFrequency = (byte) ((context.FirstStateFrequency + 11) >> 3); } else { Refresh(unitCount, context.SummaryFrequency > 16*index, context); } } return context; } private PpmContext RemoveBinaryContexts(int order, PpmContext context) { if (context.NumberStatistics == 0) { PpmState state = context.FirstState; if ((Pointer) state.Successor >= Allocator.BaseUnit && order < modelOrder) state.Successor = RemoveBinaryContexts(order + 1, state.Successor); else state.Successor = PpmContext.Zero; if ((state.Successor == PpmContext.Zero) && (context.Suffix.NumberStatistics == 0 || context.Suffix.Flags == 0xff)) { Allocator.FreeUnits(context, 1); return PpmContext.Zero; } else { return context; } } for (PpmState state = context.Statistics + context.NumberStatistics; state >= context.Statistics; state--) { if ((Pointer) state.Successor >= Allocator.BaseUnit && order < modelOrder) state.Successor = RemoveBinaryContexts(order + 1, state.Successor); else state.Successor = PpmContext.Zero; } return context; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter; using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite; using Microsoft.Protocols.TestTools; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2.TestSuite { public partial class MultipleChannelExtendedTest : SMB2TestBase { #region Test Cases [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.CombinedFeature)] [TestCategory(TestCategories.Positive)] [Description("Operate file via multi-channel with encryption on both channels.")] public void MultipleChannel_EncryptionOnBothChannels() { #region Check Applicability TestConfig.CheckDialect(DialectRevision.Smb30); TestConfig.CheckCapabilities(NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_ENCRYPTION | NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_MULTI_CHANNEL); #endregion uncSharePath = Smb2Utility.GetUncPath(TestConfig.SutComputerName, TestConfig.EncryptedFileShare); uint treeId; FILEID fileId; BaseTestSite.Log.Add( LogEntryKind.TestStep, "Establish main channel with client {0} and server {1}, encryption is enabled.", clientIps[0].ToString(), serverIps[0].ToString()); EstablishMainChannel( TestConfig.RequestDialects, serverIps[0], clientIps[0], out treeId, true); #region CREATE BaseTestSite.Log.Add(LogEntryKind.TestStep, "Main channel: Create file {0}.", fileName); Smb2CreateContextResponse[] serverCreateContexts; status = mainChannelClient.Create( treeId, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE | CreateOptions_Values.FILE_DELETE_ON_CLOSE, out fileId, out serverCreateContexts); #endregion #region WRITE BaseTestSite.Log.Add(LogEntryKind.TestStep, "Main channel: Write content to file."); status = mainChannelClient.Write(treeId, fileId, contentWrite); #endregion BaseTestSite.Log.Add( LogEntryKind.TestStep, "Establish alternative channel with client {0} and server {1}, encryption is enabled.", clientIps[1].ToString(), serverIps[1].ToString()); EstablishAlternativeChannel( TestConfig.RequestDialects, serverIps[1], clientIps[1], treeId, true); #region READ BaseTestSite.Log.Add(LogEntryKind.TestStep, "Alternative channel: Read content from file."); status = alternativeChannelClient.Read(treeId, fileId, 0, (uint)contentWrite.Length, out contentRead); #endregion BaseTestSite.Log.Add( LogEntryKind.TestStep, "Verify the contents read from alternative channel are the same as the one written by main channel."); BaseTestSite.Assert.IsTrue( contentRead.Equals(contentWrite), "Read content should be consistent with written content"); ClientTearDown(alternativeChannelClient, treeId, fileId); } [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.CombinedFeature)] [TestCategory(TestCategories.Compatibility)] [Description("Operate file via multi-channel only with encryption on main channel.")] public void MultipleChannel_Negative_EncryptionOnMainChannel() { uncSharePath = Smb2Utility.GetUncPath(TestConfig.SutComputerName, TestConfig.EncryptedFileShare); uint treeId; FILEID fileId; BaseTestSite.Log.Add( LogEntryKind.TestStep, "Establish main channel with client {0} and server {1}, encryption is enabled.", clientIps[0].ToString(), serverIps[0].ToString()); EstablishMainChannel( TestConfig.RequestDialects, serverIps[0], clientIps[0], out treeId, true); #region CREATE BaseTestSite.Log.Add(LogEntryKind.TestStep, "Main channel: Create file {0}.", fileName); Smb2CreateContextResponse[] serverCreateContexts; status = mainChannelClient.Create( treeId, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE | CreateOptions_Values.FILE_DELETE_ON_CLOSE, out fileId, out serverCreateContexts); #endregion #region WRITE BaseTestSite.Log.Add(LogEntryKind.TestStep, "Main channel: Write content to file."); status = mainChannelClient.Write(treeId, fileId, contentWrite); #endregion BaseTestSite.Log.Add( LogEntryKind.TestStep, "Establish alternative channel with client {0} and server {1}, encryption is NOT enabled.", clientIps[1].ToString(), serverIps[1].ToString()); EstablishAlternativeChannel( TestConfig.RequestDialects, serverIps[1], clientIps[1], treeId, false); #region READ // Skip the verification of signature when sending a non-encrypted CREATE request to an encrypted share alternativeChannelClient.Smb2Client.DisableVerifySignature = true; BaseTestSite.Log.Add(LogEntryKind.TestStep, "Alternative channel: Read content from file."); status = alternativeChannelClient.Read( treeId, fileId, 0, (uint)contentWrite.Length, out contentRead, checker: (header, response) => { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Verify Server response indicates that read content failed."); BaseTestSite.Assert.AreNotEqual( Smb2Status.STATUS_SUCCESS, header.Status, "Read data from file should not success"); BaseTestSite.CaptureRequirementIfAreEqual( Smb2Status.STATUS_ACCESS_DENIED, header.Status, RequirementCategory.STATUS_ACCESS_DENIED.Id, RequirementCategory.STATUS_ACCESS_DENIED.Description); }); #endregion } [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.CombinedFeature)] [TestCategory(TestCategories.Compatibility)] [Description("Operate file via multi-channel only with encryption on alternative channel.")] public void MultipleChannel_Negative_EncryptionOnAlternativeChannel() { uncSharePath = Smb2Utility.GetUncPath(TestConfig.SutComputerName, TestConfig.EncryptedFileShare); uint treeId; FILEID fileId; BaseTestSite.Log.Add( LogEntryKind.TestStep, "Establish main channel with client {0} and server {1}, encryption is NOT enabled.", clientIps[0].ToString(), serverIps[0].ToString()); EstablishMainChannel( TestConfig.RequestDialects, serverIps[0], clientIps[0], out treeId, false); #region CREATE // Skip the verification of signature when sending a non-encrypted CREATE request to an encrypted share mainChannelClient.Smb2Client.DisableVerifySignature = true; BaseTestSite.Log.Add(LogEntryKind.TestStep, "Main channel: Create file {0}.", fileName); Smb2CreateContextResponse[] serverCreateContexts; status = mainChannelClient.Create( treeId, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE | CreateOptions_Values.FILE_DELETE_ON_CLOSE, out fileId, out serverCreateContexts, checker: (header, response) => { BaseTestSite.Assert.AreNotEqual( Smb2Status.STATUS_SUCCESS, header.Status, "Create file without encryption on encrypted share is expected to fail"); BaseTestSite.CaptureRequirementIfAreEqual( Smb2Status.STATUS_ACCESS_DENIED, header.Status, RequirementCategory.STATUS_ACCESS_DENIED.Id, RequirementCategory.STATUS_ACCESS_DENIED.Description); }); #endregion BaseTestSite.Log.Add( LogEntryKind.TestStep, "Establish alternative channel with client {0} and server {1}, encryption is enabled.", clientIps[1].ToString(), serverIps[1].ToString()); EstablishAlternativeChannel( TestConfig.RequestDialects, serverIps[1], clientIps[1], treeId, true); #region READ BaseTestSite.Log.Add(LogEntryKind.TestStep, "Alternative channel: Read content from file."); status = alternativeChannelClient.Read( treeId, fileId, 0, (uint)contentWrite.Length, out contentRead, checker: (header, response) => { BaseTestSite.Assert.AreNotEqual( Smb2Status.STATUS_SUCCESS, header.Status, "Read data from file should not success"); BaseTestSite.CaptureRequirementIfAreEqual( Smb2Status.STATUS_FILE_CLOSED, header.Status, RequirementCategory.STATUS_FILE_CLOSED.Id, RequirementCategory.STATUS_FILE_CLOSED.Description); }); #endregion } #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public partial class CompilationState { class ExceptionMapBuilder { // // State // ExceptionMap m_exceptionMap; SequentialRegion m_firstRegion; SequentialRegion m_lastRegion; ExceptionMap.Range m_currentRange; // // Constructor Methods // internal ExceptionMapBuilder( ExceptionMap em ) { m_exceptionMap = em; } // // Helper Methods // internal void Compress( DataManager dm , SequentialRegion reg ) { BasicBlock bb = (BasicBlock)reg.Context; ExceptionMap.Range range = m_currentRange; range.Handlers = ExceptionMap.Handler.SharedEmptyArray; foreach(ExceptionHandlerBasicBlock ehBB in bb.ProtectedBy) { foreach(ExceptionClause ec in ehBB.HandlerFor) { ExceptionMap.Handler hnd = new ExceptionMap.Handler(); TypeRepresentation td = ec.ClassObject; bool fAdd = true; hnd.HandlerCode = dm.CreateCodePointer( ehBB ); if(td != null) { hnd.Filter = td.VirtualTable; } uint handlerAddress = reg.Owner.Resolve( ehBB ); for(int i = 0; i < range.Handlers.Length; i++) { VTable filter = range.Handlers[i].Filter; if(filter == null) { // // There's already a catch-all, no need to extend the set of handlers. // fAdd = false; break; } if(filter.TypeInfo.IsSuperClassOf( td, null )) { // // There's already a less-specific catch, no need to extend the set of handlers. // fAdd = false; break; } // // Same handlers? Then this could be a less-specific catch, update the handler. // object ehBB2 = dm.GetCodePointerFromUniqueID( range.Handlers[i].HandlerCode.Target ); uint handlerAddress2 = reg.Owner.Resolve( ehBB2 ); if(handlerAddress == handlerAddress2) { range.Handlers[i].Filter = hnd.Filter; fAdd = false; break; } } if(fAdd) { hnd.HandlerCode = dm.CreateCodePointer( ehBB ); range.Handlers = ArrayUtility.AppendToNotNullArray( range.Handlers, hnd ); } } } if(m_currentRange.SameContents( ref range ) == false) { Emit(); } else if(m_lastRegion != null) { uint startAddress = reg .BaseAddress.ToUInt32(); uint endAddress = m_lastRegion.EndAddress .ToUInt32(); if(endAddress != startAddress) { CHECKS.ASSERT( endAddress < startAddress, "Incorrect ordering of regions: {0} <=> {1}", reg, m_lastRegion ); Emit(); } } m_currentRange = range; if(m_firstRegion == null) { m_firstRegion = reg; m_currentRange.Start = reg.BaseAddress; } m_lastRegion = reg; } internal void Emit() { if(m_firstRegion != null) { if(m_currentRange.Handlers.Length > 0) { m_currentRange.End = m_lastRegion.EndAddress; if(m_currentRange.Start != m_currentRange.End) { // // Only emit non-empty ranges that have handlers. // m_exceptionMap.Ranges = ArrayUtility.AppendToNotNullArray( m_exceptionMap.Ranges, m_currentRange ); } } m_firstRegion = null; m_lastRegion = null; } } } // // State // // // Constructor Methods // // // Helper Methods // internal bool CreateExceptionHandlingTables() { SequentialRegion[] regions = GetSortedCodeRegions(); //--// ExceptionMap em = new ExceptionMap(); em.Ranges = ExceptionMap.Range.SharedEmptyArray; DataManager dm = m_cfg.TypeSystem.DataManagerInstance; ExceptionMapBuilder emb = new ExceptionMapBuilder( em ); foreach(SequentialRegion reg in regions) { emb.Compress( dm, reg ); } emb.Emit(); //--// if(em.Ranges.Length == 0) { em = null; } ExceptionMap emOld = m_cfg.Method.CodeMap.ExceptionMap; bool fModified = ExceptionMap.SameContents( em, emOld ) == false; if(fModified) { m_cfg.Method.CodeMap.ExceptionMap = em; } return fModified; } } }
using System; using System.Linq; using NUnit.Framework; using TickedPriorityQueue; namespace TickedPriorityQueueUnitTests { [TestFixture] public class TickedQueueUnit { private int test1 = -1; private int aCalled; private int bCalled; private int cCalled; private int test3 = -1; private void InitializeTestValues() { test1 = -1; aCalled = 0; bCalled = 0; cCalled = 0; test3 = -1; } [Test] public void TestPriority() { InitializeTestValues(); var queue = new TickedQueue(); var a = new TickedObject(CallbackSetTest1, 0, 0) {Priority = 0}; var b = new TickedObject(CallbackSetTest1, 0, 2) {Priority = 2}; var c = new TickedObject(CallbackSetTest1, 0, 1) {Priority = 1}; queue.Add(a); queue.Add(b); queue.Add(c); Assert.AreEqual(-1, test1, "test1 should be initialized with -1"); queue.Update(); Assert.AreEqual(-1, test1, "test1 should still be same after first update, as none of the objects should have ticked"); queue.Update(DateTime.UtcNow.AddSeconds(2)); Assert.AreNotEqual(-1, test1, "test1 should have changed after all three items ticked"); Assert.AreEqual(2, test1, "test1 should have been updated to the last object"); } [Test] public void TestPauseBasic() { InitializeTestValues(); var queue = new TickedQueue(); var a = new TickedObject(CallbackSetTest1, 0); queue.Add(a); Assert.AreEqual(-1, test1, "test1 should be initialized with -1"); queue.IsPaused = true; queue.Update(); Assert.AreEqual(-1, test1, "test1 should be initialized with -1"); queue.Update(DateTime.UtcNow.AddSeconds(2)); Assert.AreEqual(-1, test1, "test1 should be initialized with -1"); } [Test] public void TestUnPauseBasic() { InitializeTestValues(); var queue = new TickedQueue(); var a = new TickedObject(CallbackSetTest1, 0); queue.Add(a); Assert.AreEqual(-1, test1, "test1 should be initialized with -1"); queue.IsPaused = true; queue.Update(); Assert.AreEqual(-1, test1, "test1 should be initialized with -1"); queue.Update(DateTime.UtcNow.AddSeconds(2)); Assert.AreEqual(-1, test1, "test1 should be initialized with -1"); queue.IsPaused = false; queue.Update(); Assert.AreEqual(-1, test1, "test1 should be set to 0 after the queue is updated"); } [Test] public void TestUnPausePriority() { InitializeTestValues(); var queue = new TickedQueue(); var a = new TickedObject(CallbackSetTest1, 0, 0) {Priority = 0}; var b = new TickedObject(CallbackSetTest1, 0, 2) {Priority = 2}; var c = new TickedObject(CallbackSetTest1, 0, 1) {Priority = 1}; queue.Add(a); queue.Add(b); queue.Add(c); Assert.AreEqual(-1, test1, "test1 should be initialized with -1"); queue.IsPaused = true; queue.Update(DateTime.UtcNow.AddSeconds(2)); Assert.AreEqual(-1, test1, "test1 should be still be -1, since we are paused"); queue.IsPaused = false; queue.Update(DateTime.UtcNow.AddSeconds(2)); Assert.AreNotEqual(-1, test1, "test1 should have changed after all three items ticked"); Assert.AreEqual(2, test1, "test1 should have been updated to the last object"); } [Test] public void TestTiming() { var queue = new TickedQueue(); var a = new TickedObject(Callback2, 1, 0) {Priority = 1}; var b = new TickedObject(Callback2, 5, 2) {Priority = 3}; var c = new TickedObject(Callback2, 2, 1) {Priority = 2}; queue.Add(a); queue.Add(b); queue.Add(c); Assert.AreEqual(0, aCalled + bCalled + cCalled, "called variables should be initialized with 0"); queue.Update(); Assert.AreEqual(0, aCalled + bCalled + cCalled, "called variables should be 0 with 0 time update"); queue.Update(DateTime.UtcNow.AddSeconds(2.9f)); Assert.AreEqual(1, aCalled, "a should have been called once"); Assert.AreEqual(1, cCalled, "c should have been called once"); Assert.AreEqual(0, bCalled, "b should not have been called"); queue.Update(DateTime.UtcNow.AddSeconds(5.01f)); Assert.AreEqual(2, aCalled, "a should have been called twice"); Assert.AreEqual(2, cCalled, "c should have been called twice"); Assert.AreEqual(1, bCalled, "b should have been called once"); } [Test] public void TestRemove() { var queue = new TickedQueue(); var a = new TickedObject(Callback3, 0); a.TickLength = 1; queue.Add(a); queue.Update(DateTime.UtcNow.AddSeconds(2)); Assert.AreEqual(1, test3, "Callback should have been called for added item"); var result = queue.Remove(a); test3 = -1; Assert.IsTrue(result, "Call to remove the item should have returned true"); queue.Update(DateTime.UtcNow.AddSeconds(4)); Assert.AreEqual(-1, test3, "Callback should not have been called for removed item"); } [Test] public void TestRemoveWhileEnqueued() { var queue = new TickedQueue(); queue.MaxProcessedPerUpdate = 1; var aVal = 0; var a = new TickedObject((x => aVal++), 0); var bVal = 0; var b = new TickedObject((x => bVal++), 0); var cVal = 0; var c = new TickedObject((x => cVal++), 0); queue.Add(a, true); queue.Add(b, true); queue.Add(c, true); // Verify the queue works as expected queue.Update(DateTime.UtcNow.AddSeconds(0.5f)); Assert.AreEqual(1, aVal, "Invalid aVal after the first update"); Assert.AreEqual(0, bVal, "Invalid bVal after the first update"); Assert.AreEqual(0, cVal, "Invalid cVal after the first update"); Assert.IsTrue(queue.Remove(b), "Error removing B"); queue.Update(DateTime.UtcNow.AddSeconds(1f)); Assert.AreEqual(1, aVal, "Invalid aVal after the second update"); Assert.AreEqual(0, bVal, "B should not have been ticked after being removed"); Assert.AreEqual(1, cVal, "Invalid cVal after the second update"); queue.Update(DateTime.UtcNow.AddSeconds(1.5f)); Assert.AreEqual(2, aVal, "Invalid aVal after the third update"); Assert.AreEqual(0, bVal, "B should not have been ticked after being removed"); Assert.AreEqual(1, cVal, "Invalid cVal after the third update"); } /// <summary> /// Verifies that we can remove an item even while it is already on the work queue /// </summary> [Test] public void TestRemoveFromHandlerWhileInWorkQueue() { var queue = new TickedQueue(); queue.MaxProcessedPerUpdate = 10; var aVal = 0; var a = new TickedObject((x => aVal++), 0); var bVal = 0; var b = new TickedObject((x => bVal++), 0); var cVal = 0; var c = new TickedObject((x => { cVal += 2; queue.Remove(b); }), 0); queue.Add(a, true); queue.Add(c, true); // c will execute before B and remove it queue.Add(b, true); // Verify the queue works as expected queue.Update(DateTime.UtcNow.AddSeconds(0.5f)); Assert.AreEqual(1, aVal, "Invalid aVal after the first update"); Assert.AreEqual(2, cVal, "Invalid cVal after the first update"); Assert.AreEqual(0, bVal, "b should not have executed"); Assert.IsFalse(queue.Items.Contains(b), "b should not be on the queue"); queue.Update(DateTime.UtcNow.AddSeconds(1f)); Assert.AreEqual(2, aVal, "Invalid aVal after the second update"); Assert.AreEqual(4, cVal, "Invalid cVal after the second update"); Assert.AreEqual(0, bVal, "b should not have executed"); Assert.IsFalse(queue.Items.Contains(b), "b should still not be on the queue"); } /// <summary> /// Verifies that we can remove an item even while it is already on the work queue /// </summary> [Test] public void TestRemoveFromHandlerAfterPassingInWorkQueue() { var queue = new TickedQueue {MaxProcessedPerUpdate = 10}; var aVal = 0; var a = new TickedObject((x => aVal++)); var bVal = 0; var b = new TickedObject((x => bVal++)); var cVal = 0; var c = new TickedObject((x => { cVal += 2; queue.Remove(b); })); var time = DateTime.UtcNow; queue.Add(a, time, true); queue.Add(b, time, true); queue.Add(c, time, true); // c will remove b, so it should execute only once // Verify the queue works as expected queue.Update(DateTime.UtcNow.AddSeconds(0.5f)); Assert.AreEqual(1, aVal, "Invalid aVal after the first update"); Assert.AreEqual(2, cVal, "Invalid cVal after the first update"); Assert.AreEqual(1, bVal, "b should have executed the first time"); Assert.IsFalse(queue.Items.Contains(b), "b should no longer be on the queue"); queue.Update(DateTime.UtcNow.AddSeconds(1f)); Assert.AreEqual(2, aVal, "Invalid aVal after the second update"); Assert.AreEqual(4, cVal, "Invalid cVal after the second update"); Assert.AreEqual(1, bVal, "b should not have executed again"); Assert.IsFalse(queue.Items.Contains(b), "b should still not be on the queue"); } [Test] public void TestInvalidRemove() { var queue = new TickedQueue(); var a = new TickedObject(Callback3, 1); queue.Add(a); var b = new TickedObject(Callback3); var result = queue.Remove(b); Assert.IsFalse(result, "Call to remove the B should have returned false"); } [Test] public void TestNoExceptionHandler() { var queue = new TickedQueue {MaxProcessedPerUpdate = 1}; var aVal = 0; var a = new TickedObject((x => aVal++), 0); var b = new TickedObject((x => { throw new NotImplementedException("Not implemented method"); }), 0); queue.Add(a, true); queue.Add(b, true); // Verify the queue works as expected queue.Update(DateTime.UtcNow.AddSeconds(0.5f)); Assert.AreEqual(1, aVal, "Invalid aVal after the first update"); TestDelegate testDelegate = (() => queue.Update(DateTime.UtcNow.AddSeconds(1f))); Assert.Throws<NotImplementedException>(testDelegate, "Expected a not-implemented exception"); Assert.AreEqual(1, aVal, "Invalid aVal after the third update"); queue.Update(DateTime.UtcNow.AddSeconds(1.5f)); Assert.AreEqual(2, aVal, "Invalid aVal after the third update"); } [Test] public void TestExceptionHandler() { Exception raised = null; ITicked itemException = null; var queue = new TickedQueue {MaxProcessedPerUpdate = 1}; queue.TickExceptionHandler += delegate(Exception e, ITicked t) { raised = e; itemException = t; }; var aVal = 0; var a = new TickedObject((x => aVal++), 0); var b = new TickedObject((x => { throw new NotImplementedException("HELLO WORLD!"); }), 0); queue.Add(a, true); queue.Add(b, DateTime.UtcNow.AddMilliseconds(1), true); // Verify the queue works as expected queue.Update(DateTime.UtcNow.AddSeconds(0.5f)); Assert.AreEqual(1, aVal, "Invalid aVal after the first update"); TestDelegate testDelegate = (() => queue.Update(DateTime.UtcNow.AddSeconds(1f))); Assert.DoesNotThrow(testDelegate, "Did not expect any exceptions to be thrown"); Assert.AreEqual(1, aVal, "Invalid aVal after the third update"); Assert.AreEqual("HELLO WORLD!", raised.Message); Assert.IsInstanceOf<NotImplementedException>(raised); Assert.AreSame(itemException, b); } [Test] public void TestMaxProcessedPerUpdate() { var queue = new TickedQueue {MaxProcessedPerUpdate = 1}; var aVal = 0; var a = new TickedObject((x => aVal++)); var bVal = 0; var b = new TickedObject((x => bVal++)); var cVal = 0; var c = new TickedObject((x => cVal++)); queue.Add(a, true); queue.Add(b, true); queue.Add(c, true); // Verify the queue works as expected queue.Update(DateTime.UtcNow.AddSeconds(0.5f)); Assert.AreEqual(1, aVal, "Invalid aVal after the first update"); Assert.AreEqual(0, bVal, "Invalid bVal after the first update"); Assert.AreEqual(0, cVal, "Invalid cVal after the first update"); queue.Update(DateTime.UtcNow.AddSeconds(1f)); Assert.AreEqual(1, aVal, "Invalid aVal after the second update"); Assert.AreEqual(1, bVal, "Invalid bVal after the second update"); Assert.AreEqual(0, cVal, "Invalid cVal after the second update"); queue.Update(DateTime.UtcNow.AddSeconds(1.5f)); Assert.AreEqual(1, aVal, "Invalid aVal after the third update"); Assert.AreEqual(1, bVal, "Invalid bVal after the third update"); Assert.AreEqual(1, cVal, "Invalid cVal after the third update"); queue.MaxProcessedPerUpdate = 2; queue.Update(DateTime.UtcNow.AddSeconds(2f)); Assert.AreEqual(2, aVal, "Invalid aVal after the first update"); Assert.AreEqual(2, bVal, "Invalid bVal after the first update"); Assert.AreEqual(1, cVal, "Invalid cVal after the first update"); } [Test] public void TestEnumerator() { var queue = new TickedQueue(); var a = new TickedObject(Callback3, 0); a.TickLength = 1; queue.Add(a); Assert.IsTrue(queue.Items.Any(), "There should be items on the queue"); Assert.IsTrue(queue.Items.Contains(a), "Queue should contain the new item"); Assert.AreEqual(1, queue.Items.Count(), "Queue should contain only one item"); var b = new TickedObject(Callback3, 0); queue.Add(b); Assert.IsTrue(queue.Items.Contains(b), "Queue should contain the second item"); Assert.AreEqual(2, queue.Items.Count(), "Queue should contain two items"); queue.Remove(a); Assert.AreEqual(1, queue.Items.Count(), "Queue should contain only one item again"); Assert.IsFalse(queue.Items.Contains(a), "Queue should not contain the original item"); } private void CallbackSetTest1(object obj) { if (obj is int) { var i = (int) obj; if (i != test1 + 1) Assert.Fail("Callbacks called in the wrong order", obj); test1 = i; } else Assert.Fail("Junk sent back in callback", obj); } private void Callback2(object obj) { if (obj is int) { var i = (int) obj; switch (i) { case 0: ++aCalled; break; case 1: ++cCalled; break; case 2: ++bCalled; break; } } else Assert.Fail("Junk sent back in callback", obj); } private void Callback3(object obj) { test3 = 1; } } }
// 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.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Collections.Generic; using System.Diagnostics; namespace System.Linq.Expressions.Interpreter { internal interface IBoxableInstruction { Instruction BoxIfIndexMatches(int index); } internal abstract class LocalAccessInstruction : Instruction { internal readonly int _index; protected LocalAccessInstruction(int index) { _index = index; } public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects) { return cookie == null ? InstructionName + "(" + _index + ")" : InstructionName + "(" + cookie + ": " + _index + ")"; } } #region Load internal sealed class LoadLocalInstruction : LocalAccessInstruction, IBoxableInstruction { internal LoadLocalInstruction(int index) : base(index) { } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { frame.Data[frame.StackIndex++] = frame.Data[_index]; return +1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? InstructionList.LoadLocalBoxed(index) : null; } } internal sealed class LoadLocalBoxedInstruction : LocalAccessInstruction { internal LoadLocalBoxedInstruction(int index) : base(index) { } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { var box = (IStrongBox)frame.Data[_index]; frame.Data[frame.StackIndex++] = box.Value; return +1; } } internal sealed class LoadLocalFromClosureInstruction : LocalAccessInstruction { internal LoadLocalFromClosureInstruction(int index) : base(index) { } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { var box = frame.Closure[_index]; frame.Data[frame.StackIndex++] = box.Value; return +1; } } internal sealed class LoadLocalFromClosureBoxedInstruction : LocalAccessInstruction { internal LoadLocalFromClosureBoxedInstruction(int index) : base(index) { } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { var box = frame.Closure[_index]; frame.Data[frame.StackIndex++] = box; return +1; } } #endregion #region Store, Assign internal sealed class AssignLocalInstruction : LocalAccessInstruction, IBoxableInstruction { internal AssignLocalInstruction(int index) : base(index) { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { frame.Data[_index] = frame.Peek(); return +1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? InstructionList.AssignLocalBoxed(index) : null; } } internal sealed class StoreLocalInstruction : LocalAccessInstruction, IBoxableInstruction { internal StoreLocalInstruction(int index) : base(index) { } public override int ConsumedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { frame.Data[_index] = frame.Pop(); return +1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? InstructionList.StoreLocalBoxed(index) : null; } } internal sealed class AssignLocalBoxedInstruction : LocalAccessInstruction { internal AssignLocalBoxedInstruction(int index) : base(index) { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { var box = (IStrongBox)frame.Data[_index]; box.Value = frame.Peek(); return +1; } } internal sealed class StoreLocalBoxedInstruction : LocalAccessInstruction { internal StoreLocalBoxedInstruction(int index) : base(index) { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 0; } } public override int Run(InterpretedFrame frame) { var box = (IStrongBox)frame.Data[_index]; box.Value = frame.Data[--frame.StackIndex]; return +1; } } internal sealed class AssignLocalToClosureInstruction : LocalAccessInstruction { internal AssignLocalToClosureInstruction(int index) : base(index) { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { var box = frame.Closure[_index]; box.Value = frame.Peek(); return +1; } } internal sealed class ValueTypeCopyInstruction : Instruction { public static readonly ValueTypeCopyInstruction Instruction = new ValueTypeCopyInstruction(); public ValueTypeCopyInstruction() { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { object o = frame.Pop(); frame.Push(o == null ? o : RuntimeHelpers.GetObjectValue(o)); return +1; } } #endregion #region Initialize [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors")] internal abstract class InitializeLocalInstruction : LocalAccessInstruction { internal InitializeLocalInstruction(int index) : base(index) { } internal sealed class Reference : InitializeLocalInstruction, IBoxableInstruction { internal Reference(int index) : base(index) { } public override int Run(InterpretedFrame frame) { frame.Data[_index] = null; return 1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? InstructionList.InitImmutableRefBox(index) : null; } public override string InstructionName { get { return "InitRef"; } } } internal sealed class ImmutableValue : InitializeLocalInstruction, IBoxableInstruction { private readonly object _defaultValue; internal ImmutableValue(int index, object defaultValue) : base(index) { Debug.Assert(defaultValue != null); _defaultValue = defaultValue; } public override int Run(InterpretedFrame frame) { frame.Data[_index] = _defaultValue; return 1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? new ImmutableBox(index) : null; } public override string InstructionName { get { return "InitImmutableValue"; } } } internal sealed class ImmutableBox : InitializeLocalInstruction { // immutable value: internal ImmutableBox(int index) : base(index) { } public override int Run(InterpretedFrame frame) { frame.Data[_index] = new ExplicitBox(); return 1; } public override string InstructionName { get { return "InitImmutableBox"; } } } internal sealed class ImmutableRefValue : InitializeLocalInstruction, IBoxableInstruction { private readonly Type _type; internal ImmutableRefValue(int index, Type type) : base(index) { _type = type; } public override int Run(InterpretedFrame frame) { frame.Data[_index] = null; return 1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? new ImmutableRefBox(index) : null; } public override string InstructionName { get { return "InitImmutableValue"; } } } internal sealed class ImmutableRefBox : InitializeLocalInstruction { // immutable value: internal ImmutableRefBox(int index) : base(index) { } public override int Run(InterpretedFrame frame) { frame.Data[_index] = new ExplicitBox(); return 1; } public override string InstructionName { get { return "InitImmutableBox"; } } } internal sealed class ParameterBox : InitializeLocalInstruction { public ParameterBox(int index) : base(index) { } public override int Run(InterpretedFrame frame) { frame.Data[_index] = new ExplicitBox(frame.Data[_index]); return 1; } } internal sealed class Parameter : InitializeLocalInstruction, IBoxableInstruction { internal Parameter(int index, Type parameterType) : base(index) { } public override int Run(InterpretedFrame frame) { // nop return 1; } public Instruction BoxIfIndexMatches(int index) { if (index == _index) { return InstructionList.ParameterBox(index); } return null; } public override string InstructionName { get { return "InitParameter"; } } } internal sealed class MutableValue : InitializeLocalInstruction, IBoxableInstruction { private readonly Type _type; internal MutableValue(int index, Type type) : base(index) { _type = type; } public override int Run(InterpretedFrame frame) { try { frame.Data[_index] = Activator.CreateInstance(_type); } catch (TargetInvocationException e) { ExceptionHelpers.UpdateForRethrow(e.InnerException); throw e.InnerException; } return 1; } public Instruction BoxIfIndexMatches(int index) { return (index == _index) ? new MutableBox(index) : null; } public override string InstructionName { get { return "InitMutableValue"; } } } internal sealed class MutableBox : InitializeLocalInstruction { internal MutableBox(int index) : base(index) { } public override int Run(InterpretedFrame frame) { frame.Data[_index] = new ExplicitBox(); return 1; } public override string InstructionName { get { return "InitMutableBox"; } } } } #endregion #region RuntimeVariables internal sealed class RuntimeVariablesInstruction : Instruction { private readonly int _count; public RuntimeVariablesInstruction(int count) { _count = count; } public override int ProducedStack { get { return 1; } } public override int ConsumedStack { get { return _count; } } public override int Run(InterpretedFrame frame) { var ret = new IStrongBox[_count]; for (int i = ret.Length - 1; i >= 0; i--) { ret[i] = (IStrongBox)frame.Pop(); } frame.Push(RuntimeVariables.Create(ret)); return +1; } public override string ToString() { return "GetRuntimeVariables()"; } } #endregion }
using System.Collections; using Roar.Components; using UnityEngine; namespace Roar.implementation.Components { public class Inventory : IInventory { protected DataStore dataStore; protected IWebAPI.IItemsActions itemActions; protected ILogger logger; public Inventory (IWebAPI.IItemsActions itemActions, DataStore dataStore, ILogger logger) { this.itemActions = itemActions; this.dataStore = dataStore; this.logger = logger; RoarManager.roarServerItemAddEvent += this.OnServerItemAdd; } public bool HasDataFromServer { get { return dataStore.inventory.HasDataFromServer; } } public void Fetch (Roar.Callback callback) { dataStore.inventory.Fetch (callback); } public ArrayList List () { return List (null); } public ArrayList List (Roar.Callback callback) { if (callback != null) callback (new Roar.CallbackInfo<object> (dataStore.inventory.List ())); return dataStore.inventory.List (); } public void Activate (string id, Roar.Callback callback) { var item = dataStore.inventory.Get (id); if (item == null) { logger.DebugLog ("[roar] -- Failed: no record with id: " + id); return; } Hashtable args = new Hashtable (); args ["item_id"] = id; itemActions.equip (args, new ActivateCallback (callback, this, id)); } class ActivateCallback : SimpleRequestCallback<IXMLNode> { Inventory inventory; string id; public ActivateCallback (Roar.Callback in_cb, Inventory in_inventory, string in_id) : base(in_cb) { inventory = in_inventory; id = in_id; } public override object OnSuccess (CallbackInfo<IXMLNode> info) { var item = inventory.dataStore.inventory.Get (id); item ["equipped"] = true; Hashtable returnObj = new Hashtable (); returnObj ["id"] = id; returnObj ["ikey"] = item ["ikey"]; returnObj ["label"] = item ["label"]; RoarManager.OnGoodActivated (new RoarManager.GoodInfo (id, item ["ikey"] as string, item ["label"] as string)); return returnObj; } } public void Deactivate (string id, Roar.Callback callback) { var item = dataStore.inventory.Get (id as string); if (item == null) { logger.DebugLog ("[roar] -- Failed: no record with id: " + id); return; } Hashtable args = new Hashtable (); args ["item_id"] = id; itemActions.unequip (args, new DeactivateCallback (callback, this, id)); } class DeactivateCallback : SimpleRequestCallback<IXMLNode> { Inventory inventory; string id; public DeactivateCallback (Roar.Callback in_cb, Inventory in_inventory, string in_id) : base(in_cb) { inventory = in_inventory; id = in_id; } public override object OnSuccess (CallbackInfo<IXMLNode> info) { var item = inventory.dataStore.inventory.Get (id); item ["equipped"] = false; Hashtable returnObj = new Hashtable (); returnObj ["id"] = id; returnObj ["ikey"] = item ["ikey"]; returnObj ["label"] = item ["label"]; RoarManager.OnGoodDeactivated (new RoarManager.GoodInfo (id, item ["ikey"] as string, item ["label"] as string)); return returnObj; } } // `has( key, num )` boolean checks whether user has object `key` // and optionally checks for a `num` number of `keys` *(default 1)* public bool Has (string ikey) { return Has (ikey, 1, null); } public bool Has (string ikey, int num, Roar.Callback callback) { if (callback != null) callback (new Roar.CallbackInfo<object> (dataStore.inventory.Has (ikey, num))); return dataStore.inventory.Has (ikey, num); } // `quantity( key )` returns the number of `key` objects held by user public int Quantity (string ikey) { return Quantity (ikey, null); } public int Quantity (string ikey, Roar.Callback callback) { if (callback != null) callback (new Roar.CallbackInfo<object> (dataStore.inventory.Quantity (ikey))); return dataStore.inventory.Quantity (ikey); } // `sell(id)` performs a sell on the item `id` specified public void Sell (string id, Roar.Callback callback) { var item = dataStore.inventory.Get (id as string); if (item == null) { logger.DebugLog ("[roar] -- Failed: no record with id: " + id); return; } // Ensure item is sellable first if ((bool)item ["sellable"] != true) { var error = item ["ikey"] + ": Good is not sellable"; logger.DebugLog ("[roar] -- " + error); if (callback != null) callback (new Roar.CallbackInfo<object> (null, IWebAPI.DISALLOWED, error)); return; } Hashtable args = new Hashtable (); args ["item_id"] = id; itemActions.sell (args, new SellCallback (callback, this, id)); } class SellCallback : SimpleRequestCallback<IXMLNode> { Inventory inventory; string id; public SellCallback (Roar.Callback in_cb, Inventory in_inventory, string in_id) : base(in_cb) { inventory = in_inventory; id = in_id; } public override object OnSuccess (CallbackInfo<IXMLNode> info) { var item = inventory.dataStore.inventory.Get (id); Hashtable returnObj = new Hashtable (); returnObj ["id"] = id; returnObj ["ikey"] = item ["ikey"]; returnObj ["label"] = item ["label"]; inventory.dataStore.inventory.Unset (id); RoarManager.OnGoodSold (new RoarManager.GoodInfo (id, item ["ikey"] as string, item ["label"] as string)); return returnObj; } } // `use(id)` consumes/uses the item `id` public void Use (string id, Roar.Callback callback) { var item = dataStore.inventory.Get (id as string); if (item == null) { logger.DebugLog ("[roar] -- Failed: no record with id: " + id); return; } // GH#152: Ensure item is consumable first logger.DebugLog (Roar.Json.ObjectToJSON (item)); if ((bool)item ["consumable"] != true) { var error = item ["ikey"] + ": Good is not consumable"; logger.DebugLog ("[roar] -- " + error); if (callback != null) callback (new Roar.CallbackInfo<object> (null, IWebAPI.DISALLOWED, error)); return; } Hashtable args = new Hashtable (); args ["item_id"] = id; itemActions.use (args, new UseCallback (callback, this, id)); } class UseCallback : SimpleRequestCallback<IXMLNode> { Inventory inventory; string id; public UseCallback (Roar.Callback in_cb, Inventory in_inventory, string in_id) : base(in_cb) { inventory = in_inventory; id = in_id; } public override object OnSuccess (CallbackInfo<IXMLNode> info) { var item = inventory.dataStore.inventory.Get (id); Hashtable returnObj = new Hashtable (); returnObj ["id"] = id; returnObj ["ikey"] = item ["ikey"]; returnObj ["label"] = item ["label"]; inventory.dataStore.inventory.Unset (id); RoarManager.OnGoodUsed (new RoarManager.GoodInfo (id, item ["ikey"] as string, item ["label"] as string)); return returnObj; } } // `remove(id)` for now is simply an *alias* to sell public void Remove (string id, Roar.Callback callback) { Sell (id, callback); } // Returns raw data object for inventory public Hashtable GetGood (string id) { return GetGood (id, null); } public Hashtable GetGood (string id, Roar.Callback callback) { if (callback != null) callback (new Roar.CallbackInfo<object> (dataStore.inventory.Get (id))); return dataStore.inventory.Get (id); } protected void OnServerItemAdd (IXMLNode d) { // Only add to inventory if it Has previously been intialised if (HasDataFromServer) { var keysToAdd = new ArrayList (); var id = d.GetAttribute ("item_id"); var ikey = d.GetAttribute ("item_ikey"); keysToAdd.Add (ikey); if (!dataStore.cache.Has (ikey)) { dataStore.cache.AddToCache (keysToAdd, h => AddToInventory (ikey, id)); } else AddToInventory (ikey, id); } } protected void AddToInventory (string ikey, string id) { // Prepare the item to manually add to Inventory Hashtable item = new Hashtable (); item [id] = DataModel.Clone (dataStore.cache.Get (ikey)); // Also set the internal reference id (used by templates) var idspec = item [id] as Hashtable; idspec ["id"] = id; // Manually add to inventory dataStore.inventory.Set (item); } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace CorporateEvents.SharePointWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
using System; using System.Threading.Tasks; using System.Web; using Avalonia; using Avalonia.Controls; using DHT.Desktop.Dialogs.Message; using DHT.Desktop.Discord; using DHT.Desktop.Main.Controls; using DHT.Server.Database; using DHT.Server.Service; using DHT.Utils.Logging; using DHT.Utils.Models; using static DHT.Desktop.Program; namespace DHT.Desktop.Main.Pages { sealed class TrackingPageModel : BaseModel, IDisposable { private static readonly Log Log = Log.ForType<TrackingPageModel>(); internal static string ServerPort { get; set; } = ServerUtils.FindAvailablePort(50000, 60000).ToString(); internal static string ServerToken { get; set; } = ServerUtils.GenerateRandomToken(20); private string inputPort = ServerPort; public string InputPort { get => inputPort; set { Change(ref inputPort, value); OnPropertyChanged(nameof(HasMadeChanges)); } } private string inputToken = ServerToken; public string InputToken { get => inputToken; set { Change(ref inputToken, value); OnPropertyChanged(nameof(HasMadeChanges)); } } public bool HasMadeChanges => ServerPort != InputPort || ServerToken != InputToken; private bool isToggleTrackingButtonEnabled = true; public bool IsToggleButtonEnabled { get => isToggleTrackingButtonEnabled; set => Change(ref isToggleTrackingButtonEnabled, value); } public string ToggleTrackingButtonText => ServerLauncher.IsRunning ? "Pause Tracking" : "Resume Tracking"; private bool areDevToolsEnabled; private bool AreDevToolsEnabled { get => areDevToolsEnabled; set { Change(ref areDevToolsEnabled, value); OnPropertyChanged(nameof(ToggleAppDevToolsButtonText)); } } public bool IsToggleAppDevToolsButtonEnabled { get; private set; } = true; public string ToggleAppDevToolsButtonText { get { if (!IsToggleAppDevToolsButtonEnabled) { return "Unavailable"; } return AreDevToolsEnabled ? "Disable Ctrl+Shift+I" : "Enable Ctrl+Shift+I"; } } public event EventHandler<StatusBarModel.Status>? ServerStatusChanged; private readonly Window window; private readonly IDatabaseFile db; [Obsolete("Designer")] public TrackingPageModel() : this(null!, DummyDatabaseFile.Instance) {} public TrackingPageModel(Window window, IDatabaseFile db) { this.window = window; this.db = db; } public async Task Initialize() { ServerLauncher.ServerStatusChanged += ServerLauncherOnServerStatusChanged; ServerLauncher.ServerManagementExceptionCaught += ServerLauncherOnServerManagementExceptionCaught; if (int.TryParse(ServerPort, out int port)) { string token = ServerToken; ServerLauncher.Relaunch(port, token, db); } bool? devToolsEnabled = await DiscordAppSettings.AreDevToolsEnabled(); if (devToolsEnabled.HasValue) { AreDevToolsEnabled = devToolsEnabled.Value; } else { IsToggleAppDevToolsButtonEnabled = false; OnPropertyChanged(nameof(IsToggleAppDevToolsButtonEnabled)); } } public void Dispose() { ServerLauncher.ServerManagementExceptionCaught -= ServerLauncherOnServerManagementExceptionCaught; ServerLauncher.ServerStatusChanged -= ServerLauncherOnServerStatusChanged; ServerLauncher.Stop(); } private void ServerLauncherOnServerStatusChanged(object? sender, EventArgs e) { ServerStatusChanged?.Invoke(this, ServerLauncher.IsRunning ? StatusBarModel.Status.Ready : StatusBarModel.Status.Stopped); OnPropertyChanged(nameof(ToggleTrackingButtonText)); IsToggleButtonEnabled = true; } private async void ServerLauncherOnServerManagementExceptionCaught(object? sender, Exception ex) { Log.Error(ex); await Dialog.ShowOk(window, "Server Error", ex.Message); } private async Task<bool> StartServer() { if (!int.TryParse(InputPort, out int port) || port is < 0 or > 65535) { await Dialog.ShowOk(window, "Invalid Port", "Port must be a number between 0 and 65535."); return false; } IsToggleButtonEnabled = false; ServerStatusChanged?.Invoke(this, StatusBarModel.Status.Starting); ServerLauncher.Relaunch(port, InputToken, db); return true; } private void StopServer() { IsToggleButtonEnabled = false; ServerStatusChanged?.Invoke(this, StatusBarModel.Status.Stopping); ServerLauncher.Stop(); } public async Task<bool> OnClickToggleTrackingButton() { if (ServerLauncher.IsRunning) { StopServer(); return true; } else { return await StartServer(); } } public async Task<bool> OnClickCopyTrackingScript() { string bootstrap = await Resources.ReadTextAsync("Tracker/bootstrap.js"); string script = bootstrap.Replace("= 0; /*[PORT]*/", "= " + ServerPort + ";") .Replace("/*[TOKEN]*/", HttpUtility.JavaScriptStringEncode(ServerToken)) .Replace("/*[IMPORTS]*/", await Resources.ReadJoinedAsync("Tracker/scripts/", '\n')) .Replace("/*[CSS-CONTROLLER]*/", await Resources.ReadTextAsync("Tracker/styles/controller.css")) .Replace("/*[CSS-SETTINGS]*/", await Resources.ReadTextAsync("Tracker/styles/settings.css")); var clipboard = Application.Current?.Clipboard; if (clipboard == null) { await Dialog.ShowOk(window, "Copy Tracking Script", "Clipboard is not available on this system."); return false; } try { await clipboard.SetTextAsync(script); return true; } catch { await Dialog.ShowOk(window, "Copy Tracking Script", "An error occurred while copying to clipboard."); return false; } } public void OnClickRandomizeToken() { InputToken = ServerUtils.GenerateRandomToken(20); } public async void OnClickApplyChanges() { if (await StartServer()) { ServerPort = InputPort; ServerToken = InputToken; OnPropertyChanged(nameof(HasMadeChanges)); } } public void OnClickCancelChanges() { InputPort = ServerPort; InputToken = ServerToken; } public async void OnClickToggleAppDevTools() { const string DialogTitle = "Discord App Settings File"; bool oldState = AreDevToolsEnabled; bool newState = !oldState; switch (await DiscordAppSettings.ConfigureDevTools(newState)) { case SettingsJsonResult.Success: AreDevToolsEnabled = newState; await Dialog.ShowOk(window, DialogTitle, "Ctrl+Shift+I was " + (newState ? "enabled." : "disabled.") + " Restart the Discord app for the change to take effect."); break; case SettingsJsonResult.AlreadySet: await Dialog.ShowOk(window, DialogTitle, "Ctrl+Shift+I is already " + (newState ? "enabled." : "disabled.")); AreDevToolsEnabled = newState; break; case SettingsJsonResult.FileNotFound: await Dialog.ShowOk(window, DialogTitle, "Cannot find the settings file:\n" + DiscordAppSettings.JsonFilePath); break; case SettingsJsonResult.ReadError: await Dialog.ShowOk(window, DialogTitle, "Cannot read the settings file:\n" + DiscordAppSettings.JsonFilePath); break; case SettingsJsonResult.InvalidJson: await Dialog.ShowOk(window, DialogTitle, "Unknown format of the settings file:\n" + DiscordAppSettings.JsonFilePath); break; case SettingsJsonResult.WriteError: await Dialog.ShowOk(window, DialogTitle, "Cannot save the settings file:\n" + DiscordAppSettings.JsonFilePath); break; default: throw new ArgumentOutOfRangeException(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Diagnostics; using System.Runtime.Serialization; //For SR using System.Globalization; using System.Security; namespace System.Text { internal class Base64Encoding : Encoding { private static byte[] s_char2val = new byte[128] { /* 0-15 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* 16-31 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* 32-47 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 62, 0xFF, 0xFF, 0xFF, 63, /* 48-63 */ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0xFF, 0xFF, 0xFF, 64, 0xFF, 0xFF, /* 64-79 */ 0xFF, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 80-95 */ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* 96-111 */ 0xFF, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 112-127 */ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; private static string s_val2char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; private static byte[] s_val2byte = new byte[] { (byte)'A',(byte)'B',(byte)'C',(byte)'D',(byte)'E',(byte)'F',(byte)'G',(byte)'H',(byte)'I',(byte)'J',(byte)'K',(byte)'L',(byte)'M',(byte)'N',(byte)'O',(byte)'P', (byte)'Q',(byte)'R',(byte)'S',(byte)'T',(byte)'U',(byte)'V',(byte)'W',(byte)'X',(byte)'Y',(byte)'Z',(byte)'a',(byte)'b',(byte)'c',(byte)'d',(byte)'e',(byte)'f', (byte)'g',(byte)'h',(byte)'i',(byte)'j',(byte)'k',(byte)'l',(byte)'m',(byte)'n',(byte)'o',(byte)'p',(byte)'q',(byte)'r',(byte)'s',(byte)'t',(byte)'u',(byte)'v', (byte)'w',(byte)'x',(byte)'y',(byte)'z',(byte)'0',(byte)'1',(byte)'2',(byte)'3',(byte)'4',(byte)'5',(byte)'6',(byte)'7',(byte)'8',(byte)'9',(byte)'+',(byte)'/' }; public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.ValueMustBeNonNegative))); if ((charCount % 4) != 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString(NumberFormatInfo.CurrentInfo)))); return charCount / 4 * 3; } private bool IsValidLeadBytes(int v1, int v2, int v3, int v4) { // First two chars of a four char base64 sequence can't be ==, and must be valid return ((v1 | v2) < 64) && ((v3 | v4) != 0xFF); } private bool IsValidTailBytes(int v3, int v4) { // If the third char is = then the fourth char must be = return !(v3 == 64 && v4 != 64); } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public override int GetByteCount(char[] chars, int index, int count) { if (chars == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (index < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.ValueMustBeNonNegative))); if (index > chars.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.OffsetExceedsBufferSize, chars.Length))); if (count < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative))); if (count > chars.Length - index) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - index))); if (count == 0) return 0; if ((count % 4) != 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, count.ToString(NumberFormatInfo.CurrentInfo)))); fixed (byte* _char2val = s_char2val) { fixed (char* _chars = &chars[index]) { int totalCount = 0; char* pch = _chars; char* pchMax = _chars + count; while (pch < pchMax) { DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, ""); char pch0 = pch[0]; char pch1 = pch[1]; char pch2 = pch[2]; char pch3 = pch[3]; if ((pch0 | pch1 | pch2 | pch3) >= 128) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), index + (int)(pch - _chars)))); // xx765432 xx107654 xx321076 xx543210 // 76543210 76543210 76543210 int v1 = _char2val[pch0]; int v2 = _char2val[pch1]; int v3 = _char2val[pch2]; int v4 = _char2val[pch3]; if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), index + (int)(pch - _chars)))); int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1)); totalCount += byteCount; pch += 4; } return totalCount; } } } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (charIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.ValueMustBeNonNegative))); if (charIndex > chars.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length))); if (charCount < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.ValueMustBeNonNegative))); if (charCount > chars.Length - charIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex))); if (bytes == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes))); if (byteIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.ValueMustBeNonNegative))); if (byteIndex > bytes.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length))); if (charCount == 0) return 0; if ((charCount % 4) != 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString(NumberFormatInfo.CurrentInfo)))); fixed (byte* _char2val = s_char2val) { fixed (char* _chars = &chars[charIndex]) { fixed (byte* _bytes = &bytes[byteIndex]) { char* pch = _chars; char* pchMax = _chars + charCount; byte* pb = _bytes; byte* pbMax = _bytes + bytes.Length - byteIndex; while (pch < pchMax) { DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, ""); char pch0 = pch[0]; char pch1 = pch[1]; char pch2 = pch[2]; char pch3 = pch[3]; if ((pch0 | pch1 | pch2 | pch3) >= 128) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), charIndex + (int)(pch - _chars)))); // xx765432 xx107654 xx321076 xx543210 // 76543210 76543210 76543210 int v1 = _char2val[pch0]; int v2 = _char2val[pch1]; int v3 = _char2val[pch2]; int v4 = _char2val[pch3]; if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), charIndex + (int)(pch - _chars)))); int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1)); if (pb + byteCount > pbMax) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), nameof(bytes))); pb[0] = (byte)((v1 << 2) | ((v2 >> 4) & 0x03)); if (byteCount > 1) { pb[1] = (byte)((v2 << 4) | ((v3 >> 2) & 0x0F)); if (byteCount > 2) { pb[2] = (byte)((v3 << 6) | ((v4 >> 0) & 0x3F)); } } pb += byteCount; pch += 4; } return (int)(pb - _bytes); } } } } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public virtual int GetBytes(byte[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (charIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.ValueMustBeNonNegative))); if (charIndex > chars.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length))); if (charCount < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.ValueMustBeNonNegative))); if (charCount > chars.Length - charIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex))); if (bytes == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes))); if (byteIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.ValueMustBeNonNegative))); if (byteIndex > bytes.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length))); if (charCount == 0) return 0; if ((charCount % 4) != 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString(NumberFormatInfo.CurrentInfo)))); fixed (byte* _char2val = s_char2val) { fixed (byte* _chars = &chars[charIndex]) { fixed (byte* _bytes = &bytes[byteIndex]) { byte* pch = _chars; byte* pchMax = _chars + charCount; byte* pb = _bytes; byte* pbMax = _bytes + bytes.Length - byteIndex; while (pch < pchMax) { DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, ""); byte pch0 = pch[0]; byte pch1 = pch[1]; byte pch2 = pch[2]; byte pch3 = pch[3]; if ((pch0 | pch1 | pch2 | pch3) >= 128) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, "?", charIndex + (int)(pch - _chars)))); // xx765432 xx107654 xx321076 xx543210 // 76543210 76543210 76543210 int v1 = _char2val[pch0]; int v2 = _char2val[pch1]; int v3 = _char2val[pch2]; int v4 = _char2val[pch3]; if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, "?", charIndex + (int)(pch - _chars)))); int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1)); if (pb + byteCount > pbMax) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), nameof(bytes))); pb[0] = (byte)((v1 << 2) | ((v2 >> 4) & 0x03)); if (byteCount > 1) { pb[1] = (byte)((v2 << 4) | ((v3 >> 2) & 0x0F)); if (byteCount > 2) { pb[2] = (byte)((v3 << 6) | ((v4 >> 0) & 0x3F)); } } pb += byteCount; pch += 4; } return (int)(pb - _bytes); } } } } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0 || byteCount > int.MaxValue / 4 * 3 - 2) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.ValueMustBeInRange, 0, int.MaxValue / 4 * 3 - 2))); return ((byteCount + 2) / 3) * 4; } public override int GetCharCount(byte[] bytes, int index, int count) { return GetMaxCharCount(count); } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (bytes == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes))); if (byteIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.ValueMustBeNonNegative))); if (byteIndex > bytes.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length))); if (byteCount < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.ValueMustBeNonNegative))); if (byteCount > bytes.Length - byteIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex))); int charCount = GetCharCount(bytes, byteIndex, byteCount); if (chars == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (charIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.ValueMustBeNonNegative))); if (charIndex > chars.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length))); if (charCount < 0 || charCount > chars.Length - charIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), nameof(chars))); // We've computed exactly how many chars there are and verified that // there's enough space in the char buffer, so we can proceed without // checking the charCount. if (byteCount > 0) { fixed (char* _val2char = s_val2char) { fixed (byte* _bytes = &bytes[byteIndex]) { fixed (char* _chars = &chars[charIndex]) { byte* pb = _bytes; byte* pbMax = pb + byteCount - 3; char* pch = _chars; // Convert chunks of 3 bytes to 4 chars while (pb <= pbMax) { // 76543210 76543210 76543210 // xx765432 xx107654 xx321076 xx543210 // Inspect the code carefully before you change this pch[0] = _val2char[(pb[0] >> 2)]; pch[1] = _val2char[((pb[0] & 0x03) << 4) | (pb[1] >> 4)]; pch[2] = _val2char[((pb[1] & 0x0F) << 2) | (pb[2] >> 6)]; pch[3] = _val2char[pb[2] & 0x3F]; pb += 3; pch += 4; } // Handle 1 or 2 trailing bytes if (pb - pbMax == 2) { // 1 trailing byte // 76543210 xxxxxxxx xxxxxxxx // xx765432 xx10xxxx xxxxxxxx xxxxxxxx pch[0] = _val2char[(pb[0] >> 2)]; pch[1] = _val2char[((pb[0] & 0x03) << 4)]; pch[2] = '='; pch[3] = '='; } else if (pb - pbMax == 1) { // 2 trailing bytes // 76543210 76543210 xxxxxxxx // xx765432 xx107654 xx3210xx xxxxxxxx pch[0] = _val2char[(pb[0] >> 2)]; pch[1] = _val2char[((pb[0] & 0x03) << 4) | (pb[1] >> 4)]; pch[2] = _val2char[((pb[1] & 0x0F) << 2)]; pch[3] = '='; } else { // 0 trailing bytes DiagnosticUtility.DebugAssert(pb - pbMax == 3, ""); } } } } } return charCount; } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public int GetChars(byte[] bytes, int byteIndex, int byteCount, byte[] chars, int charIndex) { if (bytes == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes))); if (byteIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.ValueMustBeNonNegative))); if (byteIndex > bytes.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length))); if (byteCount < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.ValueMustBeNonNegative))); if (byteCount > bytes.Length - byteIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex))); int charCount = GetCharCount(bytes, byteIndex, byteCount); if (chars == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); if (charIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.ValueMustBeNonNegative))); if (charIndex > chars.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length))); if (charCount < 0 || charCount > chars.Length - charIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), nameof(chars))); // We've computed exactly how many chars there are and verified that // there's enough space in the char buffer, so we can proceed without // checking the charCount. if (byteCount > 0) { fixed (byte* _val2byte = s_val2byte) { fixed (byte* _bytes = &bytes[byteIndex]) { fixed (byte* _chars = &chars[charIndex]) { byte* pb = _bytes; byte* pbMax = pb + byteCount - 3; byte* pch = _chars; // Convert chunks of 3 bytes to 4 chars while (pb <= pbMax) { // 76543210 76543210 76543210 // xx765432 xx107654 xx321076 xx543210 // Inspect the code carefully before you change this pch[0] = _val2byte[(pb[0] >> 2)]; pch[1] = _val2byte[((pb[0] & 0x03) << 4) | (pb[1] >> 4)]; pch[2] = _val2byte[((pb[1] & 0x0F) << 2) | (pb[2] >> 6)]; pch[3] = _val2byte[pb[2] & 0x3F]; pb += 3; pch += 4; } // Handle 1 or 2 trailing bytes if (pb - pbMax == 2) { // 1 trailing byte // 76543210 xxxxxxxx xxxxxxxx // xx765432 xx10xxxx xxxxxxxx xxxxxxxx pch[0] = _val2byte[(pb[0] >> 2)]; pch[1] = _val2byte[((pb[0] & 0x03) << 4)]; pch[2] = (byte)'='; pch[3] = (byte)'='; } else if (pb - pbMax == 1) { // 2 trailing bytes // 76543210 76543210 xxxxxxxx // xx765432 xx107654 xx3210xx xxxxxxxx pch[0] = _val2byte[(pb[0] >> 2)]; pch[1] = _val2byte[((pb[0] & 0x03) << 4) | (pb[1] >> 4)]; pch[2] = _val2byte[((pb[1] & 0x0F) << 2)]; pch[3] = (byte)'='; } else { // 0 trailing bytes DiagnosticUtility.DebugAssert(pb - pbMax == 3, ""); } } } } } return charCount; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PlotView.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // <summary> // Provides a view that can show a <see cref="PlotModel" />. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace OxyPlot.Xamarin.iOS { using Foundation; using UIKit; using OxyPlot; /// <summary> /// Provides a view that can show a <see cref="PlotModel" />. /// </summary> [Register("PlotView")] public class PlotView : UIView, IPlotView { /// <summary> /// The current plot model. /// </summary> private PlotModel model; /// <summary> /// The default plot controller. /// </summary> private IPlotController defaultController; /// <summary> /// Initializes a new instance of the <see cref="OxyPlot.Xamarin.iOS.PlotView"/> class. /// </summary> public PlotView() { this.Initialize (); } /// <summary> /// Initializes a new instance of the <see cref="OxyPlot.Xamarin.iOS.PlotView"/> class. /// </summary> /// <param name="frame">The initial frame.</param> public PlotView(CoreGraphics.CGRect frame) : base(frame) { this.Initialize (); } /// <summary> /// Initializes a new instance of the <see cref="OxyPlot.Xamarin.iOS.PlotView"/> class. /// </summary> /// <param name="coder">Coder.</param> [Export ("initWithCoder:")] public PlotView(NSCoder coder) : base (coder) { this.Initialize (); } /// <summary> /// Uses the new layout. /// </summary> /// <returns><c>true</c>, if new layout was used, <c>false</c> otherwise.</returns> [Export ("requiresConstraintBasedLayout")] bool UseNewLayout () { return true; } /// <summary> /// Initialize the view. /// </summary> private void Initialize() { this.UserInteractionEnabled = true; this.MultipleTouchEnabled = true; this.BackgroundColor = UIColor.White; this.KeepAspectRatioWhenPinching = true; } /// <summary> /// Gets or sets the <see cref="PlotModel"/> to show in the view. /// </summary> /// <value>The <see cref="PlotModel"/>.</value> public PlotModel Model { get { return this.model; } set { if (this.model != value) { this.model = value; this.InvalidatePlot(); } } } /// <summary> /// Gets or sets the <see cref="IPlotController"/> that handles input events. /// </summary> /// <value>The <see cref="IPlotController"/>.</value> public IPlotController Controller { get; set; } /// <summary> /// Gets the actual model in the view. /// </summary> /// <value> /// The actual model. /// </value> Model IView.ActualModel { get { return this.Model; } } /// <summary> /// Gets the actual <see cref="PlotModel"/> to show. /// </summary> /// <value>The actual model.</value> public PlotModel ActualModel { get { return this.Model; } } /// <summary> /// Gets the actual controller. /// </summary> /// <value> /// The actual <see cref="IController" />. /// </value> IController IView.ActualController { get { return this.ActualController; } } /// <summary> /// Gets the coordinates of the client area of the view. /// </summary> public OxyRect ClientArea { get { // TODO return new OxyRect(0, 0, 100, 100); } } /// <summary> /// Gets the actual <see cref="IPlotController"/>. /// </summary> /// <value>The actual plot controller.</value> public IPlotController ActualController { get { return this.Controller ?? (this.defaultController ?? (this.defaultController = new PlotController())); } } /// <summary> /// Gets or sets a value indicating whether this <see cref="OxyPlot.Xamarin.iOS.PlotView"/> keeps the aspect ratio when pinching. /// </summary> /// <value><c>true</c> if keep aspect ratio when pinching; otherwise, <c>false</c>.</value> public bool KeepAspectRatioWhenPinching { get; set; } /// <summary> /// Hides the tracker. /// </summary> public void HideTracker() { } /// <summary> /// Hides the zoom rectangle. /// </summary> public void HideZoomRectangle() { } /// <summary> /// Invalidates the plot (not blocking the UI thread) /// </summary> /// <param name="updateData">If set to <c>true</c> update data.</param> public void InvalidatePlot(bool updateData = true) { var actualModel = this.model; if (actualModel != null) { // TODO: update the model on a background thread ((IPlotModel)actualModel).Update(updateData); } if (actualModel != null && !actualModel.Background.IsUndefined()) { this.BackgroundColor = actualModel.Background.ToUIColor(); } else { // Use white as default background color this.BackgroundColor = UIColor.White; } this.SetNeedsDisplay(); } /// <summary> /// Sets the cursor type. /// </summary> /// <param name="cursorType">The cursor type.</param> public void SetCursorType(CursorType cursorType) { // No cursor on iOS } /// <summary> /// Shows the tracker. /// </summary> /// <param name="trackerHitResult">The tracker data.</param> public void ShowTracker(TrackerHitResult trackerHitResult) { // TODO: how to show a tracker on iOS // the tracker must be moved away from the finger... } /// <summary> /// Shows the zoom rectangle. /// </summary> /// <param name="rectangle">The rectangle.</param> public void ShowZoomRectangle(OxyRect rectangle) { // Not needed - better with pinch events on iOS? } /// <summary> /// Stores text on the clipboard. /// </summary> /// <param name="text">The text.</param> public void SetClipboardText(string text) { UIPasteboard.General.SetValue(new NSString(text), "public.utf8-plain-text"); } /// <summary> /// Draws the content of the view. /// </summary> /// <param name="rect">The rectangle to draw.</param> public override void Draw(CoreGraphics.CGRect rect) { if (this.model != null) { using (var renderer = new CoreGraphicsRenderContext(UIGraphics.GetCurrentContext())) { ((IPlotModel)this.model).Render(renderer, rect.Width, rect.Height); } } } /// <summary> /// Method invoked when a motion (a shake) has started. /// </summary> /// <param name="motion">The motion subtype.</param> /// <param name="evt">The event arguments.</param> public override void MotionBegan(UIEventSubtype motion, UIEvent evt) { base.MotionBegan(motion, evt); if (motion == UIEventSubtype.MotionShake) { this.ActualController.HandleGesture(this, new OxyShakeGesture(), new OxyKeyEventArgs()); } } /// <summary> /// Called when a touch gesture begins. /// </summary> /// <param name="touches">The touches.</param> /// <param name="evt">The event arguments.</param> public override void TouchesBegan(NSSet touches, UIEvent evt) { base.TouchesBegan(touches, evt); var touch = touches.AnyObject as UITouch; if (touch != null) { this.ActualController.HandleTouchStarted(this, touch.ToTouchEventArgs(this)); } } /// <summary> /// Called when a touch gesture is moving. /// </summary> /// <param name="touches">The touches.</param> /// <param name="evt">The event arguments.</param> public override void TouchesMoved(NSSet touches, UIEvent evt) { // it seems to be easier to handle touch events here than using UIPanGesturRecognizer and UIPinchGestureRecognizer base.TouchesMoved(touches, evt); // convert the touch points to an array var ta = touches.ToArray<UITouch>(); if (ta.Length > 0) { // get current and previous location of the first touch point var t1 = ta[0]; var l1 = t1.LocationInView(this).ToScreenPoint(); var pl1 = t1.PreviousLocationInView(this).ToScreenPoint(); var l = l1; var t = l1 - pl1; var s = new ScreenVector(1, 1); if (ta.Length > 1) { // get current and previous location of the second touch point var t2 = ta[1]; var l2 = t2.LocationInView(this).ToScreenPoint(); var pl2 = t2.PreviousLocationInView(this).ToScreenPoint(); var d = l1 - l2; var pd = pl1 - pl2; if (!this.KeepAspectRatioWhenPinching) { var scalex = System.Math.Abs(pd.X) > 0 ? System.Math.Abs(d.X / pd.X) : 1; var scaley = System.Math.Abs(pd.Y) > 0 ? System.Math.Abs(d.Y / pd.Y) : 1; s = new ScreenVector(scalex, scaley); } else { var scale = pd.Length > 0 ? d.Length / pd.Length : 1; s = new ScreenVector(scale, scale); } } var e = new OxyTouchEventArgs { Position = l, DeltaTranslation = t, DeltaScale = s }; this.ActualController.HandleTouchDelta(this, e); } } /// <summary> /// Called when a touch gesture ends. /// </summary> /// <param name="touches">The touches.</param> /// <param name="evt">The event arguments.</param> public override void TouchesEnded(NSSet touches, UIEvent evt) { base.TouchesEnded(touches, evt); var touch = touches.AnyObject as UITouch; if (touch != null) { this.ActualController.HandleTouchCompleted(this, touch.ToTouchEventArgs(this)); } } /// <summary> /// Called when a touch gesture is cancelled. /// </summary> /// <param name="touches">The touches.</param> /// <param name="evt">The event arguments.</param> public override void TouchesCancelled(NSSet touches, UIEvent evt) { base.TouchesCancelled(touches, evt); var touch = touches.AnyObject as UITouch; if (touch != null) { this.ActualController.HandleTouchCompleted(this, touch.ToTouchEventArgs(this)); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace UnicornHack.Services.English { public class EnglishMorphologicalProcessor { private static readonly string[] UninflectiveSuffixes = {"fish", "ese", "ois", "sheep", "deer", "pos", "itis", "ism", "ness"}; private static readonly string[] UninflectiveWords = { "advice", "aircraft", "asparagus", "barracks", "beef", "bison", "binoculars", "bream", "britches", "breeches", "broccoli", "cabbage", "carp", "cattle", "clippers", "chassis", "cod", "contretemps", "corps", "corn", "cotton", "chaos", "diabetes", "debris", "earth", "elk", "eland", "flounder", "gallows", "gold", "graffiti", "high-jinks", "headquarters", "herpes", "homework", "hay", "hair", "hemp", "jeans", "jackanapes", "information", "ice", "lettuce", "mackerel", "moose", "mumps", "mews", "milk", "millet", "mutton", "molasses", "measles", "news", "okra", "offspring", "pants", "proceedings", "pliers", "pincers", "police", "pork", "rabies", "rice", "salmon", "scissors", "sea-bass", "series", "shears", "shorts", "species", "swine", "scabies", "shambles", "shingles", "trout", "tuna", "traffic", "tobacco", "wildebeest", "whiting", "venison", "apparatus", "impetus", "prospectus", "cantus", "nexus", "sinus", "coitus", "plexus", "status", "hiatus" }; private static readonly Dictionary<string, string> IrregularPlurals = new Dictionary<string, string> { {"trilby", "trilbys"}, {"cheese", "cheeses"}, {"child", "children"}, {"person", "people"}, {"ox", "oxen"}, {"chilli", "chillies"}, {"cloth", "clothes"}, {"staff", "staves"}, {"thief", "thieves"}, {"die", "dice"}, {"mouse", "mice"}, {"louse", "lice"}, {"goose", "geese"}, {"albino", "albinos"}, {"generalissimo", "generalissimos"}, {"manifesto", "manifestos"}, {"archipelago", "archipelagos"}, {"ghetto", "ghettos"}, {"medico", "medicos"}, {"armadillo", "armadillos"}, {"guano", "guanos"}, {"commando", "commandos"}, {"inferno", "infernos"}, {"photo", "photos"}, {"ditto", "dittos"}, {"jumbo", "jumbos"}, {"pro", "pros"}, {"dynamo", "dynamos"}, {"lingo", "lingos"}, {"solo", "solos"}, {"quarto", "quartos"}, {"octavo", "octavos"}, {"embryo", "embryos"}, {"lumbago", "lumbagos"}, {"rhino", "rhinos"}, {"fiasco", "fiascos"}, {"magneto", "magnetos"}, {"stylo", "stylos"}, {"auto", "autos"}, {"memo", "memos"}, {"casino", "casinos"}, {"silo", "silos"}, {"stereo", "stereos"}, {"halo", "halos"}, {"kilo", "kilos"}, {"piano", "pianos"}, {"alumna", "alumnae"}, {"alga", "algae"}, {"vertebra", "vertebrae"}, {"larva", "larvae"}, {"abscissa", "abscissae"}, {"formula", "formulae"}, {"medusa", "medusae"}, {"amoeba", "amoebae"}, {"hydra", "hydrae"}, {"nebula", "nebulae"}, {"antenna", "antennae"}, {"hyperbola", "hyperbolae"}, {"nova", "novae"}, {"aurora", "aurorae"}, {"lacuna", "lacunae"}, {"parabola", "parabolae"}, {"codex", "codices"}, {"murex", "murices"}, {"silex", "silices"}, {"apex", "apices"}, {"latex", "latices"}, {"vertex", "vertices"}, {"cortex", "cortices"}, {"pontifex", "pontifices"}, {"vortex", "vortices"}, {"index", "indices"}, {"simplex", "simplices"}, {"aphelion", "aphelia"}, {"perihelion", "perihelia"}, {"hyperbaton", "hyperbata"}, {"asyndeton", "asyndeta"}, {"noumenon", "noumena"}, {"phenomenon", "phenomena"}, {"criterion", "criteria"}, {"organon", "organa"}, {"prolegomenon", "prolegomena"}, {"automaton", "automata"}, {"polyhedron", "polyhedra"}, {"agendum", "agenda"}, {"datum", "data"}, {"extremum", "extrema"}, {"bacterium", "bacteria"}, {"desideratum", "desiderata"}, {"stratum", "strata"}, {"candelabrum", "candelabra"}, {"erratum", "errata"}, {"ovum", "ova"}, {"forum", "fora"}, {"addendum", "addenda"}, {"stadium", "stadia"}, {"aquarium", "aquaria"}, {"interregnum", "interregna"}, {"quantum", "quanta"}, {"compendium", "compendia"}, {"lustrum", "lustra"}, {"rostrum", "rostra"}, {"consortium", "consortia"}, {"maximum", "maxima"}, {"spectrum", "spectra"}, {"cranium", "crania"}, {"medium", "media"}, {"speculum", "specula"}, {"curriculum", "curricula"}, {"memorandum", "memoranda"}, {"dictum", "dicta"}, {"millenium", "millenia"}, {"trapezium", "trapezia"}, {"emporium", "emporia"}, {"minimum", "minima"}, {"ultimatum", "ultimata"}, {"enconium", "enconia"}, {"momentum", "momenta"}, {"vacuum", "vacua"}, {"gymnasium", "gymnasia"}, {"optimum", "optima"}, {"velum", "vela"}, {"honorarium", "honoraria"}, {"phylum", "phyla"}, {"stamen", "stamina"}, {"foramen", "foramina"}, {"lumen", "lumina"}, {"anathema", "anathemata"}, {"enema", "enemata"}, {"oedema", "oedemata"}, {"bema", "bemata"}, {"enigma", "enigmata"}, {"sarcoma", "sarcomata"}, {"carcinoma", "carcinomata"}, {"gumma", "gummata"}, {"schema", "schemata"}, {"charisma", "charismata"}, {"lemma", "lemmata"}, {"soma", "somata"}, {"diploma", "diplomata"}, {"lymphoma", "lymphomata"}, {"stigma", "stigmata"}, {"dogma", "dogmata"}, {"magma", "magmata"}, {"stoma", "stomata"}, {"drama", "dramata"}, {"melisma", "melismata"}, {"trauma", "traumata"}, {"edema", "edemata"}, {"miasma", "miasmata"}, {"corpus", "corpora"}, {"viscus", "viscera"}, {"ephemeris", "ephemerides"}, {"iris", "irides"}, {"clitoris", "clitorides"}, {"alumnus", "alumni"}, {"cactus", "cacti"}, {"focus", "foci"}, {"genius", "genii"}, {"hippopotamus", "hippopotami"}, {"incubus", "incubi"}, {"succubus", "succubi"}, {"fungus", "fungi"}, {"mythos", "mythoi"}, {"nimbus", "nimbi"}, {"nucleolus", "nucleoli"}, {"nucleus", "nuclei"}, {"radius", "radii"}, {"stimulus", "stimuli"}, {"stylus", "styli"}, {"torus", "tori"}, {"umbilicus", "umbilici"}, {"uterus", "uteri"}, {"efreet", "efreeti"}, {"djinni", "djinnis"}, {"cherub", "cherubim"}, {"goy", "goyim"}, {"seraph", "seraphim"} }; private static readonly string[,,] Pronouns = new string[2, 5, 5] { { {"I", "you", "it", "he", "she"}, {"me", "you", "it", "him", "her"}, {"myself", "yourself", "itself", "himself", "herself"}, {"mine", "yours", "its", "his", "hers"}, {"my", "your", "its", "his", "her"} }, { {"we", "you", "they", "they", "they"}, {"us", "you", "them", "them", "them"}, {"ourselves", "yourselves", "themselves", "themselves", "themselves"}, {"ours", "yours", "theirs", "theirs", "theirs"}, {"our", "your", "their", "their", "their"} } }; private readonly SuffixReplacementStateMachine _nounPluralizationMachine = new SuffixReplacementStateMachine(); private readonly SuffixReplacementStateMachine _verbSFormMachine = new SuffixReplacementStateMachine(); public EnglishMorphologicalProcessor() { foreach (var suffix in UninflectiveSuffixes) { _nounPluralizationMachine.AddRule(suffix, replacement: "", charactersToReplace: 0); } foreach (var word in UninflectiveWords) { _nounPluralizationMachine.AddRule("^" + word, replacement: "", charactersToReplace: 0); } foreach (var pair in IrregularPlurals) { _nounPluralizationMachine.AddRule("^" + pair.Key, pair.Value, pair.Key.Length); } _nounPluralizationMachine.AddRule(suffix: "man", replacement: "en", charactersToReplace: 2); _nounPluralizationMachine.AddRule(suffix: "tooth", replacement: "eeth", charactersToReplace: 4); _nounPluralizationMachine.AddRule(suffix: "foot", replacement: "eet", charactersToReplace: 3); _nounPluralizationMachine.AddRule(suffix: "zoon", replacement: "a", charactersToReplace: 2); _nounPluralizationMachine.AddRule(suffix: "cis", replacement: "es", charactersToReplace: 2); _nounPluralizationMachine.AddRule(suffix: "sis", replacement: "es", charactersToReplace: 2); _nounPluralizationMachine.AddRule(suffix: "xis", replacement: "es", charactersToReplace: 2); _nounPluralizationMachine.AddRule(suffix: "trix", replacement: "ces", charactersToReplace: 1); _nounPluralizationMachine.AddRule(suffix: "eau", replacement: "x", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "ieu", replacement: "x", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "alf", replacement: "ves", charactersToReplace: 1); _nounPluralizationMachine.AddRule(suffix: "elf", replacement: "ves", charactersToReplace: 1); _nounPluralizationMachine.AddRule(suffix: "olf", replacement: "ves", charactersToReplace: 1); _nounPluralizationMachine.AddRule(suffix: "eaf", replacement: "ves", charactersToReplace: 1); _nounPluralizationMachine.AddRule(suffix: "arf", replacement: "ves", charactersToReplace: 1); _nounPluralizationMachine.AddRule(suffix: "ife", replacement: "ves", charactersToReplace: 2); _nounPluralizationMachine.AddRule(suffix: "ao", replacement: "s", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "eo", replacement: "s", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "io", replacement: "s", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "oo", replacement: "s", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "uo", replacement: "s", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "ch", replacement: "es", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "sh", replacement: "es", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "ss", replacement: "es", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "s", replacement: "es", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "zz", replacement: "es", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "x", replacement: "es", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "o", replacement: "es", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "i", replacement: "es", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "z", replacement: "zes", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "ay", replacement: "s", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "ey", replacement: "s", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "iy", replacement: "s", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "oy", replacement: "s", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "uy", replacement: "s", charactersToReplace: 0); _nounPluralizationMachine.AddRule(suffix: "y", replacement: "ies", charactersToReplace: 1); _nounPluralizationMachine.AddRule(suffix: "", replacement: "s", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "^be", replacement: "is", charactersToReplace: 2); _verbSFormMachine.AddRule(suffix: "^have", replacement: "s", charactersToReplace: 2); _verbSFormMachine.AddRule(suffix: "ao", replacement: "s", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "eo", replacement: "s", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "io", replacement: "s", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "oo", replacement: "s", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "uo", replacement: "s", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "ch", replacement: "es", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "sh", replacement: "es", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "ss", replacement: "es", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "s", replacement: "es", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "zz", replacement: "es", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "x", replacement: "es", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "o", replacement: "es", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "i", replacement: "es", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "z", replacement: "zes", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "ay", replacement: "s", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "ey", replacement: "s", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "iy", replacement: "s", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "oy", replacement: "s", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "uy", replacement: "s", charactersToReplace: 0); _verbSFormMachine.AddRule(suffix: "y", replacement: "ies", charactersToReplace: 1); _verbSFormMachine.AddRule(suffix: "", replacement: "s", charactersToReplace: 0); } public string ProcessVerbSimplePresent(string verbPhrase, EnglishPerson person) => ProcessVerb( verbPhrase, person == EnglishPerson.Third ? EnglishVerbForm.ThirdPersonSingularPresent : EnglishVerbForm.BareInfinitive); public string ProcessVerb(string verbPhrase, EnglishVerbForm form) { switch (form) { case EnglishVerbForm.Infinitive: return "to " + verbPhrase; case EnglishVerbForm.ThirdPersonSingularPresent: var verb = GetFirstWord(verbPhrase, out var lastPart); return _verbSFormMachine.Process(verb) + lastPart; default: return verbPhrase; } } public string ProcessNoun(string nounPhrase, EnglishNounForm form) { switch (form) { case EnglishNounForm.Plural: var words = nounPhrase.Split(' '); var indexToPluralize = words.Length - 1; if (words.Length > 2 && string.Equals("of", words[1], StringComparison.OrdinalIgnoreCase)) { indexToPluralize = 0; } words[indexToPluralize] = _nounPluralizationMachine.Process(words[indexToPluralize]); return string.Join(" ", words); default: return nounPhrase; } } public bool IsPlural(string noun) => noun.Length > 2 && noun.Substring(noun.Length - 2, 2) == "es"; public bool IsVocal(char c) { switch (char.ToLowerInvariant(c)) { case 'a': case 'e': case 'i': case 'o': case 'u': return true; default: return false; } } public string GetPronoun( EnglishPronounForm form, EnglishNumber number, EnglishPerson person, EnglishGender? gender) { var numberIndex = number == EnglishNumber.Plural ? 1 : 0; var formIndex = (int)form; var personIndex = person == EnglishPerson.Third ? 2 + (int)gender.Value : (int)person; return Pronouns[numberIndex, formIndex, personIndex]; } private static string GetFirstWord(string phrase, out string lastPart) { var firstWordLength = phrase.IndexOf(value: ' '); if (firstWordLength == -1) { firstWordLength = phrase.Length; } lastPart = phrase.Substring(firstWordLength); return phrase.Substring(startIndex: 0, length: firstWordLength); } private static string GetLastWord(string phrase, out string firstPart) { var firstPartLength = phrase.LastIndexOf(value: ' ') + 1; firstPart = phrase.Substring(startIndex: 0, length: firstPartLength); return phrase.Substring(firstPartLength); } private class SuffixReplacementStateMachine { private readonly State _initialState = new State(); public void AddRule(string suffix, string replacement, int charactersToReplace) { Debug.Assert(suffix.Length >= charactersToReplace); var state = _initialState; for (var i = suffix.Length - 1; i >= 0; i--) { var nextCharacter = suffix[i]; var nextState = state.Next(nextCharacter); if (nextState == null) { nextState = new State(); state.AddNext(nextCharacter, nextState); } state = nextState; } Debug.Assert(state.Replacement == null, "Repeated suffix " + suffix); state.Replacement = new ReplacementSuffix { ReplacementString = replacement, CharactersToReplace = charactersToReplace }; } public string Process(string word) { var state = _initialState; Debug.Assert(state.Replacement.HasValue); var replacement = state.Replacement.Value; var reachedEnd = true; for (var i = word.Length - 1; i >= 0; i--) { var nextState = state.Next(word[i]); if (nextState == null) { reachedEnd = false; break; } state = nextState; if (state.Replacement.HasValue) { replacement = state.Replacement.Value; } } if (reachedEnd) { var nextState = state.Next(character: '^'); if (nextState != null) { Debug.Assert(nextState.Replacement.HasValue); replacement = nextState.Replacement.Value; } } return word.Remove(word.Length - replacement.CharactersToReplace, replacement.CharactersToReplace) + replacement.ReplacementString; } private class State { private readonly Dictionary<char, State> _nextStates = new Dictionary<char, State>(); public ReplacementSuffix? Replacement { get; set; } public void AddNext(char character, State state) => _nextStates.Add(character, state); public State Next(char character) => _nextStates.TryGetValue(character, out var nextState) ? nextState : null; } private struct ReplacementSuffix { public string ReplacementString { get; set; } public int CharactersToReplace { get; set; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Xml.Linq { public static partial class Extensions { public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> AncestorsAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source) { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> AncestorsAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source, System.Xml.Linq.XName name) { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XNode { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors<T>(this System.Collections.Generic.IEnumerable<T> source, System.Xml.Linq.XName name) where T : System.Xml.Linq.XNode { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source) { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source, System.Xml.Linq.XName name) { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodesAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source) { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodes<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XContainer { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> DescendantsAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source) { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> DescendantsAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source, System.Xml.Linq.XName name) { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XContainer { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants<T>(this System.Collections.Generic.IEnumerable<T> source, System.Xml.Linq.XName name) where T : System.Xml.Linq.XContainer { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XContainer { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements<T>(this System.Collections.Generic.IEnumerable<T> source, System.Xml.Linq.XName name) where T : System.Xml.Linq.XContainer { throw null; } public static System.Collections.Generic.IEnumerable<T> InDocumentOrder<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XNode { throw null; } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> Nodes<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XContainer { throw null; } public static void Remove(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> source) { } public static void Remove<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XNode { } } [System.FlagsAttribute] public enum LoadOptions { None = 0, PreserveWhitespace = 1, SetBaseUri = 2, SetLineInfo = 4, } [System.FlagsAttribute] public enum ReaderOptions { None = 0, OmitDuplicateNamespaces = 1, } [System.FlagsAttribute] public enum SaveOptions { DisableFormatting = 1, None = 0, OmitDuplicateNamespaces = 2, } public partial class XAttribute : System.Xml.Linq.XObject { public XAttribute(System.Xml.Linq.XAttribute other) { } public XAttribute(System.Xml.Linq.XName name, object value) { } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> EmptySequence { get { throw null; } } public bool IsNamespaceDeclaration { get { throw null; } } public System.Xml.Linq.XName Name { get { throw null; } } public System.Xml.Linq.XAttribute NextAttribute { get { throw null; } } public override System.Xml.XmlNodeType NodeType { get { throw null; } } public System.Xml.Linq.XAttribute PreviousAttribute { get { throw null; } } public string Value { get { throw null; } set { } } [System.CLSCompliantAttribute(false)] public static explicit operator bool (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.DateTime (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.DateTimeOffset (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator decimal (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator double (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.Guid (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator int (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator long (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator bool? (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.DateTimeOffset? (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.DateTime? (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator decimal? (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator double? (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.Guid? (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator int? (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator long? (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator float? (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.TimeSpan? (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator uint? (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator ulong? (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator float (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator string (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.TimeSpan (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator uint (System.Xml.Linq.XAttribute attribute) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator ulong (System.Xml.Linq.XAttribute attribute) { throw null; } public void Remove() { } public void SetValue(object value) { } public override string ToString() { throw null; } } public partial class XCData : System.Xml.Linq.XText { public XCData(string value) : base (default(string)) { } public XCData(System.Xml.Linq.XCData other) : base (default(string)) { } public override System.Xml.XmlNodeType NodeType { get { throw null; } } public override void WriteTo(System.Xml.XmlWriter writer) { } public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class XComment : System.Xml.Linq.XNode { public XComment(string value) { } public XComment(System.Xml.Linq.XComment other) { } public override System.Xml.XmlNodeType NodeType { get { throw null; } } public string Value { get { throw null; } set { } } public override void WriteTo(System.Xml.XmlWriter writer) { } public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; } } public abstract partial class XContainer : System.Xml.Linq.XNode { internal XContainer() { } public System.Xml.Linq.XNode FirstNode { get { throw null; } } public System.Xml.Linq.XNode LastNode { get { throw null; } } public void Add(object content) { } public void Add(params object[] content) { } public void AddFirst(object content) { } public void AddFirst(params object[] content) { } public System.Xml.XmlWriter CreateWriter() { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodes() { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants() { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants(System.Xml.Linq.XName name) { throw null; } public System.Xml.Linq.XElement Element(System.Xml.Linq.XName name) { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements() { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements(System.Xml.Linq.XName name) { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> Nodes() { throw null; } public void RemoveNodes() { } public void ReplaceNodes(object content) { } public void ReplaceNodes(params object[] content) { } } public partial class XDeclaration { public XDeclaration(string version, string encoding, string standalone) { } public XDeclaration(System.Xml.Linq.XDeclaration other) { } public string Encoding { get { throw null; } set { } } public string Standalone { get { throw null; } set { } } public string Version { get { throw null; } set { } } public override string ToString() { throw null; } } public partial class XDocument : System.Xml.Linq.XContainer { public XDocument() { } public XDocument(params object[] content) { } public XDocument(System.Xml.Linq.XDeclaration declaration, params object[] content) { } public XDocument(System.Xml.Linq.XDocument other) { } public System.Xml.Linq.XDeclaration Declaration { get { throw null; } set { } } public System.Xml.Linq.XDocumentType DocumentType { get { throw null; } } public override System.Xml.XmlNodeType NodeType { get { throw null; } } public System.Xml.Linq.XElement Root { get { throw null; } } public static System.Xml.Linq.XDocument Load(System.IO.Stream stream) { throw null; } public static System.Xml.Linq.XDocument Load(System.IO.Stream stream, System.Xml.Linq.LoadOptions options) { throw null; } public static System.Xml.Linq.XDocument Load(System.IO.TextReader textReader) { throw null; } public static System.Xml.Linq.XDocument Load(System.IO.TextReader textReader, System.Xml.Linq.LoadOptions options) { throw null; } public static System.Xml.Linq.XDocument Load(string uri) { throw null; } public static System.Xml.Linq.XDocument Load(string uri, System.Xml.Linq.LoadOptions options) { throw null; } public static System.Xml.Linq.XDocument Load(System.Xml.XmlReader reader) { throw null; } public static System.Xml.Linq.XDocument Load(System.Xml.XmlReader reader, System.Xml.Linq.LoadOptions options) { throw null; } public static System.Threading.Tasks.Task<System.Xml.Linq.XDocument> LoadAsync(System.IO.Stream stream, System.Xml.Linq.LoadOptions options, System.Threading.CancellationToken cancellationToken) { throw null; } public static System.Threading.Tasks.Task<System.Xml.Linq.XDocument> LoadAsync(System.IO.TextReader textReader, System.Xml.Linq.LoadOptions options, System.Threading.CancellationToken cancellationToken) { throw null; } public static System.Threading.Tasks.Task<System.Xml.Linq.XDocument> LoadAsync(System.Xml.XmlReader reader, System.Xml.Linq.LoadOptions options, System.Threading.CancellationToken cancellationToken) { throw null; } public static System.Xml.Linq.XDocument Parse(string text) { throw null; } public static System.Xml.Linq.XDocument Parse(string text, System.Xml.Linq.LoadOptions options) { throw null; } public void Save(System.IO.Stream stream) { } public void Save(System.IO.Stream stream, System.Xml.Linq.SaveOptions options) { } public void Save(System.IO.TextWriter textWriter) { } public void Save(System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options) { } public void Save(string fileName) { } public void Save(string fileName, System.Xml.Linq.SaveOptions options) { } public void Save(System.Xml.XmlWriter writer) { } public System.Threading.Tasks.Task SaveAsync(System.IO.Stream stream, System.Xml.Linq.SaveOptions options, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task SaveAsync(System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task SaveAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; } public override void WriteTo(System.Xml.XmlWriter writer) { } public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class XDocumentType : System.Xml.Linq.XNode { public XDocumentType(string name, string publicId, string systemId, string internalSubset) { } public XDocumentType(System.Xml.Linq.XDocumentType other) { } public string InternalSubset { get { throw null; } set { } } public string Name { get { throw null; } set { } } public override System.Xml.XmlNodeType NodeType { get { throw null; } } public string PublicId { get { throw null; } set { } } public string SystemId { get { throw null; } set { } } public override void WriteTo(System.Xml.XmlWriter writer) { } public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; } } [System.Xml.Serialization.XmlSchemaProviderAttribute(null, IsAny=true)] public partial class XElement : System.Xml.Linq.XContainer, System.Xml.Serialization.IXmlSerializable { public XElement(System.Xml.Linq.XElement other) { } public XElement(System.Xml.Linq.XName name) { } public XElement(System.Xml.Linq.XName name, object content) { } public XElement(System.Xml.Linq.XName name, params object[] content) { } public XElement(System.Xml.Linq.XStreamingElement other) { } public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> EmptySequence { get { throw null; } } public System.Xml.Linq.XAttribute FirstAttribute { get { throw null; } } public bool HasAttributes { get { throw null; } } public bool HasElements { get { throw null; } } public bool IsEmpty { get { throw null; } } public System.Xml.Linq.XAttribute LastAttribute { get { throw null; } } public System.Xml.Linq.XName Name { get { throw null; } set { } } public override System.Xml.XmlNodeType NodeType { get { throw null; } } public string Value { get { throw null; } set { } } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> AncestorsAndSelf() { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> AncestorsAndSelf(System.Xml.Linq.XName name) { throw null; } public System.Xml.Linq.XAttribute Attribute(System.Xml.Linq.XName name) { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes() { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes(System.Xml.Linq.XName name) { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodesAndSelf() { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> DescendantsAndSelf() { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> DescendantsAndSelf(System.Xml.Linq.XName name) { throw null; } public System.Xml.Linq.XNamespace GetDefaultNamespace() { throw null; } public System.Xml.Linq.XNamespace GetNamespaceOfPrefix(string prefix) { throw null; } public string GetPrefixOfNamespace(System.Xml.Linq.XNamespace ns) { throw null; } public static System.Xml.Linq.XElement Load(System.IO.Stream stream) { throw null; } public static System.Xml.Linq.XElement Load(System.IO.Stream stream, System.Xml.Linq.LoadOptions options) { throw null; } public static System.Xml.Linq.XElement Load(System.IO.TextReader textReader) { throw null; } public static System.Xml.Linq.XElement Load(System.IO.TextReader textReader, System.Xml.Linq.LoadOptions options) { throw null; } public static System.Xml.Linq.XElement Load(string uri) { throw null; } public static System.Xml.Linq.XElement Load(string uri, System.Xml.Linq.LoadOptions options) { throw null; } public static System.Xml.Linq.XElement Load(System.Xml.XmlReader reader) { throw null; } public static System.Xml.Linq.XElement Load(System.Xml.XmlReader reader, System.Xml.Linq.LoadOptions options) { throw null; } public static System.Threading.Tasks.Task<System.Xml.Linq.XElement> LoadAsync(System.IO.Stream stream, System.Xml.Linq.LoadOptions options, System.Threading.CancellationToken cancellationToken) { throw null; } public static System.Threading.Tasks.Task<System.Xml.Linq.XElement> LoadAsync(System.IO.TextReader textReader, System.Xml.Linq.LoadOptions options, System.Threading.CancellationToken cancellationToken) { throw null; } public static System.Threading.Tasks.Task<System.Xml.Linq.XElement> LoadAsync(System.Xml.XmlReader reader, System.Xml.Linq.LoadOptions options, System.Threading.CancellationToken cancellationToken) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator bool (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.DateTime (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.DateTimeOffset (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator decimal (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator double (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.Guid (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator int (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator long (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator bool? (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.DateTimeOffset? (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.DateTime? (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator decimal? (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator double? (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.Guid? (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator int? (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator long? (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator float? (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.TimeSpan? (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator uint? (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator ulong? (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator float (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator string (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator System.TimeSpan (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator uint (System.Xml.Linq.XElement element) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator ulong (System.Xml.Linq.XElement element) { throw null; } public static System.Xml.Linq.XElement Parse(string text) { throw null; } public static System.Xml.Linq.XElement Parse(string text, System.Xml.Linq.LoadOptions options) { throw null; } public void RemoveAll() { } public void RemoveAttributes() { } public void ReplaceAll(object content) { } public void ReplaceAll(params object[] content) { } public void ReplaceAttributes(object content) { } public void ReplaceAttributes(params object[] content) { } public void Save(System.IO.Stream stream) { } public void Save(System.IO.Stream stream, System.Xml.Linq.SaveOptions options) { } public void Save(System.IO.TextWriter textWriter) { } public void Save(System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options) { } public void Save(string fileName) { } public void Save(string fileName, System.Xml.Linq.SaveOptions options) { } public void Save(System.Xml.XmlWriter writer) { } public System.Threading.Tasks.Task SaveAsync(System.IO.Stream stream, System.Xml.Linq.SaveOptions options, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task SaveAsync(System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task SaveAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; } public void SetAttributeValue(System.Xml.Linq.XName name, object value) { } public void SetElementValue(System.Xml.Linq.XName name, object value) { } public void SetValue(object value) { } System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public override void WriteTo(System.Xml.XmlWriter writer) { } public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; } } public sealed partial class XName : System.IEquatable<System.Xml.Linq.XName>, System.Runtime.Serialization.ISerializable { internal XName() { } public string LocalName { get { throw null; } } public System.Xml.Linq.XNamespace Namespace { get { throw null; } } public string NamespaceName { get { throw null; } } public override bool Equals(object obj) { throw null; } public static System.Xml.Linq.XName Get(string expandedName) { throw null; } public static System.Xml.Linq.XName Get(string localName, string namespaceName) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Xml.Linq.XName left, System.Xml.Linq.XName right) { throw null; } [System.CLSCompliantAttribute(false)] public static implicit operator System.Xml.Linq.XName (string expandedName) { throw null; } public static bool operator !=(System.Xml.Linq.XName left, System.Xml.Linq.XName right) { throw null; } bool System.IEquatable<System.Xml.Linq.XName>.Equals(System.Xml.Linq.XName other) { throw null; } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } } public sealed partial class XNamespace { internal XNamespace() { } public string NamespaceName { get { throw null; } } public static System.Xml.Linq.XNamespace None { get { throw null; } } public static System.Xml.Linq.XNamespace Xml { get { throw null; } } public static System.Xml.Linq.XNamespace Xmlns { get { throw null; } } public override bool Equals(object obj) { throw null; } public static System.Xml.Linq.XNamespace Get(string namespaceName) { throw null; } public override int GetHashCode() { throw null; } public System.Xml.Linq.XName GetName(string localName) { throw null; } public static System.Xml.Linq.XName operator +(System.Xml.Linq.XNamespace ns, string localName) { throw null; } public static bool operator ==(System.Xml.Linq.XNamespace left, System.Xml.Linq.XNamespace right) { throw null; } [System.CLSCompliantAttribute(false)] public static implicit operator System.Xml.Linq.XNamespace (string namespaceName) { throw null; } public static bool operator !=(System.Xml.Linq.XNamespace left, System.Xml.Linq.XNamespace right) { throw null; } public override string ToString() { throw null; } } public abstract partial class XNode : System.Xml.Linq.XObject { internal XNode() { } public static System.Xml.Linq.XNodeDocumentOrderComparer DocumentOrderComparer { get { throw null; } } public static System.Xml.Linq.XNodeEqualityComparer EqualityComparer { get { throw null; } } public System.Xml.Linq.XNode NextNode { get { throw null; } } public System.Xml.Linq.XNode PreviousNode { get { throw null; } } public void AddAfterSelf(object content) { } public void AddAfterSelf(params object[] content) { } public void AddBeforeSelf(object content) { } public void AddBeforeSelf(params object[] content) { } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors() { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors(System.Xml.Linq.XName name) { throw null; } public static int CompareDocumentOrder(System.Xml.Linq.XNode n1, System.Xml.Linq.XNode n2) { throw null; } public System.Xml.XmlReader CreateReader() { throw null; } public System.Xml.XmlReader CreateReader(System.Xml.Linq.ReaderOptions readerOptions) { throw null; } public static bool DeepEquals(System.Xml.Linq.XNode n1, System.Xml.Linq.XNode n2) { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsAfterSelf() { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsAfterSelf(System.Xml.Linq.XName name) { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsBeforeSelf() { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsBeforeSelf(System.Xml.Linq.XName name) { throw null; } public bool IsAfter(System.Xml.Linq.XNode node) { throw null; } public bool IsBefore(System.Xml.Linq.XNode node) { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> NodesAfterSelf() { throw null; } public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> NodesBeforeSelf() { throw null; } public static System.Xml.Linq.XNode ReadFrom(System.Xml.XmlReader reader) { throw null; } public static System.Threading.Tasks.Task<System.Xml.Linq.XNode> ReadFromAsync(System.Xml.XmlReader reader, System.Threading.CancellationToken cancellationToken) { throw null; } public void Remove() { } public void ReplaceWith(object content) { } public void ReplaceWith(params object[] content) { } public override string ToString() { throw null; } public string ToString(System.Xml.Linq.SaveOptions options) { throw null; } public abstract void WriteTo(System.Xml.XmlWriter writer); public abstract System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken); } public sealed partial class XNodeDocumentOrderComparer : System.Collections.Generic.IComparer<System.Xml.Linq.XNode>, System.Collections.IComparer { public XNodeDocumentOrderComparer() { } public int Compare(System.Xml.Linq.XNode x, System.Xml.Linq.XNode y) { throw null; } int System.Collections.IComparer.Compare(object x, object y) { throw null; } } public sealed partial class XNodeEqualityComparer : System.Collections.Generic.IEqualityComparer<System.Xml.Linq.XNode>, System.Collections.IEqualityComparer { public XNodeEqualityComparer() { } public bool Equals(System.Xml.Linq.XNode x, System.Xml.Linq.XNode y) { throw null; } public int GetHashCode(System.Xml.Linq.XNode obj) { throw null; } bool System.Collections.IEqualityComparer.Equals(object x, object y) { throw null; } int System.Collections.IEqualityComparer.GetHashCode(object obj) { throw null; } } public abstract partial class XObject : System.Xml.IXmlLineInfo { internal XObject() { } public string BaseUri { get { throw null; } } public System.Xml.Linq.XDocument Document { get { throw null; } } public abstract System.Xml.XmlNodeType NodeType { get; } public System.Xml.Linq.XElement Parent { get { throw null; } } int System.Xml.IXmlLineInfo.LineNumber { get { throw null; } } int System.Xml.IXmlLineInfo.LinePosition { get { throw null; } } public event System.EventHandler<System.Xml.Linq.XObjectChangeEventArgs> Changed { add { } remove { } } public event System.EventHandler<System.Xml.Linq.XObjectChangeEventArgs> Changing { add { } remove { } } public void AddAnnotation(object annotation) { } public object Annotation(System.Type type) { throw null; } public System.Collections.Generic.IEnumerable<object> Annotations(System.Type type) { throw null; } public System.Collections.Generic.IEnumerable<T> Annotations<T>() where T : class { throw null; } public T Annotation<T>() where T : class { throw null; } public void RemoveAnnotations(System.Type type) { } public void RemoveAnnotations<T>() where T : class { } bool System.Xml.IXmlLineInfo.HasLineInfo() { throw null; } } public enum XObjectChange { Add = 0, Name = 2, Remove = 1, Value = 3, } public partial class XObjectChangeEventArgs : System.EventArgs { public static readonly System.Xml.Linq.XObjectChangeEventArgs Add; public static readonly System.Xml.Linq.XObjectChangeEventArgs Name; public static readonly System.Xml.Linq.XObjectChangeEventArgs Remove; public static readonly System.Xml.Linq.XObjectChangeEventArgs Value; public XObjectChangeEventArgs(System.Xml.Linq.XObjectChange objectChange) { } public System.Xml.Linq.XObjectChange ObjectChange { get { throw null; } } } public partial class XProcessingInstruction : System.Xml.Linq.XNode { public XProcessingInstruction(string target, string data) { } public XProcessingInstruction(System.Xml.Linq.XProcessingInstruction other) { } public string Data { get { throw null; } set { } } public override System.Xml.XmlNodeType NodeType { get { throw null; } } public string Target { get { throw null; } set { } } public override void WriteTo(System.Xml.XmlWriter writer) { } public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class XStreamingElement { public XStreamingElement(System.Xml.Linq.XName name) { } public XStreamingElement(System.Xml.Linq.XName name, object content) { } public XStreamingElement(System.Xml.Linq.XName name, params object[] content) { } public System.Xml.Linq.XName Name { get { throw null; } set { } } public void Add(object content) { } public void Add(params object[] content) { } public void Save(System.IO.Stream stream) { } public void Save(System.IO.Stream stream, System.Xml.Linq.SaveOptions options) { } public void Save(System.IO.TextWriter textWriter) { } public void Save(System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options) { } public void Save(string fileName) { } public void Save(string fileName, System.Xml.Linq.SaveOptions options) { } public void Save(System.Xml.XmlWriter writer) { } public override string ToString() { throw null; } public string ToString(System.Xml.Linq.SaveOptions options) { throw null; } public void WriteTo(System.Xml.XmlWriter writer) { } } public partial class XText : System.Xml.Linq.XNode { public XText(string value) { } public XText(System.Xml.Linq.XText other) { } public override System.Xml.XmlNodeType NodeType { get { throw null; } } public string Value { get { throw null; } set { } } public override void WriteTo(System.Xml.XmlWriter writer) { } public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; } } } namespace System.Xml.Schema { public static partial class Extensions { public static System.Xml.Schema.IXmlSchemaInfo GetSchemaInfo(this System.Xml.Linq.XAttribute source) { throw null; } public static System.Xml.Schema.IXmlSchemaInfo GetSchemaInfo(this System.Xml.Linq.XElement source) { throw null; } public static void Validate(this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler) { } public static void Validate(this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo) { } public static void Validate(this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler) { } public static void Validate(this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo) { } public static void Validate(this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler) { } public static void Validate(this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo) { } } }
//originally from Matthew Adams, who was a thorough blog on these things at http://mwadams.spaces.live.com/blog/cns!652A0FB566F633D5!133.entry using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Windows.Forms; using SIL.Progress; using SIL.Reporting; namespace SIL.Windows.Forms.Progress { /// <summary> /// Provides a progress dialog similar to the one shown by Windows /// </summary> public class ProgressDialog : Form { public delegate void ProgressCallback(int progress); private Label _statusLabel; private ProgressBar _progressBar; private Label _progressLabel; private Button _cancelButton; private Timer _showWindowIfTakingLongTimeTimer; private Timer _progressTimer; private bool _isClosing; private Label _overviewLabel; private DateTime _startTime; private IContainer components; private BackgroundWorker _backgroundWorker; // private ProgressState _lastHeardFromProgressState; private ProgressState _progressState; private TableLayoutPanel tableLayout; private bool _workerStarted; private bool _appUsingWaitCursor; /// <summary> /// Standard constructor /// </summary> public ProgressDialog() { // // Required for Windows Form Designer support // InitializeComponent(); _statusLabel.BackColor = Color.Transparent; _progressLabel.BackColor = Color.Transparent; _overviewLabel.BackColor = Color.Transparent; _startTime = default(DateTime); Text = UsageReporter.AppNameToUseInDialogs; _statusLabel.Font = SystemFonts.MessageBoxFont; _progressLabel.Font = SystemFonts.MessageBoxFont; _overviewLabel.Font = SystemFonts.MessageBoxFont; _statusLabel.Text = string.Empty; _progressLabel.Text = string.Empty; _overviewLabel.Text = string.Empty; _cancelButton.MouseEnter += delegate { _appUsingWaitCursor = Application.UseWaitCursor; _cancelButton.Cursor = Cursor = Cursors.Arrow; Application.UseWaitCursor = false; }; _cancelButton.MouseLeave += delegate { Application.UseWaitCursor = _appUsingWaitCursor; }; //avoids the client getting null errors if he checks this when there //has yet to be a callback from the worker // _lastHeardFromProgressState = new NullProgressState(); } private void HandleTableLayoutSizeChanged(object sender, EventArgs e) { if (!IsHandleCreated) CreateHandle(); var desiredHeight = tableLayout.Height + Padding.Top + Padding.Bottom + (Height - ClientSize.Height); var scn = Screen.FromControl(this); Height = Math.Min(desiredHeight, scn.WorkingArea.Height - 20); AutoScroll = (desiredHeight > scn.WorkingArea.Height - 20); } /// <summary> /// Get / set the time in ms to delay /// before showing the dialog /// </summary> private/*doesn't work yet public*/ int DelayShowInterval { get { return _showWindowIfTakingLongTimeTimer.Interval; } set { _showWindowIfTakingLongTimeTimer.Interval = value; } } /// <summary> /// Get / set the text to display in the first status panel /// </summary> public string StatusText { get { return _statusLabel.Text; } set { _statusLabel.Text = value; } } /// <summary> /// Description of why this dialog is even showing /// </summary> public string Overview { get { return _overviewLabel.Text; } set { _overviewLabel.Text = value; } } /// <summary> /// Get / set the minimum range of the progress bar /// </summary> public int ProgressRangeMinimum { get { return _progressBar.Minimum; } set { if (_backgroundWorker == null) { _progressBar.Minimum = value; } } } /// <summary> /// Get / set the maximum range of the progress bar /// </summary> public int ProgressRangeMaximum { get { return _progressBar.Maximum; } set { if (_backgroundWorker != null) { return; } if (InvokeRequired) { Invoke(new ProgressCallback(SetMaximumCrossThread), new object[] { value }); } else { _progressBar.Maximum = value; } } } private void SetMaximumCrossThread(int amount) { ProgressRangeMaximum = amount; } /// <summary> /// Get / set the current value of the progress bar /// </summary> public int Progress { get { return _progressBar.Value; } set { /* these were causing weird, hard to debug (because of threads) * failures. The debugger would reprot that value == max, so why fail? * Debug.Assert(value <= _progressBar.Maximum); */ Debug.WriteLineIf(value > _progressBar.Maximum, "***Warning progres was " + value + " but max is " + _progressBar.Maximum); Debug.Assert(value >= _progressBar.Minimum); if (value > _progressBar.Maximum) { _progressBar.Maximum = value;//not worth crashing over in Release build } if (value < _progressBar.Minimum) { return; //not worth crashing over in Release build } _progressBar.Value = value; } } /// <summary> /// Get/set a boolean which determines whether the form /// will show a cancel option (true) or not (false) /// </summary> public bool CanCancel { get { return _cancelButton.Enabled; } set { _cancelButton.Enabled = value; } } /// <summary> /// If this is set before showing, the dialog will run the worker and respond /// to its events /// </summary> public BackgroundWorker BackgroundWorker { get { return _backgroundWorker; } set { _backgroundWorker = value; _progressBar.Minimum = 0; _progressBar.Maximum = 100; } } public ProgressState ProgressStateResult { get { return _progressState;// return _lastHeardFromProgressState; } } /// <summary> /// Gets or sets the manner in which progress should be indicated on the progress bar. /// </summary> public ProgressBarStyle BarStyle { get { return _progressBar.Style; } set { _progressBar.Style = value; } } /// <summary> /// Optional; one will be created (of some class or subclass) if you don't set it. /// E.g. dlg.ProgressState = new BackgroundWorkerState(dlg.BackgroundWorker); /// Also, you can use the getter to gain access to the progressstate, in order to add arguments /// which the worker method can get at. /// </summary> public ProgressState ProgressState { get { if(_progressState ==null) { if(_backgroundWorker == null) { throw new ArgumentException("You must set BackgroundWorker before accessing this property."); } ProgressState = new BackgroundWorkerState(_backgroundWorker); } return _progressState; } set { if (_progressState!=null) { CancelRequested -= _progressState.CancelRequested; } _progressState = value; CancelRequested += _progressState.CancelRequested; _progressState.TotalNumberOfStepsChanged += OnTotalNumberOfStepsChanged; } } void OnBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //BackgroundWorkerState progressState = e.Result as ProgressState; if(e.Cancelled ) { DialogResult = DialogResult.Cancel; //_progressState.State = ProgressState.StateValue.Finished; } //NB: I don't know how to actually let the BW know there was an error //else if (e.Error != null || else if (ProgressStateResult != null && (ProgressStateResult.State == ProgressState.StateValue.StoppedWithError || ProgressStateResult.ExceptionThatWasEncountered != null)) { //this dialog really can't know whether this was an unexpected exception or not //so don't do this: Reporting.ErrorReporter.ReportException(ProgressStateResult.ExceptionThatWasEncountered, this, false); DialogResult = DialogResult.Abort;//not really matching semantics // _progressState.State = ProgressState.StateValue.StoppedWithError; } else { DialogResult = DialogResult.OK; // _progressState.State = ProgressState.StateValue.Finished; } _isClosing = true; Close(); } void OnBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { ProgressState state = e.UserState as ProgressState; if (state != null) { // _lastHeardFromProgressState = state; StatusText = state.StatusLabel; } if (state == null || state is BackgroundWorkerState) { Progress = e.ProgressPercentage; } else { ProgressRangeMaximum = state.TotalNumberOfSteps; Progress = state.NumberOfStepsCompleted; } } /// <summary> /// Show the control, but honor the /// <see cref="DelayShowInterval"/>. /// </summary> private/*doesn't work yet public*/ void DelayShow() { // This creates the control, but doesn't // show it; you can't use CreateControl() // here, because it will return because // the control is not visible CreateHandle(); } //************ //the problem is that our worker reports progress, and we die (only in some circumstance not nailed-down yet) //because of a begininvoke with no window yet. Sometimes, we don't get the callback to //the very important OnBackgroundWorker_RunWorkerCompleted private/*doesn't work yet public*/ void ShowDialogIfTakesLongTime() { DelayShow(); OnStartWorker(this, null); while((_progressState.State == ProgressState.StateValue.NotStarted || _progressState.State == ProgressState.StateValue.Busy) && !this.Visible) { Application.DoEvents(); } } /// <summary> /// Close the dialog, ignoring cancel status /// </summary> public void ForceClose() { _isClosing = true; Close(); } /// <summary> /// Raised when the cancel button is clicked /// </summary> public event EventHandler CancelRequested; /// <summary> /// Raises the cancelled event /// </summary> /// <param name="e">Event data</param> protected virtual void OnCancelled( EventArgs e ) { EventHandler cancelled = CancelRequested; if( cancelled != null ) { cancelled( this, e ); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (_showWindowIfTakingLongTimeTimer != null) { _showWindowIfTakingLongTimeTimer.Stop(); } if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } ///// <summary> ///// Custom handle creation code ///// </summary> ///// <param name="e">Event data</param> // protected override void OnHandleCreated(EventArgs e) // { // base.OnHandleCreated (e); // if( !_showOnce ) // { // // First, we don't want this to happen again // _showOnce = true; // // Then, start the timer which will determine whether // // we are going to show this again // _showWindowIfTakingLongTimeTimer.Start(); // } // } ///// <summary> ///// Custom close handler ///// </summary> ///// <param name="e">Event data</param> // protected override void OnClosing(CancelEventArgs e) // { // Debug.WriteLine("Dialog:OnClosing"); // if (_showWindowIfTakingLongTimeTimer != null) // { // _showWindowIfTakingLongTimeTimer.Stop(); // } // // if( !_isClosing ) // { // Debug.WriteLine("Warning: OnClosing called but _isClosing=false, attempting cancel click"); // e.Cancel = true; // _cancelButton.PerformClick(); // } // base.OnClosing( e ); // } #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(); this._statusLabel = new System.Windows.Forms.Label(); this._progressBar = new System.Windows.Forms.ProgressBar(); this._cancelButton = new System.Windows.Forms.Button(); this._progressLabel = new System.Windows.Forms.Label(); this._showWindowIfTakingLongTimeTimer = new System.Windows.Forms.Timer(this.components); this._progressTimer = new System.Windows.Forms.Timer(this.components); this._overviewLabel = new System.Windows.Forms.Label(); this.tableLayout = new System.Windows.Forms.TableLayoutPanel(); this.tableLayout.SuspendLayout(); this.SuspendLayout(); // // _statusLabel // this._statusLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._statusLabel.AutoSize = true; this._statusLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.tableLayout.SetColumnSpan(this._statusLabel, 2); this._statusLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._statusLabel.Location = new System.Drawing.Point(0, 35); this._statusLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 5); this._statusLabel.Name = "_statusLabel"; this._statusLabel.Size = new System.Drawing.Size(355, 15); this._statusLabel.TabIndex = 12; this._statusLabel.Text = "#"; this._statusLabel.UseMnemonic = false; // // _progressBar // this._progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tableLayout.SetColumnSpan(this._progressBar, 2); this._progressBar.Location = new System.Drawing.Point(0, 55); this._progressBar.Margin = new System.Windows.Forms.Padding(0, 0, 0, 12); this._progressBar.Name = "_progressBar"; this._progressBar.Size = new System.Drawing.Size(355, 18); this._progressBar.Style = System.Windows.Forms.ProgressBarStyle.Continuous; this._progressBar.TabIndex = 11; this._progressBar.Value = 1; // // _cancelButton // this._cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this._cancelButton.AutoSize = true; this._cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this._cancelButton.Location = new System.Drawing.Point(280, 85); this._cancelButton.Margin = new System.Windows.Forms.Padding(8, 0, 0, 0); this._cancelButton.Name = "_cancelButton"; this._cancelButton.Size = new System.Drawing.Size(75, 23); this._cancelButton.TabIndex = 10; this._cancelButton.Text = "&Cancel"; this._cancelButton.Click += new System.EventHandler(this.OnCancelButton_Click); // // _progressLabel // this._progressLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._progressLabel.AutoEllipsis = true; this._progressLabel.AutoSize = true; this._progressLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this._progressLabel.Location = new System.Drawing.Point(0, 90); this._progressLabel.Margin = new System.Windows.Forms.Padding(0, 5, 0, 0); this._progressLabel.Name = "_progressLabel"; this._progressLabel.Size = new System.Drawing.Size(272, 13); this._progressLabel.TabIndex = 9; this._progressLabel.Text = "#"; this._progressLabel.UseMnemonic = false; // // _showWindowIfTakingLongTimeTimer // this._showWindowIfTakingLongTimeTimer.Interval = 2000; this._showWindowIfTakingLongTimeTimer.Tick += new System.EventHandler(this.OnTakingLongTimeTimerClick); // // _progressTimer // this._progressTimer.Enabled = true; this._progressTimer.Interval = 1000; this._progressTimer.Tick += new System.EventHandler(this.progressTimer_Tick); // // _overviewLabel // this._overviewLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._overviewLabel.AutoSize = true; this._overviewLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.tableLayout.SetColumnSpan(this._overviewLabel, 2); this._overviewLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._overviewLabel.Location = new System.Drawing.Point(0, 0); this._overviewLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 20); this._overviewLabel.Name = "_overviewLabel"; this._overviewLabel.Size = new System.Drawing.Size(355, 15); this._overviewLabel.TabIndex = 8; this._overviewLabel.Text = "#"; this._overviewLabel.UseMnemonic = false; // // tableLayout // this.tableLayout.AutoSize = true; this.tableLayout.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayout.BackColor = System.Drawing.Color.Transparent; this.tableLayout.ColumnCount = 2; this.tableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayout.Controls.Add(this._cancelButton, 1, 3); this.tableLayout.Controls.Add(this._overviewLabel, 0, 0); this.tableLayout.Controls.Add(this._progressLabel, 0, 3); this.tableLayout.Controls.Add(this._progressBar, 0, 2); this.tableLayout.Controls.Add(this._statusLabel, 0, 1); this.tableLayout.Dock = System.Windows.Forms.DockStyle.Top; this.tableLayout.Location = new System.Drawing.Point(12, 12); this.tableLayout.Name = "tableLayout"; this.tableLayout.RowCount = 4; this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayout.Size = new System.Drawing.Size(355, 108); this.tableLayout.TabIndex = 13; this.tableLayout.SizeChanged += new System.EventHandler(this.HandleTableLayoutSizeChanged); // // ProgressDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.AutoSize = true; this.ClientSize = new System.Drawing.Size(379, 150); this.ControlBox = false; this.Controls.Add(this.tableLayout); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ProgressDialog"; this.Padding = new System.Windows.Forms.Padding(12); this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Palaso"; this.Load += new System.EventHandler(this.ProgressDialog_Load); this.Shown += new System.EventHandler(this.ProgressDialog_Shown); this.tableLayout.ResumeLayout(false); this.tableLayout.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private void OnTakingLongTimeTimerClick(object sender, EventArgs e) { // Show the window now the timer has elapsed, and stop the timer _showWindowIfTakingLongTimeTimer.Stop(); if (!this.Visible) { Show(); } } private void OnCancelButton_Click(object sender, EventArgs e) { _showWindowIfTakingLongTimeTimer.Stop(); if(_isClosing) return; Debug.WriteLine("Dialog:OnCancelButton_Click"); // Prevent further cancellation _cancelButton.Enabled = false; _progressTimer.Stop(); _progressLabel.Text = "Canceling..."; // Tell people we're canceling OnCancelled( e ); if (_backgroundWorker != null && _backgroundWorker.WorkerSupportsCancellation) { _backgroundWorker.CancelAsync(); } } private void progressTimer_Tick(object sender, EventArgs e) { int range = _progressBar.Maximum - _progressBar.Minimum; if( range <= 0 ) { return; } if( _progressBar.Value <= 0 ) { return; } if (_startTime != default(DateTime)) { TimeSpan elapsed = DateTime.Now - _startTime; double estimatedSeconds = (elapsed.TotalSeconds * range) / _progressBar.Value; TimeSpan estimatedToGo = new TimeSpan(0, 0, 0, (int)(estimatedSeconds - elapsed.TotalSeconds), 0); //_progressLabel.Text = String.Format( // System.Globalization.CultureInfo.CurrentUICulture, // "Elapsed: {0} Remaining: {1}", // GetStringFor(elapsed), // GetStringFor(estimatedToGo)); _progressLabel.Text = String.Format( CultureInfo.CurrentUICulture, "{0}", //GetStringFor(elapsed), GetStringFor(estimatedToGo)); } } private static string GetStringFor( TimeSpan span ) { if( span.TotalDays > 1 ) { return string.Format(CultureInfo.CurrentUICulture, "{0} day {1} hour", span.Days, span.Hours); } else if( span.TotalHours > 1 ) { return string.Format(CultureInfo.CurrentUICulture, "{0} hour {1} minutes", span.Hours, span.Minutes); } else if( span.TotalMinutes > 1 ) { return string.Format(CultureInfo.CurrentUICulture, "{0} minutes {1} seconds", span.Minutes, span.Seconds); } return string.Format( CultureInfo.CurrentUICulture, "{0} seconds", span.Seconds ); } public void OnNumberOfStepsCompletedChanged(object sender, EventArgs e) { Progress = ((ProgressState) sender).NumberOfStepsCompleted; //in case there is no event pump showing us (mono-threaded) progressTimer_Tick(this, null); Refresh(); } public void OnTotalNumberOfStepsChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new ProgressCallback(UpdateTotal), new object[] { ((ProgressState)sender).TotalNumberOfSteps }); } else { UpdateTotal(((ProgressState) sender).TotalNumberOfSteps); } } private void UpdateTotal(int steps) { _startTime = DateTime.Now; ProgressRangeMaximum = steps; Refresh(); } public void OnStatusLabelChanged(object sender, EventArgs e) { StatusText = ((ProgressState)sender).StatusLabel; Refresh(); } private void OnStartWorker(object sender, EventArgs e) { _workerStarted = true; Debug.WriteLine("Dialog:StartWorker"); if (_backgroundWorker != null) { //BW uses percentages (unless it's using our custom ProgressState in the UserState member) ProgressRangeMinimum = 0; ProgressRangeMaximum = 100; //if the actual task can't take cancelling, the caller of this should set CanCancel to false; _backgroundWorker.WorkerSupportsCancellation = CanCancel; _backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(OnBackgroundWorker_ProgressChanged); _backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnBackgroundWorker_RunWorkerCompleted); _backgroundWorker.RunWorkerAsync(ProgressState); } } //this is here, in addition to the OnShown handler, because of a weird bug were a certain, //completely unrelated test (which doesn't use this class at all) can cause tests using this to //fail because the OnShown event is never fired. //I don't know why the orginal code we copied this from was using onshown instead of onload, //but it may have something to do with its "delay show" feature (which I couldn't get to work, //but which would be a terrific thing to have) private void ProgressDialog_Load(object sender, EventArgs e) { if(!_workerStarted) { OnStartWorker(this, null); } } private void ProgressDialog_Shown(object sender, EventArgs e) { if(!_workerStarted) { OnStartWorker(this, 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.Text; using Xunit; namespace System.Tests { public class ConvertFromBase64Tests { [Fact] public static void Roundtrip1() { string input = "test"; Verify(input, result => { // See Freed, N. and N. Borenstein, RFC2045, Section 6.8 for a description of why this check is necessary. Assert.Equal(3, result.Length); uint triplet = (uint)((result[0] << 16) | (result[1] << 8) | result[2]); Assert.Equal<uint>(45, triplet >> 18); // 't' Assert.Equal<uint>(30, (triplet << 14) >> 26); // 'e' Assert.Equal<uint>(44, (triplet << 20) >> 26); // 's' Assert.Equal<uint>(45, (triplet << 26) >> 26); // 't' Assert.Equal(input, Convert.ToBase64String(result)); }); } [Fact] public static void Roundtrip2() { VerifyRoundtrip("AAAA"); } [Fact] public static void Roundtrip3() { VerifyRoundtrip("AAAAAAAA"); } [Fact] public static void EmptyString() { string input = string.Empty; Verify(input, result => { Assert.NotNull(result); Assert.Equal(0, result.Length); }); } [Fact] public static void ZeroLengthArray() { string input = "test"; char[] inputChars = input.ToCharArray(); byte[] result = Convert.FromBase64CharArray(inputChars, 0, 0); Assert.NotNull(result); Assert.Equal(0, result.Length); } [Fact] public static void RoundtripWithPadding1() { VerifyRoundtrip("abc="); } [Fact] public static void RoundtripWithPadding2() { VerifyRoundtrip("BQYHCA=="); } [Fact] public static void PartialRoundtripWithPadding1() { string input = "ab=="; Verify(input, result => { Assert.Equal(1, result.Length); string roundtrippedString = Convert.ToBase64String(result); Assert.NotEqual(input, roundtrippedString); Assert.Equal(input[0], roundtrippedString[0]); }); } [Fact] public static void PartialRoundtripWithPadding2() { string input = "789="; Verify(input, result => { Assert.Equal(2, result.Length); string roundtrippedString = Convert.ToBase64String(result); Assert.NotEqual(input, roundtrippedString); Assert.Equal(input[0], roundtrippedString[0]); Assert.Equal(input[1], roundtrippedString[1]); }); } [Fact] public static void ParseWithWhitespace() { Verify("abc= \t \r\n ="); } [Fact] public static void RoundtripWithWhitespace2() { string input = "abc= \t\n\t\r "; VerifyRoundtrip(input, input.Trim()); } [Fact] public static void RoundtripWithWhitespace3() { string input = "abc \r\n\t = \t\n\t\r "; VerifyRoundtrip(input, "abc="); } [Fact] public static void RoundtripWithWhitespace4() { string expected = "test"; string input = expected.Insert(1, new string(' ', 17)).PadLeft(31, ' ').PadRight(12, ' '); VerifyRoundtrip(input, expected, expectedLengthBytes: 3); } [Fact] public static void RoundtripWithWhitespace5() { string expected = "test"; string input = expected.Insert(2, new string('\t', 9)).PadLeft(37, '\t').PadRight(8, '\t'); VerifyRoundtrip(input, expected, expectedLengthBytes: 3); } [Fact] public static void RoundtripWithWhitespace6() { string expected = "test"; string input = expected.Insert(2, new string('\r', 13)).PadLeft(7, '\r').PadRight(29, '\r'); VerifyRoundtrip(input, expected, expectedLengthBytes: 3); } [Fact] public static void RoundtripWithWhitespace7() { string expected = "test"; string input = expected.Insert(2, new string('\n', 23)).PadLeft(17, '\n').PadRight(34, '\n'); VerifyRoundtrip(input, expected, expectedLengthBytes: 3); } [Fact] public static void RoundtripLargeString() { string input = new string('a', 10000); VerifyRoundtrip(input, input); } [Fact] public static void InvalidOffset() { string input = "test"; char[] inputChars = input.ToCharArray(); Assert.Throws<ArgumentOutOfRangeException>(() => Convert.FromBase64CharArray(inputChars, -1, inputChars.Length)); Assert.Throws<ArgumentOutOfRangeException>(() => Convert.FromBase64CharArray(inputChars, inputChars.Length, inputChars.Length)); } [Fact] public static void InvalidLength() { string input = "test"; char[] inputChars = input.ToCharArray(); Assert.Throws<ArgumentOutOfRangeException>(() => Convert.FromBase64CharArray(inputChars, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Convert.FromBase64CharArray(inputChars, 0, inputChars.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => Convert.FromBase64CharArray(inputChars, 1, inputChars.Length)); } [Fact] public static void InvalidInput() { Assert.Throws<ArgumentNullException>(() => Convert.FromBase64CharArray(null, 0, 3)); // Input must be at least 4 characters long VerifyInvalidInput("No"); // Length of input must be a multiple of 4 VerifyInvalidInput("NoMore"); // Input must not contain invalid characters VerifyInvalidInput("2-34"); // Input must not contain 3 or more padding characters in a row VerifyInvalidInput("a==="); VerifyInvalidInput("abc====="); VerifyInvalidInput("a===\r \t \n"); // Input must not contain padding characters in the middle of the string VerifyInvalidInput("No=n"); VerifyInvalidInput("abcdabc=abcd"); VerifyInvalidInput("abcdab==abcd"); VerifyInvalidInput("abcda===abcd"); VerifyInvalidInput("abcd====abcd"); // Input must not contain extra trailing padding characters VerifyInvalidInput("="); VerifyInvalidInput("abc==="); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void ExtraPaddingCharacter() { VerifyInvalidInput("abcdxyz=" + "="); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] public static void ExtraPaddingCharacterOnNetFx() { // This should throw a FormatException because of the extra "=". But due to a bug in NetFx, this // gets "successfully" decoded as if it were "abcdyz==". byte[] actual = Convert.FromBase64String("abcdxyz=" + "="); byte[] expected = { 0x69, 0xb7, 0x1d, 0xcb }; Assert.Equal<byte>(expected, actual); } [Fact] public static void InvalidCharactersInInput() { ushort[] invalidChars = { 30122, 62608, 13917, 19498, 2473, 40845, 35988, 2281, 51246, 36372 }; foreach (char ch in invalidChars) { var builder = new StringBuilder("abc"); builder.Insert(1, ch); VerifyInvalidInput(builder.ToString()); } } private static void VerifyRoundtrip(string input, string expected = null, int? expectedLengthBytes = null) { if (expected == null) { expected = input; } Verify(input, result => { if (expectedLengthBytes.HasValue) { Assert.Equal(expectedLengthBytes.Value, result.Length); } Assert.Equal(expected, Convert.ToBase64String(result)); Assert.Equal(expected, Convert.ToBase64String(result, 0, result.Length)); }); } private static void VerifyInvalidInput(string input) { char[] inputChars = input.ToCharArray(); Assert.Throws<FormatException>(() => Convert.FromBase64CharArray(inputChars, 0, inputChars.Length)); Assert.Throws<FormatException>(() => Convert.FromBase64String(input)); } private static void Verify(string input, Action<byte[]> action = null) { if (action != null) { action(Convert.FromBase64CharArray(input.ToCharArray(), 0, input.Length)); action(Convert.FromBase64String(input)); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace lust.website.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoad.Business.ERCLevel { /// <summary> /// B01Level1Coll (editable root list).<br/> /// This is a generated base class of <see cref="B01Level1Coll"/> business object. /// </summary> /// <remarks> /// The items of the collection are <see cref="B02Level1"/> objects. /// </remarks> [Serializable] public partial class B01Level1Coll : BusinessListBase<B01Level1Coll, B02Level1> { #region Collection Business Methods /// <summary> /// Removes a <see cref="B02Level1"/> item from the collection. /// </summary> /// <param name="level_1_ID">The Level_1_ID of the item to be removed.</param> public void Remove(int level_1_ID) { foreach (var b02Level1 in this) { if (b02Level1.Level_1_ID == level_1_ID) { Remove(b02Level1); break; } } } /// <summary> /// Determines whether a <see cref="B02Level1"/> item is in the collection. /// </summary> /// <param name="level_1_ID">The Level_1_ID of the item to search for.</param> /// <returns><c>true</c> if the B02Level1 is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int level_1_ID) { foreach (var b02Level1 in this) { if (b02Level1.Level_1_ID == level_1_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="B02Level1"/> item is in the collection's DeletedList. /// </summary> /// <param name="level_1_ID">The Level_1_ID of the item to search for.</param> /// <returns><c>true</c> if the B02Level1 is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int level_1_ID) { foreach (var b02Level1 in this.DeletedList) { if (b02Level1.Level_1_ID == level_1_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="B02Level1"/> item of the <see cref="B01Level1Coll"/> collection, based on item key properties. /// </summary> /// <param name="level_1_ID">The Level_1_ID.</param> /// <returns>A <see cref="B02Level1"/> object.</returns> public B02Level1 FindB02Level1ByParentProperties(int level_1_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].Level_1_ID.Equals(level_1_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="B01Level1Coll"/> collection. /// </summary> /// <returns>A reference to the created <see cref="B01Level1Coll"/> collection.</returns> public static B01Level1Coll NewB01Level1Coll() { return DataPortal.Create<B01Level1Coll>(); } /// <summary> /// Factory method. Loads a <see cref="B01Level1Coll"/> object. /// </summary> /// <returns>A reference to the fetched <see cref="B01Level1Coll"/> object.</returns> public static B01Level1Coll GetB01Level1Coll() { return DataPortal.Fetch<B01Level1Coll>(); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="B01Level1Coll"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private B01Level1Coll() { // Prevent direct creation var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="B01Level1Coll"/> collection from the database. /// </summary> protected void DataPortal_Fetch() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetB01Level1Coll", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; var args = new DataPortalHookArgs(cmd); OnFetchPre(args); LoadCollection(cmd); OnFetchPost(args); } } } private void LoadCollection(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { Fetch(dr); if (this.Count > 0) this[0].FetchChildren(dr); } } /// <summary> /// Loads all <see cref="B01Level1Coll"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(B02Level1.GetB02Level1(dr)); } RaiseListChangedEvents = rlce; } /// <summary> /// Updates in the database all changes made to the <see cref="B01Level1Coll"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { base.Child_Update(); } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion } }
// 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.Threading { public partial class AbandonedMutexException : System.SystemException { public AbandonedMutexException() { } public AbandonedMutexException(int location, System.Threading.WaitHandle handle) { } protected AbandonedMutexException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public AbandonedMutexException(string message) { } public AbandonedMutexException(string message, System.Exception inner) { } public AbandonedMutexException(string message, System.Exception inner, int location, System.Threading.WaitHandle handle) { } public AbandonedMutexException(string message, int location, System.Threading.WaitHandle handle) { } public System.Threading.Mutex Mutex { get { throw null; } } public int MutexIndex { get { throw null; } } } public partial struct AsyncFlowControl : System.IDisposable { private object _dummy; public void Dispose() { } public override bool Equals(object obj) { throw null; } public bool Equals(System.Threading.AsyncFlowControl obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Threading.AsyncFlowControl a, System.Threading.AsyncFlowControl b) { throw null; } public static bool operator !=(System.Threading.AsyncFlowControl a, System.Threading.AsyncFlowControl b) { throw null; } public void Undo() { } } public readonly partial struct AsyncLocalValueChangedArgs<T> { private readonly T _dummy; private readonly int _dummyPrimitive; public T CurrentValue { get { throw null; } } public T PreviousValue { get { throw null; } } public bool ThreadContextChanged { get { throw null; } } } public sealed partial class AsyncLocal<T> { public AsyncLocal() { } public AsyncLocal(System.Action<System.Threading.AsyncLocalValueChangedArgs<T>> valueChangedHandler) { } public T Value { get { throw null; } set { } } } public sealed partial class AutoResetEvent : System.Threading.EventWaitHandle { public AutoResetEvent(bool initialState) : base (default(bool), default(System.Threading.EventResetMode)) { } } public partial class Barrier : System.IDisposable { public Barrier(int participantCount) { } public Barrier(int participantCount, System.Action<System.Threading.Barrier> postPhaseAction) { } public long CurrentPhaseNumber { get { throw null; } } public int ParticipantCount { get { throw null; } } public int ParticipantsRemaining { get { throw null; } } public long AddParticipant() { throw null; } public long AddParticipants(int participantCount) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void RemoveParticipant() { } public void RemoveParticipants(int participantCount) { } public void SignalAndWait() { } public bool SignalAndWait(int millisecondsTimeout) { throw null; } public bool SignalAndWait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public void SignalAndWait(System.Threading.CancellationToken cancellationToken) { } public bool SignalAndWait(System.TimeSpan timeout) { throw null; } public bool SignalAndWait(System.TimeSpan timeout, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class BarrierPostPhaseException : System.Exception { public BarrierPostPhaseException() { } public BarrierPostPhaseException(System.Exception innerException) { } protected BarrierPostPhaseException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public BarrierPostPhaseException(string message) { } public BarrierPostPhaseException(string message, System.Exception innerException) { } } public delegate void ContextCallback(object state); public partial class CountdownEvent : System.IDisposable { public CountdownEvent(int initialCount) { } public int CurrentCount { get { throw null; } } public int InitialCount { get { throw null; } } public bool IsSet { get { throw null; } } public System.Threading.WaitHandle WaitHandle { get { throw null; } } public void AddCount() { } public void AddCount(int signalCount) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void Reset() { } public void Reset(int count) { } public bool Signal() { throw null; } public bool Signal(int signalCount) { throw null; } public bool TryAddCount() { throw null; } public bool TryAddCount(int signalCount) { throw null; } public void Wait() { } public bool Wait(int millisecondsTimeout) { throw null; } public bool Wait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public void Wait(System.Threading.CancellationToken cancellationToken) { } public bool Wait(System.TimeSpan timeout) { throw null; } public bool Wait(System.TimeSpan timeout, System.Threading.CancellationToken cancellationToken) { throw null; } } public enum EventResetMode { AutoReset = 0, ManualReset = 1, } public partial class EventWaitHandle : System.Threading.WaitHandle { public EventWaitHandle(bool initialState, System.Threading.EventResetMode mode) { } public EventWaitHandle(bool initialState, System.Threading.EventResetMode mode, string name) { } public EventWaitHandle(bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew) { throw null; } public static System.Threading.EventWaitHandle OpenExisting(string name) { throw null; } public bool Reset() { throw null; } public bool Set() { throw null; } public static bool TryOpenExisting(string name, out System.Threading.EventWaitHandle result) { throw null; } } public sealed partial class ExecutionContext : System.IDisposable, System.Runtime.Serialization.ISerializable { internal ExecutionContext() { } public static System.Threading.ExecutionContext Capture() { throw null; } public System.Threading.ExecutionContext CreateCopy() { throw null; } public void Dispose() { } public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public static bool IsFlowSuppressed() { throw null; } public static void RestoreFlow() { } public static void Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) { } public static System.Threading.AsyncFlowControl SuppressFlow() { throw null; } } public partial class HostExecutionContext : System.IDisposable { public HostExecutionContext() { } public HostExecutionContext(object state) { } protected internal object State { get { throw null; } set { } } public virtual System.Threading.HostExecutionContext CreateCopy() { throw null; } public void Dispose() { } public virtual void Dispose(bool disposing) { } } public partial class HostExecutionContextManager { public HostExecutionContextManager() { } public virtual System.Threading.HostExecutionContext Capture() { throw null; } public virtual void Revert(object previousState) { } public virtual object SetHostExecutionContext(System.Threading.HostExecutionContext hostExecutionContext) { throw null; } } public static partial class Interlocked { public static int Add(ref int location1, int value) { throw null; } public static long Add(ref long location1, long value) { throw null; } public static double CompareExchange(ref double location1, double value, double comparand) { throw null; } public static int CompareExchange(ref int location1, int value, int comparand) { throw null; } public static long CompareExchange(ref long location1, long value, long comparand) { throw null; } public static System.IntPtr CompareExchange(ref System.IntPtr location1, System.IntPtr value, System.IntPtr comparand) { throw null; } public static object CompareExchange(ref object location1, object value, object comparand) { throw null; } public static float CompareExchange(ref float location1, float value, float comparand) { throw null; } public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class { throw null; } public static int Decrement(ref int location) { throw null; } public static long Decrement(ref long location) { throw null; } public static double Exchange(ref double location1, double value) { throw null; } public static int Exchange(ref int location1, int value) { throw null; } public static long Exchange(ref long location1, long value) { throw null; } public static System.IntPtr Exchange(ref System.IntPtr location1, System.IntPtr value) { throw null; } public static object Exchange(ref object location1, object value) { throw null; } public static float Exchange(ref float location1, float value) { throw null; } public static T Exchange<T>(ref T location1, T value) where T : class { throw null; } public static int Increment(ref int location) { throw null; } public static long Increment(ref long location) { throw null; } public static void MemoryBarrier() { } public static void MemoryBarrierProcessWide() { } public static long Read(ref long location) { throw null; } } public static partial class LazyInitializer { public static T EnsureInitialized<T>(ref T target) where T : class { throw null; } public static T EnsureInitialized<T>(ref T target, ref bool initialized, ref object syncLock) { throw null; } public static T EnsureInitialized<T>(ref T target, ref bool initialized, ref object syncLock, System.Func<T> valueFactory) { throw null; } public static T EnsureInitialized<T>(ref T target, System.Func<T> valueFactory) where T : class { throw null; } public static T EnsureInitialized<T>(ref T target, ref object syncLock, System.Func<T> valueFactory) where T : class { throw null; } } public partial struct LockCookie { private int _dummyPrimitive; public override bool Equals(object obj) { throw null; } public bool Equals(System.Threading.LockCookie obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Threading.LockCookie a, System.Threading.LockCookie b) { throw null; } public static bool operator !=(System.Threading.LockCookie a, System.Threading.LockCookie b) { throw null; } } public partial class LockRecursionException : System.Exception { public LockRecursionException() { } protected LockRecursionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public LockRecursionException(string message) { } public LockRecursionException(string message, System.Exception innerException) { } } public enum LockRecursionPolicy { NoRecursion = 0, SupportsRecursion = 1, } public sealed partial class ManualResetEvent : System.Threading.EventWaitHandle { public ManualResetEvent(bool initialState) : base (default(bool), default(System.Threading.EventResetMode)) { } } public partial class ManualResetEventSlim : System.IDisposable { public ManualResetEventSlim() { } public ManualResetEventSlim(bool initialState) { } public ManualResetEventSlim(bool initialState, int spinCount) { } public bool IsSet { get { throw null; } } public int SpinCount { get { throw null; } } public System.Threading.WaitHandle WaitHandle { get { throw null; } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void Reset() { } public void Set() { } public void Wait() { } public bool Wait(int millisecondsTimeout) { throw null; } public bool Wait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public void Wait(System.Threading.CancellationToken cancellationToken) { } public bool Wait(System.TimeSpan timeout) { throw null; } public bool Wait(System.TimeSpan timeout, System.Threading.CancellationToken cancellationToken) { throw null; } } public static partial class Monitor { public static void Enter(object obj) { } public static void Enter(object obj, ref bool lockTaken) { } public static void Exit(object obj) { } public static bool IsEntered(object obj) { throw null; } public static void Pulse(object obj) { } public static void PulseAll(object obj) { } public static bool TryEnter(object obj) { throw null; } public static void TryEnter(object obj, ref bool lockTaken) { } public static bool TryEnter(object obj, int millisecondsTimeout) { throw null; } public static void TryEnter(object obj, int millisecondsTimeout, ref bool lockTaken) { } public static bool TryEnter(object obj, System.TimeSpan timeout) { throw null; } public static void TryEnter(object obj, System.TimeSpan timeout, ref bool lockTaken) { } public static bool Wait(object obj) { throw null; } public static bool Wait(object obj, int millisecondsTimeout) { throw null; } public static bool Wait(object obj, int millisecondsTimeout, bool exitContext) { throw null; } public static bool Wait(object obj, System.TimeSpan timeout) { throw null; } public static bool Wait(object obj, System.TimeSpan timeout, bool exitContext) { throw null; } } public sealed partial class Mutex : System.Threading.WaitHandle { public Mutex() { } public Mutex(bool initiallyOwned) { } public Mutex(bool initiallyOwned, string name) { } public Mutex(bool initiallyOwned, string name, out bool createdNew) { throw null; } public static System.Threading.Mutex OpenExisting(string name) { throw null; } public void ReleaseMutex() { } public static bool TryOpenExisting(string name, out System.Threading.Mutex result) { throw null; } } public sealed partial class ReaderWriterLock : System.Runtime.ConstrainedExecution.CriticalFinalizerObject { public ReaderWriterLock() { } public bool IsReaderLockHeld { get { throw null; } } public bool IsWriterLockHeld { get { throw null; } } public int WriterSeqNum { get { throw null; } } public void AcquireReaderLock(int millisecondsTimeout) { } public void AcquireReaderLock(System.TimeSpan timeout) { } public void AcquireWriterLock(int millisecondsTimeout) { } public void AcquireWriterLock(System.TimeSpan timeout) { } public bool AnyWritersSince(int seqNum) { throw null; } public void DowngradeFromWriterLock(ref System.Threading.LockCookie lockCookie) { } ~ReaderWriterLock() { } public System.Threading.LockCookie ReleaseLock() { throw null; } public void ReleaseReaderLock() { } public void ReleaseWriterLock() { } public void RestoreLock(ref System.Threading.LockCookie lockCookie) { } public System.Threading.LockCookie UpgradeToWriterLock(int millisecondsTimeout) { throw null; } public System.Threading.LockCookie UpgradeToWriterLock(System.TimeSpan timeout) { throw null; } } public partial class ReaderWriterLockSlim : System.IDisposable { public ReaderWriterLockSlim() { } public ReaderWriterLockSlim(System.Threading.LockRecursionPolicy recursionPolicy) { } public int CurrentReadCount { get { throw null; } } public bool IsReadLockHeld { get { throw null; } } public bool IsUpgradeableReadLockHeld { get { throw null; } } public bool IsWriteLockHeld { get { throw null; } } public System.Threading.LockRecursionPolicy RecursionPolicy { get { throw null; } } public int RecursiveReadCount { get { throw null; } } public int RecursiveUpgradeCount { get { throw null; } } public int RecursiveWriteCount { get { throw null; } } public int WaitingReadCount { get { throw null; } } public int WaitingUpgradeCount { get { throw null; } } public int WaitingWriteCount { get { throw null; } } public void Dispose() { } public void EnterReadLock() { } public void EnterUpgradeableReadLock() { } public void EnterWriteLock() { } public void ExitReadLock() { } public void ExitUpgradeableReadLock() { } public void ExitWriteLock() { } public bool TryEnterReadLock(int millisecondsTimeout) { throw null; } public bool TryEnterReadLock(System.TimeSpan timeout) { throw null; } public bool TryEnterUpgradeableReadLock(int millisecondsTimeout) { throw null; } public bool TryEnterUpgradeableReadLock(System.TimeSpan timeout) { throw null; } public bool TryEnterWriteLock(int millisecondsTimeout) { throw null; } public bool TryEnterWriteLock(System.TimeSpan timeout) { throw null; } } public sealed partial class Semaphore : System.Threading.WaitHandle { public Semaphore(int initialCount, int maximumCount) { } public Semaphore(int initialCount, int maximumCount, string name) { } public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew) { throw null; } public static System.Threading.Semaphore OpenExisting(string name) { throw null; } public int Release() { throw null; } public int Release(int releaseCount) { throw null; } public static bool TryOpenExisting(string name, out System.Threading.Semaphore result) { throw null; } } public partial class SemaphoreFullException : System.SystemException { public SemaphoreFullException() { } protected SemaphoreFullException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public SemaphoreFullException(string message) { } public SemaphoreFullException(string message, System.Exception innerException) { } } public partial class SemaphoreSlim : System.IDisposable { public SemaphoreSlim(int initialCount) { } public SemaphoreSlim(int initialCount, int maxCount) { } public System.Threading.WaitHandle AvailableWaitHandle { get { throw null; } } public int CurrentCount { get { throw null; } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public int Release() { throw null; } public int Release(int releaseCount) { throw null; } public void Wait() { } public bool Wait(int millisecondsTimeout) { throw null; } public bool Wait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public void Wait(System.Threading.CancellationToken cancellationToken) { } public bool Wait(System.TimeSpan timeout) { throw null; } public bool Wait(System.TimeSpan timeout, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task WaitAsync() { throw null; } public System.Threading.Tasks.Task<bool> WaitAsync(int millisecondsTimeout) { throw null; } public System.Threading.Tasks.Task<bool> WaitAsync(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task WaitAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<bool> WaitAsync(System.TimeSpan timeout) { throw null; } public System.Threading.Tasks.Task<bool> WaitAsync(System.TimeSpan timeout, System.Threading.CancellationToken cancellationToken) { throw null; } } public delegate void SendOrPostCallback(object state); public partial struct SpinLock { private int _dummyPrimitive; public SpinLock(bool enableThreadOwnerTracking) { throw null; } public bool IsHeld { get { throw null; } } public bool IsHeldByCurrentThread { get { throw null; } } public bool IsThreadOwnerTrackingEnabled { get { throw null; } } public void Enter(ref bool lockTaken) { } public void Exit() { } public void Exit(bool useMemoryBarrier) { } public void TryEnter(ref bool lockTaken) { } public void TryEnter(int millisecondsTimeout, ref bool lockTaken) { } public void TryEnter(System.TimeSpan timeout, ref bool lockTaken) { } } public partial struct SpinWait { private int _dummyPrimitive; public int Count { get { throw null; } } public bool NextSpinWillYield { get { throw null; } } public void Reset() { } public void SpinOnce() { } public void SpinOnce(int sleep1Threshold) { } public static void SpinUntil(System.Func<bool> condition) { } public static bool SpinUntil(System.Func<bool> condition, int millisecondsTimeout) { throw null; } public static bool SpinUntil(System.Func<bool> condition, System.TimeSpan timeout) { throw null; } } public partial class SynchronizationContext { public SynchronizationContext() { } public static System.Threading.SynchronizationContext Current { get { throw null; } } public virtual System.Threading.SynchronizationContext CreateCopy() { throw null; } public bool IsWaitNotificationRequired() { throw null; } public virtual void OperationCompleted() { } public virtual void OperationStarted() { } public virtual void Post(System.Threading.SendOrPostCallback d, object state) { } public virtual void Send(System.Threading.SendOrPostCallback d, object state) { } public static void SetSynchronizationContext(System.Threading.SynchronizationContext syncContext) { } protected void SetWaitNotificationRequired() { } [System.CLSCompliantAttribute(false)] [System.Runtime.ConstrainedExecution.PrePrepareMethodAttribute] public virtual int Wait(System.IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { throw null; } [System.CLSCompliantAttribute(false)] [System.Runtime.ConstrainedExecution.PrePrepareMethodAttribute] protected static int WaitHelper(System.IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { throw null; } } public partial class SynchronizationLockException : System.SystemException { public SynchronizationLockException() { } protected SynchronizationLockException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public SynchronizationLockException(string message) { } public SynchronizationLockException(string message, System.Exception innerException) { } } public partial class ThreadLocal<T> : System.IDisposable { public ThreadLocal() { } public ThreadLocal(bool trackAllValues) { } public ThreadLocal(System.Func<T> valueFactory) { } public ThreadLocal(System.Func<T> valueFactory, bool trackAllValues) { } public bool IsValueCreated { get { throw null; } } public T Value { get { throw null; } set { } } public System.Collections.Generic.IList<T> Values { get { throw null; } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } ~ThreadLocal() { } public override string ToString() { throw null; } } public static partial class Volatile { public static bool Read(ref bool location) { throw null; } public static byte Read(ref byte location) { throw null; } public static double Read(ref double location) { throw null; } public static short Read(ref short location) { throw null; } public static int Read(ref int location) { throw null; } public static long Read(ref long location) { throw null; } public static System.IntPtr Read(ref System.IntPtr location) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte Read(ref sbyte location) { throw null; } public static float Read(ref float location) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort Read(ref ushort location) { throw null; } [System.CLSCompliantAttribute(false)] public static uint Read(ref uint location) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong Read(ref ulong location) { throw null; } [System.CLSCompliantAttribute(false)] public static System.UIntPtr Read(ref System.UIntPtr location) { throw null; } public static T Read<T>(ref T location) where T : class { throw null; } public static void Write(ref bool location, bool value) { } public static void Write(ref byte location, byte value) { } public static void Write(ref double location, double value) { } public static void Write(ref short location, short value) { } public static void Write(ref int location, int value) { } public static void Write(ref long location, long value) { } public static void Write(ref System.IntPtr location, System.IntPtr value) { } [System.CLSCompliantAttribute(false)] public static void Write(ref sbyte location, sbyte value) { } public static void Write(ref float location, float value) { } [System.CLSCompliantAttribute(false)] public static void Write(ref ushort location, ushort value) { } [System.CLSCompliantAttribute(false)] public static void Write(ref uint location, uint value) { } [System.CLSCompliantAttribute(false)] public static void Write(ref ulong location, ulong value) { } [System.CLSCompliantAttribute(false)] public static void Write(ref System.UIntPtr location, System.UIntPtr value) { } public static void Write<T>(ref T location, T value) where T : class { } } public partial class WaitHandleCannotBeOpenedException : System.ApplicationException { public WaitHandleCannotBeOpenedException() { } protected WaitHandleCannotBeOpenedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public WaitHandleCannotBeOpenedException(string message) { } public WaitHandleCannotBeOpenedException(string message, System.Exception innerException) { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using DeOps.Implementation.Dht; using DeOps.Implementation.Transport; using DeOps.Implementation.Protocol; namespace DeOps.Implementation.Protocol.Net { public class DhtClient { public ulong UserID; public ushort ClientID; // RoutingID: slightly mod the user's lower bits so that dhtid is unique (max 64k uniques) // needed so that 1000 of the same user are online, the routing table still works // high/low/xor cache area is still fair and balanced public ulong RoutingID { get { return UserID ^ ClientID; } } public DhtClient() { } public DhtClient(DhtClient copy) { UserID = copy.UserID; ClientID = copy.ClientID; } public DhtClient(ulong dht, ushort client) { UserID = dht; ClientID = client; } public byte[] ToBytes() { byte[] bytes = new byte[10]; BitConverter.GetBytes(UserID).CopyTo(bytes, 0); BitConverter.GetBytes(ClientID).CopyTo(bytes, 8); return bytes; } public static DhtClient FromBytes(byte[] data, int start) { DhtClient result = new DhtClient(); result.UserID = BitConverter.ToUInt64(data, start); result.ClientID = BitConverter.ToUInt16(data, start + 8); return result; } public override bool Equals(object obj) { DhtClient compare = obj as DhtClient; if (compare == null) return false ; return UserID == compare.UserID && ClientID == compare.ClientID; } public override int GetHashCode() { return UserID.GetHashCode() ^ ClientID.GetHashCode(); } } public class TunnelAddress : DhtClient { public ushort TunnelID; public TunnelAddress() { } public TunnelAddress(DhtClient client, ushort id) { UserID = client.UserID; ClientID = client.ClientID; TunnelID = id; } public new byte[] ToBytes() { byte[] bytes = new byte[12]; BitConverter.GetBytes(UserID).CopyTo(bytes, 0); BitConverter.GetBytes(ClientID).CopyTo(bytes, 8); BitConverter.GetBytes(TunnelID).CopyTo(bytes, 10); return bytes; } public new static TunnelAddress FromBytes(byte[] data, int start) { TunnelAddress result = new TunnelAddress(); result.UserID = BitConverter.ToUInt64(data, start); result.ClientID = BitConverter.ToUInt16(data, start + 8); result.TunnelID = BitConverter.ToUInt16(data, start + 10); return result; } public override string ToString() { return UserID + ":" + ClientID + ":" + TunnelID; } } public class DhtSource : DhtClient { public const int PAYLOAD_SIZE = 15; public ushort TcpPort; public ushort UdpPort; public FirewallType Firewall; public DhtSource() { } public DhtSource(DhtAddress address) { } public void WritePacket(G2Protocol protocol, G2Frame root, byte name) { byte[] payload = new byte[PAYLOAD_SIZE]; BitConverter.GetBytes(UserID).CopyTo(payload, 0); BitConverter.GetBytes(ClientID).CopyTo(payload, 8); BitConverter.GetBytes(TcpPort).CopyTo(payload, 10); BitConverter.GetBytes(UdpPort).CopyTo(payload, 12); payload[14] = (byte)Firewall; G2Frame source = protocol.WritePacket(root, name, payload); } public static DhtSource ReadPacket(G2Header root) { // read payload DhtSource source = new DhtSource(); source.UserID = BitConverter.ToUInt64(root.Data, root.PayloadPos); source.ClientID = BitConverter.ToUInt16(root.Data, root.PayloadPos + 8); source.TcpPort = BitConverter.ToUInt16(root.Data, root.PayloadPos + 10); source.UdpPort = BitConverter.ToUInt16(root.Data, root.PayloadPos + 12); source.Firewall = (FirewallType)root.Data[root.PayloadPos + 14]; // read packets G2Protocol.ResetPacket(root); return source; } } public class DhtAddress : DhtClient { public const int PAYLOAD_SIZE = 12; const byte Packet_IP = 0x01; public IPAddress IP; public ushort UdpPort; public DhtAddress TunnelServer; public TunnelAddress TunnelClient; public DhtAddress() { } public DhtAddress(ulong user, ushort client, IPAddress ip, ushort port) { UserID = user; ClientID = client; IP = ip; UdpPort = port; } public DhtAddress(IPAddress ip, DhtSource source) { UserID = source.UserID; ClientID = source.ClientID; IP = ip; UdpPort = source.UdpPort; } public IPEndPoint ToEndPoint() { return new IPEndPoint(IP, UdpPort); } public void WritePacket(G2Protocol protocol, G2Frame root, byte name) { byte[] payload = new byte[PAYLOAD_SIZE]; BitConverter.GetBytes(UserID).CopyTo(payload, 0); BitConverter.GetBytes(ClientID).CopyTo(payload, 8); BitConverter.GetBytes(UdpPort).CopyTo(payload, 10); G2Frame address = protocol.WritePacket(root, name, payload); protocol.WritePacket(address, Packet_IP, IP.GetAddressBytes()); } public static DhtAddress ReadPacket(G2Header root) { // read payload DhtAddress address = new DhtAddress(); address.UserID = BitConverter.ToUInt64(root.Data, root.PayloadPos); address.ClientID = BitConverter.ToUInt16(root.Data, root.PayloadPos + 8); address.UdpPort = BitConverter.ToUInt16(root.Data, root.PayloadPos + 10); // read packets G2Protocol.ResetPacket(root); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_IP: address.IP = new IPAddress(Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize)); break; } } return address; } public override bool Equals(object obj) { DhtAddress check = obj as DhtAddress; if (check == null) return false; if (UserID == check.UserID && ClientID == check.ClientID && IP.Equals(check.IP) && UdpPort == check.UdpPort) return true; return false; } public int CacheHash() { return UserID.GetHashCode() ^ IP.GetHashCode() ^ UdpPort.GetHashCode(); } public override int GetHashCode() { int hash = UserID.GetHashCode() ^ ClientID.GetHashCode() ^ IP.GetHashCode() ^ UdpPort.GetHashCode(); if (TunnelClient != null) hash = hash ^ TunnelClient.GetHashCode(); if (TunnelServer != null) hash = hash ^ TunnelServer.GetHashCode(); return hash; } public override string ToString() { return IP.ToString() + ":" + ClientID.ToString() + ":" + UdpPort.ToString() + ":" + Utilities.IDtoBin(UserID).Substring(0, 10); } } public class NetworkPacket : G2Packet { const byte Packet_SourceID = 0x01; const byte Packet_ClientID = 0x02; const byte Packet_To = 0x03; const byte Packet_From = 0x04; // public packet types public const byte SearchRequest = 0x10; public const byte SearchAck = 0x20; public const byte StoreRequest = 0x30; public const byte Ping = 0x40; public const byte Pong = 0x50; public const byte Bye = 0x60; public const byte ProxyRequest = 0x70; public const byte ProxyAck = 0x80; public const byte CrawlRequest = 0x90; public const byte CrawlAck = 0xA0; public ulong SourceID; public ushort ClientID; public DhtAddress ToAddress; public DhtAddress FromAddress; public byte[] InternalData; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame gn = protocol.WritePacket(null, RootPacket.Network, InternalData); protocol.WritePacket(gn, Packet_SourceID, BitConverter.GetBytes(SourceID)); protocol.WritePacket(gn, Packet_ClientID, BitConverter.GetBytes(ClientID)); if (ToAddress != null) ToAddress.WritePacket(protocol, gn, Packet_To); if (FromAddress != null) FromAddress.WritePacket(protocol, gn, Packet_From); return protocol.WriteFinish(); } } public static NetworkPacket Decode(G2Header root) { NetworkPacket gn = new NetworkPacket(); if (G2Protocol.ReadPayload(root)) gn.InternalData = Utilities.ExtractBytes(root.Data, root.PayloadPos, root.PayloadSize); G2Protocol.ResetPacket(root); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_SourceID: gn.SourceID = BitConverter.ToUInt64(child.Data, child.PayloadPos); break; case Packet_ClientID: gn.ClientID = BitConverter.ToUInt16(child.Data, child.PayloadPos); break; case Packet_To: gn.ToAddress = DhtAddress.ReadPacket(child); break; case Packet_From: gn.FromAddress = DhtAddress.ReadPacket(child); break; } } return gn; } } public class SearchReq : NetworkPacket { const byte Packet_Source = 0x10; const byte Packet_Nodes = 0x20; const byte Packet_SearchID = 0x30; const byte Packet_Target = 0x40; const byte Packet_Service = 0x50; const byte Packet_DataType = 0x60; const byte Packet_Parameters = 0x70; const byte Packet_EndSearch = 0x80; public DhtSource Source = new DhtSource(); public bool Nodes = true; public uint SearchID; public UInt64 TargetID; public uint Service; public uint DataType; public byte[] Parameters; public bool EndProxySearch; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame req = protocol.WritePacket(null, NetworkPacket.SearchRequest, null); Source.WritePacket(protocol, req, Packet_Source); protocol.WritePacket(req, Packet_Nodes, BitConverter.GetBytes(Nodes)); protocol.WritePacket(req, Packet_SearchID, BitConverter.GetBytes(SearchID)); protocol.WritePacket(req, Packet_Target, BitConverter.GetBytes(TargetID)); protocol.WritePacket(req, Packet_Service, CompactNum.GetBytes(Service)); protocol.WritePacket(req, Packet_DataType, CompactNum.GetBytes(DataType)); protocol.WritePacket(req, Packet_Parameters, Parameters); if (EndProxySearch) protocol.WritePacket(req, Packet_EndSearch, BitConverter.GetBytes(true)); InternalData = protocol.WriteFinish(); return base.Encode(protocol); } } public static SearchReq Decode(G2ReceivedPacket packet) { SearchReq req = new SearchReq(); G2Header child = new G2Header(packet.Root.Data); while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD ) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Source: req.Source = DhtSource.ReadPacket(child); break; case Packet_SearchID: req.SearchID = BitConverter.ToUInt32(child.Data, child.PayloadPos); break; case Packet_Target: req.TargetID = BitConverter.ToUInt64(child.Data, child.PayloadPos); break; case Packet_Service: req.Service = CompactNum.ToUInt32(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_DataType: req.DataType = CompactNum.ToUInt32(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_Parameters: req.Parameters = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_Nodes: req.Nodes = BitConverter.ToBoolean(child.Data, child.PayloadPos); break; case Packet_EndSearch: req.EndProxySearch = true; break; } } return req; } } public class SearchAck : NetworkPacket { const byte Packet_Source = 0x10; const byte Packet_SearchID = 0x20; const byte Packet_Proxied = 0x30; const byte Packet_Contacts = 0x40; const byte Packet_Values = 0x50; const byte Packet_Service = 0x60; public DhtSource Source = new DhtSource(); public uint SearchID; public bool Proxied; public uint Service; public List<DhtContact> ContactList = new List<DhtContact>(); public List<byte[]> ValueList = new List<byte[]>(); public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame ack = protocol.WritePacket(null, NetworkPacket.SearchAck, null); Source.WritePacket(protocol, ack, Packet_Source); protocol.WritePacket(ack, Packet_SearchID, BitConverter.GetBytes(SearchID)); protocol.WritePacket(ack, Packet_Service, CompactNum.GetBytes(Service)); if (Proxied) protocol.WritePacket(ack, Packet_Proxied, null); foreach (DhtContact contact in ContactList) contact.WritePacket(protocol, ack, Packet_Contacts); foreach (byte[] value in ValueList) protocol.WritePacket(ack, Packet_Values, value); InternalData = protocol.WriteFinish(); return base.Encode(protocol); } } public static SearchAck Decode(G2ReceivedPacket packet) { SearchAck ack = new SearchAck(); G2Header child = new G2Header(packet.Root.Data); while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD ) { if (child.Name == Packet_Proxied) { ack.Proxied = true; continue; } if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Source: ack.Source = DhtSource.ReadPacket(child); break; case Packet_SearchID: ack.SearchID = BitConverter.ToUInt32(child.Data, child.PayloadPos); break; case Packet_Contacts: ack.ContactList.Add( DhtContact.ReadPacket(child) ); break; case Packet_Service: ack.Service = CompactNum.ToUInt32(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_Values: ack.ValueList.Add(Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize)); break; } } return ack; } } public class StoreReq : NetworkPacket { const byte Packet_Source = 0x10; const byte Packet_Key = 0x20; const byte Packet_Service = 0x30; const byte Packet_DataType = 0x40; const byte Packet_Data = 0x50; const byte Packet_TTL = 0x60; public DhtSource Source = new DhtSource(); public UInt64 Key; public uint Service; public uint DataType; public byte[] Data; public ushort TTL = ushort.MaxValue; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame req = protocol.WritePacket(null, NetworkPacket.StoreRequest, null); Source.WritePacket(protocol, req, Packet_Source); protocol.WritePacket(req, Packet_Key, BitConverter.GetBytes(Key)); protocol.WritePacket(req, Packet_Service, CompactNum.GetBytes(Service)); protocol.WritePacket(req, Packet_DataType, CompactNum.GetBytes(DataType)); protocol.WritePacket(req, Packet_Data, Data); protocol.WritePacket(req, Packet_TTL, BitConverter.GetBytes(TTL)); InternalData = protocol.WriteFinish(); return base.Encode(protocol); } } public static StoreReq Decode(G2ReceivedPacket packet) { StoreReq req = new StoreReq(); G2Header child = new G2Header(packet.Root.Data); while (G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Source: req.Source = DhtSource.ReadPacket(child); break; case Packet_Key: req.Key = BitConverter.ToUInt64(child.Data, child.PayloadPos); break; case Packet_Service: req.Service = CompactNum.ToUInt32(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_DataType: req.DataType = CompactNum.ToUInt32(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_Data: req.Data = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_TTL: req.TTL = BitConverter.ToUInt16(child.Data, child.PayloadPos); break; } } return req; } } public class Ping : NetworkPacket { const byte Packet_Source = 0x10; const byte Packet_RemoteIP = 0x20; public DhtSource Source; public IPAddress RemoteIP; public ushort Ident; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { // ping packet G2Frame pi = protocol.WritePacket(null, NetworkPacket.Ping, BitConverter.GetBytes(Ident)); if(Source != null) Source.WritePacket(protocol, pi, Packet_Source); if (RemoteIP != null) protocol.WritePacket(pi, Packet_RemoteIP, RemoteIP.GetAddressBytes()); // network packet InternalData = protocol.WriteFinish(); return base.Encode(protocol); } } public static Ping Decode(G2ReceivedPacket packet) { Ping pi = new Ping(); if(G2Protocol.ReadPayload(packet.Root)) pi.Ident = BitConverter.ToUInt16(packet.Root.Data, packet.Root.PayloadPos); G2Protocol.ResetPacket(packet.Root); G2Header child = new G2Header(packet.Root.Data); while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD ) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Source: pi.Source = DhtSource.ReadPacket(child); break; case Packet_RemoteIP: pi.RemoteIP = new IPAddress(Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize)); break; } } return pi; } } public class Pong : NetworkPacket { const byte Packet_Source = 0x10; const byte Packet_RemoteIP = 0x20; const byte Packet_Direct = 0x30; const byte Packet_Version = 0x40; public DhtSource Source; public IPAddress RemoteIP; public bool Direct; // version of the cached update file (NOT the client) use crawl to find that // in pong because receiveing pong proves we can send and recv from host public uint Version; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame po = protocol.WritePacket(null, NetworkPacket.Pong, null); if(Source != null) Source.WritePacket(protocol, po, Packet_Source); if (RemoteIP != null) protocol.WritePacket(po, Packet_RemoteIP, RemoteIP.GetAddressBytes()); if(Direct) protocol.WritePacket(po, Packet_Direct, null); if (Version != 0) protocol.WritePacket(po, Packet_Version, CompactNum.GetBytes(Version)); // network packet InternalData = protocol.WriteFinish(); return base.Encode(protocol); } } public static Pong Decode(G2ReceivedPacket packet) { Pong po = new Pong(); G2Header child = new G2Header(packet.Root.Data); while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD ) { if (!G2Protocol.ReadPayload(child)) { if(child.Name == Packet_Direct) po.Direct = true; continue; } switch (child.Name) { case Packet_Source: po.Source = DhtSource.ReadPacket(child); break; case Packet_RemoteIP: po.RemoteIP = new IPAddress(Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize)); break; case Packet_Version: po.Version = CompactNum.ToUInt32(child.Data, child.PayloadPos, child.PayloadSize); break; } } return po; } } public class Bye : NetworkPacket { const byte Packet_Source = 0x10; const byte Packet_Contacts = 0x20; const byte Packet_Message = 0x30; const byte Packet_Reconnect = 0x40; public UInt64 SenderID; public List<DhtContact> ContactList = new List<DhtContact>(); public string Message; public bool Reconnect; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame bye = protocol.WritePacket(null, NetworkPacket.Bye, null); protocol.WritePacket(bye, Packet_Source, BitConverter.GetBytes(SenderID)); foreach (DhtContact contact in ContactList) contact.WritePacket(protocol, bye, Packet_Contacts); if (Message != null) protocol.WritePacket(bye, Packet_Message, UTF8Encoding.UTF8.GetBytes(Message)); if (Reconnect) protocol.WritePacket(bye, Packet_Reconnect, null); // network packet InternalData = protocol.WriteFinish(); return base.Encode(protocol); } } public static Bye Decode(G2ReceivedPacket packet) { Bye bye = new Bye(); G2Header child = new G2Header(packet.Root.Data); while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD ) { if (!G2Protocol.ReadPayload(child)) { if (child.Name == Packet_Reconnect) bye.Reconnect = true; continue; } switch (child.Name) { case Packet_Source: bye.SenderID = BitConverter.ToUInt64(child.Data, child.PayloadPos); break; case Packet_Contacts: bye.ContactList.Add( DhtContact.ReadPacket(child)); break; case Packet_Message: bye.Message = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; } } return bye; } } public class ProxyReq : NetworkPacket { const byte Packet_Source = 0x10; const byte Packet_Blocked = 0x20; const byte Packet_NAT = 0x30; public UInt64 SenderID; public ProxyType Type; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame pr = protocol.WritePacket(null, NetworkPacket.ProxyRequest, null); protocol.WritePacket(pr, Packet_Source, BitConverter.GetBytes(SenderID)); if (Type == ProxyType.ClientBlocked) protocol.WritePacket(pr, Packet_Blocked, null); else if (Type == ProxyType.ClientNAT) protocol.WritePacket(pr, Packet_NAT, null); // network packet InternalData = protocol.WriteFinish(); return base.Encode(protocol); } } public static ProxyReq Decode(G2ReceivedPacket packet) { ProxyReq pr = new ProxyReq(); G2Header child = new G2Header(packet.Root.Data); while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD ) { switch (child.Name) { case Packet_Source: if (G2Protocol.ReadPayload(child)) pr.SenderID = BitConverter.ToUInt64(child.Data, child.PayloadPos); break; case Packet_Blocked: pr.Type = ProxyType.ClientBlocked; break; case Packet_NAT: pr.Type = ProxyType.ClientNAT; break; } } return pr; } } public class ProxyAck : NetworkPacket { const byte Packet_Source = 0x10; const byte Packet_Accept = 0x20; const byte Packet_Contacts = 0x30; public DhtSource Source = new DhtSource(); public bool Accept; public List<DhtContact> ContactList = new List<DhtContact>(); public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame pa = protocol.WritePacket(null, NetworkPacket.ProxyAck, null); Source.WritePacket(protocol, pa, Packet_Source); if (Accept) protocol.WritePacket(pa, Packet_Accept, null); foreach (DhtContact contact in ContactList) contact.WritePacket(protocol, pa, Packet_Contacts); // network packet InternalData = protocol.WriteFinish(); return base.Encode(protocol); } } public static ProxyAck Decode(G2ReceivedPacket packet) { ProxyAck pa = new ProxyAck(); G2Header child = new G2Header(packet.Root.Data); while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD ) { switch (child.Name) { case Packet_Source: if (G2Protocol.ReadPayload(child)) pa.Source = DhtSource.ReadPacket(child); break; case Packet_Accept: pa.Accept = true; break; case Packet_Contacts: if (G2Protocol.ReadPayload(child)) pa.ContactList.Add( DhtContact.ReadPacket(child)); break; } } return pa; } } public class CrawlRequest : NetworkPacket { const byte Packet_Target = 0x10; public DhtClient Target; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame request = protocol.WritePacket(null, NetworkPacket.CrawlRequest, null); protocol.WritePacket(request, Packet_Target, Target.ToBytes()); // network packet InternalData = protocol.WriteFinish(); return base.Encode(protocol); } } public static CrawlRequest Decode(G2ReceivedPacket packet) { CrawlRequest request = new CrawlRequest(); G2Header child = new G2Header(packet.Root.Data); while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD ) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Target: request.Target = DhtClient.FromBytes(child.Data, child.PayloadPos); break; } } return request; } } public class CrawlAck : NetworkPacket { const byte Packet_Source = 0x10; const byte Packet_Version = 0x20; const byte Packet_Uptime = 0x30; const byte Packet_ProxyServers = 0x50; const byte Packet_ProxyClients = 0x60; public DhtSource Source = new DhtSource(); public string Version; public int Uptime; public List<DhtContact> ProxyServers = new List<DhtContact>(); public List<DhtContact> ProxyClients = new List<DhtContact>(); public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame ack = protocol.WritePacket(null, NetworkPacket.CrawlAck, null); Source.WritePacket(protocol, ack, Packet_Source); protocol.WritePacket(ack, Packet_Version, UTF8Encoding.UTF8.GetBytes(Version)); protocol.WritePacket(ack, Packet_Uptime, BitConverter.GetBytes(Uptime)); foreach (DhtContact proxy in ProxyServers) proxy.WritePacket(protocol, ack, Packet_ProxyServers); foreach (DhtContact proxy in ProxyClients) proxy.WritePacket(protocol, ack, Packet_ProxyClients); // network packet InternalData = protocol.WriteFinish(); return base.Encode(protocol); } } public static CrawlAck Decode(G2ReceivedPacket packet) { CrawlAck ack = new CrawlAck(); G2Header child = new G2Header(packet.Root.Data); while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD ) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Source: ack.Source = DhtSource.ReadPacket(child); break; case Packet_Version: ack.Version = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_Uptime: ack.Uptime = BitConverter.ToInt32(child.Data, child.PayloadPos); break; case Packet_ProxyServers: ack.ProxyServers.Add( DhtContact.ReadPacket(child)); break; case Packet_ProxyClients: ack.ProxyClients.Add(DhtContact.ReadPacket(child)); break; } } return ack; } } public class CryptPadding : G2Packet { public byte[] Filler; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { protocol.WritePacket(null, RootPacket.Padding, Filler); return protocol.WriteFinish(); } } public static CryptPadding Decode(G2ReceivedPacket packet) { CryptPadding padding = new CryptPadding(); return padding; } } /*public class TestPacket : G2Packet { public string Message; public int Num; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame earth = protocol.WritePacket(null, "Earth", UTF8Encoding.UTF8.GetBytes("Our Home")); G2Frame america = protocol.WritePacket(earth, "America", UTF8Encoding.UTF8.GetBytes("Where I live")); G2Frame nh = protocol.WritePacket(america, "NH", UTF8Encoding.UTF8.GetBytes("Home")); protocol.WritePacket(nh, "Nashua", null); protocol.WritePacket(nh, "Concord", UTF8Encoding.UTF8.GetBytes("Capitol")); protocol.WritePacket(america, "Mass", UTF8Encoding.UTF8.GetBytes("Where I go to school")); G2Frame europe = protocol.WritePacket(earth, "Europe", UTF8Encoding.UTF8.GetBytes("Across the ocean")); protocol.WritePacket(europe, "London", UTF8Encoding.UTF8.GetBytes("in england")); protocol.WritePacket(europe, "Paris", UTF8Encoding.UTF8.GetBytes("in france")); return protocol.WriteFinish(); } } public static TestPacket Decode(G2ReceivedPacket packet) { TestPacket test = new TestPacket(); G2Header child = new G2Header(packet.Root.Data); while( G2Protocol.ReadNextChild(packet.Root, child) == G2ReadResult.PACKET_GOOD ) { } return test; } }*/ }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Orleans; using Orleans.Concurrency; using Orleans.Providers; using UnitTests.GrainInterfaces; using System.Globalization; using Orleans.CodeGeneration; namespace UnitTests.Grains { [Serializable] public class SimpleGenericGrainState<T> { public T A { get; set; } public T B { get; set; } } [StorageProvider(ProviderName = "MemoryStore")] public class SimpleGenericGrain1<T> : Grain<SimpleGenericGrainState<T>>, ISimpleGenericGrain1<T> { public Task<T> GetA() { return Task.FromResult(State.A); } public Task SetA(T a) { State.A = a; return TaskDone.Done; } public Task SetB(T b) { State.B = b; return TaskDone.Done; } public Task<string> GetAxB() { string retValue = string.Format("{0}x{1}", State.A, State.B); return Task.FromResult(retValue); } public Task<string> GetAxB(T a, T b) { string retValue = string.Format("{0}x{1}", a, b); return Task.FromResult(retValue); } } [StorageProvider(ProviderName = "AzureStore")] public class SimpleGenericGrainUsingAzureTableStorage<T> : Grain<SimpleGenericGrainState<T>>, ISimpleGenericGrainUsingAzureTableStorage<T> { public async Task<T> EchoAsync(T entity) { State.A = entity; await WriteStateAsync(); return entity; } public async Task ClearState() { await ClearStateAsync(); } } [StorageProvider(ProviderName = "AzureStore")] public class TinyNameGrain<T> : Grain<SimpleGenericGrainState<T>>, ITinyNameGrain<T> { public async Task<T> EchoAsync(T entity) { State.A = entity; await WriteStateAsync(); return entity; } public async Task ClearState() { await ClearStateAsync(); } } [Serializable] public class SimpleGenericGrainUState<U> { public U A { get; set; } public U B { get; set; } } [StorageProvider(ProviderName = "MemoryStore")] public class SimpleGenericGrainU<U> : Grain<SimpleGenericGrainUState<U>>, ISimpleGenericGrainU<U> { public Task<U> GetA() { return Task.FromResult(State.A); } public Task SetA(U a) { State.A = a; return TaskDone.Done; } public Task SetB(U b) { State.B = b; return TaskDone.Done; } public Task<string> GetAxB() { string retValue = string.Format("{0}x{1}", State.A, State.B); return Task.FromResult(retValue); } public Task<string> GetAxB(U a, U b) { string retValue = string.Format("{0}x{1}", a, b); return Task.FromResult(retValue); } } [Serializable] public class SimpleGenericGrain2State<T, U> { public T A { get; set; } public U B { get; set; } } [StorageProvider(ProviderName = "MemoryStore")] public class SimpleGenericGrain2<T, U> : Grain<SimpleGenericGrain2State<T, U>>, ISimpleGenericGrain2<T, U> { public Task<T> GetA() { return Task.FromResult(State.A); } public Task SetA(T a) { State.A = a; return TaskDone.Done; } public Task SetB(U b) { State.B = b; return TaskDone.Done; } public Task<string> GetAxB() { string retValue = string.Format(CultureInfo.InvariantCulture, "{0}x{1}", State.A, State.B); return Task.FromResult(retValue); } public Task<string> GetAxB(T a, U b) { string retValue = string.Format(CultureInfo.InvariantCulture, "{0}x{1}", a, b); return Task.FromResult(retValue); } } public class GenericGrainWithNoProperties<T> : Grain, IGenericGrainWithNoProperties<T> { public Task<string> GetAxB(T a, T b) { string retValue = string.Format("{0}x{1}", a, b); return Task.FromResult(retValue); } } public class GrainWithNoProperties : Grain, IGrainWithNoProperties { public Task<string> GetAxB(int a, int b) { string retValue = string.Format("{0}x{1}", a, b); return Task.FromResult(retValue); } } [Serializable] public class IGrainWithListFieldsState { public IList<string> Items { get; set; } } [StorageProvider(ProviderName = "MemoryStore")] public class GrainWithListFields : Grain<IGrainWithListFieldsState>, IGrainWithListFields { public override Task OnActivateAsync() { if (State.Items == null) State.Items = new List<string>(); return base.OnActivateAsync(); } public Task AddItem(string item) { State.Items.Add(item); return TaskDone.Done; } public Task<IList<string>> GetItems() { return Task.FromResult((State.Items)); } } [Serializable] public class GenericGrainWithListFieldsState<T> { public IList<T> Items { get; set; } } [StorageProvider(ProviderName = "MemoryStore")] public class GenericGrainWithListFields<T> : Grain<GenericGrainWithListFieldsState<T>>, IGenericGrainWithListFields<T> { public override Task OnActivateAsync() { if (State.Items == null) State.Items = new List<T>(); return base.OnActivateAsync(); } public Task AddItem(T item) { State.Items.Add(item); return TaskDone.Done; } public Task<IList<T>> GetItems() { return Task.FromResult(State.Items); } } [Serializable] public class GenericReaderWriterState<T> { public T Value { get; set; } } [Serializable] public class GenericReader2State<TOne, TTwo> { public TOne Value1 { get; set; } public TTwo Value2 { get; set; } } [Serializable] public class GenericReaderWriterGrain2State<TOne, TTwo> { public TOne Value1 { get; set; } public TTwo Value2 { get; set; } } [Serializable] public class GenericReader3State<TOne, TTwo, TThree> { public TOne Value1 { get; set; } public TTwo Value2 { get; set; } public TThree Value3 { get; set; } } [StorageProvider(ProviderName = "MemoryStore")] public class GenericReaderWriterGrain1<T> : Grain<GenericReaderWriterState<T>>, IGenericReaderWriterGrain1<T> { public Task SetValue(T value) { State.Value = value; return TaskDone.Done; } public Task<T> GetValue() { return Task.FromResult(State.Value); } } [StorageProvider(ProviderName = "MemoryStore")] public class GenericReaderWriterGrain2<TOne, TTwo> : Grain<GenericReaderWriterGrain2State<TOne, TTwo>>, IGenericReaderWriterGrain2<TOne, TTwo> { public Task SetValue1(TOne value) { State.Value1 = value; return TaskDone.Done; } public Task SetValue2(TTwo value) { State.Value2 = value; return TaskDone.Done; } public Task<TOne> GetValue1() { return Task.FromResult(State.Value1); } public Task<TTwo> GetValue2() { return Task.FromResult(State.Value2); } } [StorageProvider(ProviderName = "MemoryStore")] public class GenericReaderWriterGrain3<TOne, TTwo, TThree> : Grain<GenericReader3State<TOne, TTwo, TThree>>, IGenericReaderWriterGrain3<TOne, TTwo, TThree> { public Task SetValue1(TOne value) { State.Value1 = value; return TaskDone.Done; } public Task SetValue2(TTwo value) { State.Value2 = value; return TaskDone.Done; } public Task SetValue3(TThree value) { State.Value3 = value; return TaskDone.Done; } public Task<TThree> GetValue3() { return Task.FromResult(State.Value3); } public Task<TOne> GetValue1() { return Task.FromResult(State.Value1); } public Task<TTwo> GetValue2() { return Task.FromResult(State.Value2); } } public class BasicGenericGrain<T, U> : Grain, IBasicGenericGrain<T, U> { private T _a; private U _b; public Task<T> GetA() { return Task.FromResult(_a); } public Task<string> GetAxB() { string retValue = string.Format(CultureInfo.InvariantCulture, "{0}x{1}", _a, _b); return Task.FromResult(retValue); } public Task<string> GetAxB(T a, U b) { string retValue = string.Format(CultureInfo.InvariantCulture, "{0}x{1}", a, b); return Task.FromResult(retValue); } public Task SetA(T a) { this._a = a; return TaskDone.Done; } public Task SetB(U b) { this._b = b; return TaskDone.Done; } } public class HubGrain<TKey, T1, T2> : Grain, IHubGrain<TKey, T1, T2> { public virtual Task Bar(TKey key, T1 message1, T2 message2) { throw new System.NotImplementedException(); } } public class EchoHubGrain<TKey, TMessage> : HubGrain<TKey, TMessage, TMessage>, IEchoHubGrain<TKey, TMessage> { private int _x; public Task Foo(TKey key, TMessage message, int x) { _x = x; return TaskDone.Done; } public override Task Bar(TKey key, TMessage message1, TMessage message2) { return TaskDone.Done; } public Task<int> GetX() { return Task.FromResult(_x); } } public class EchoGenericChainGrain<T> : Grain, IEchoGenericChainGrain<T> { public async Task<T> Echo(T item) { long pk = this.GetPrimaryKeyLong(); var otherGrain = GrainFactory.GetGrain<ISimpleGenericGrain1<T>>(pk); await otherGrain.SetA(item); return await otherGrain.GetA(); } public async Task<T> Echo2(T item) { long pk = this.GetPrimaryKeyLong() + 1; var otherGrain = GrainFactory.GetGrain<IEchoGenericChainGrain<T>>(pk); return await otherGrain.Echo(item); } public async Task<T> Echo3(T item) { long pk = this.GetPrimaryKeyLong() + 1; var otherGrain = GrainFactory.GetGrain<IEchoGenericChainGrain<T>>(pk); return await otherGrain.Echo2(item); } public async Task<T> Echo4(T item) { long pk = this.GetPrimaryKeyLong() + 1; var otherGrain = GrainFactory.GetGrain<ISimpleGenericGrain1<T>>(pk); await otherGrain.SetA(item); return await otherGrain.GetA(); } public async Task<T> Echo5(T item) { long pk = this.GetPrimaryKeyLong() + 1; var otherGrain = GrainFactory.GetGrain<IEchoGenericChainGrain<T>>(pk); return await otherGrain.Echo4(item); } public async Task<T> Echo6(T item) { long pk = this.GetPrimaryKeyLong() + 1; var otherGrain = GrainFactory.GetGrain<IEchoGenericChainGrain<T>>(pk); return await otherGrain.Echo5(item); } } public class NonGenericBaseGrain : Grain, INonGenericBase { public Task Ping() { return TaskDone.Done; } } public class Generic1ArgumentGrain<T> : NonGenericBaseGrain, IGeneric1Argument<T> { public Task<T> Ping(T t) { return Task.FromResult(t); } } public class Generic1ArgumentDerivedGrain<T> : NonGenericBaseGrain, IGeneric1Argument<T> { public Task<T> Ping(T t) { return Task.FromResult(t); } } public class Generic2ArgumentGrain<T, U> : Grain, IGeneric2Arguments<T, U> { public Task<Tuple<T, U>> Ping(T t, U u) { return Task.FromResult(new Tuple<T, U>(t, u)); } public Task Ping() { return TaskDone.Done; } } public class Generic2ArgumentsDerivedGrain<T, U> : NonGenericBaseGrain, IGeneric2Arguments<T, U> { public Task<Tuple<T, U>> Ping(T t, U u) { return Task.FromResult(new Tuple<T, U>(t, u)); } } public class DbGrain<T> : Grain, IDbGrain<T> { private T _value; public Task SetValue(T value) { _value = value; return TaskDone.Done; } public Task<T> GetValue() { return Task.FromResult(_value); } } [Reentrant] public class PingSelfGrain<T> : Grain, IGenericPingSelf<T> { private T _lastValue; public Task<T> Ping(T t) { _lastValue = t; return Task.FromResult(t); } public Task<T> PingOther(IGenericPingSelf<T> target, T t) { return target.Ping(t); } public Task<T> PingSelf(T t) { return PingOther(this, t); } public Task<T> PingSelfThroughOther(IGenericPingSelf<T> target, T t) { return target.PingOther(this, t); } public Task ScheduleDelayedPing(IGenericPingSelf<T> target, T t, TimeSpan delay) { RegisterTimer(o => { this.GetLogger().Verbose("***Timer fired for pinging {0}***", target.GetPrimaryKey()); return target.Ping(t); }, null, delay, TimeSpan.FromMilliseconds(-1)); return TaskDone.Done; } public Task<T> GetLastValue() { return Task.FromResult(_lastValue); } public async Task ScheduleDelayedPingToSelfAndDeactivate(IGenericPingSelf<T> target, T t, TimeSpan delay) { await target.ScheduleDelayedPing(this, t, delay); DeactivateOnIdle(); } public override Task OnActivateAsync() { GetLogger().Verbose("***Activating*** {0}", this.GetPrimaryKey()); return TaskDone.Done; } public override Task OnDeactivateAsync() { GetLogger().Verbose("***Deactivating*** {0}", this.GetPrimaryKey()); return TaskDone.Done; } } public class LongRunningTaskGrain<T> : Grain, ILongRunningTaskGrain<T> { public async Task<T> CallOtherLongRunningTask(ILongRunningTaskGrain<T> target, T t, TimeSpan delay) { return await target.LongRunningTask(t, delay); } public async Task<T> LongRunningTask(T t, TimeSpan delay) { await Task.Delay(delay); return await Task.FromResult(t); } public Task<string> GetRuntimeInstanceId() { return Task.FromResult(RuntimeIdentity); } } public class GenericGrainWithContraints<A, B, C>: Grain, IGenericGrainWithConstraints<A, B, C> where A : ICollection<B>, new() where B : struct where C : class { private A collection; public override Task OnActivateAsync() { collection = new A(); return TaskDone.Done; } public Task<int> GetCount() { return Task.FromResult(collection.Count); } public Task Add(B item) { collection.Add(item); return TaskDone.Done; } public Task<C> RoundTrip(C value) { return Task.FromResult(value); } } public class NonGenericCastableGrain : Grain, INonGenericCastableGrain, ISomeGenericGrain<string>, IIndependentlyConcretizedGenericGrain<string>, IIndependentlyConcretizedGrain { public Task DoSomething() { return TaskDone.Done; } public Task<string> Hello() { return Task.FromResult("Hello!"); } } public class GenericCastableGrain<T> : Grain, IGenericCastableGrain<T>, INonGenericCastGrain { public Task<string> Hello() { return Task.FromResult("Hello!"); } } public class IndepedentlyConcretizedGenericGrain : Grain, IIndependentlyConcretizedGenericGrain<string>, IIndependentlyConcretizedGrain { public Task<string> Hello() { return Task.FromResult("I have been independently concretized!"); } } namespace Generic.EdgeCases { using System.Linq; using UnitTests.GrainInterfaces.Generic.EdgeCases; public abstract class BasicGrain : Grain { public Task<string> Hello() { return Task.FromResult("Hello!"); } public Task<string[]> ConcreteGenArgTypeNames() { var grainType = GetImmediateSubclass(this.GetType()); return Task.FromResult( grainType.GetGenericArguments() .Select(t => t.FullName) .ToArray() ); } Type GetImmediateSubclass(Type subject) { if(subject.BaseType == typeof(BasicGrain)) { return subject; } return GetImmediateSubclass(subject.BaseType); } } public class PartiallySpecifyingGrain<T> : BasicGrain, IGrainWithTwoGenArgs<string, T> { } public class GrainWithPartiallySpecifyingInterface<T> : BasicGrain, IPartiallySpecifyingInterface<T> { } public class GrainSpecifyingSameGenArgTwice<T> : BasicGrain, IGrainReceivingRepeatedGenArgs<T, T> { } public class SpecifyingRepeatedGenArgsAmongstOthers<T1, T2> : BasicGrain, IReceivingRepeatedGenArgsAmongstOthers<T2, T1, T2> { } public class GrainForTestingCastingBetweenInterfacesWithReusedGenArgs : BasicGrain, ISpecifyingGenArgsRepeatedlyToParentInterface<bool> { } public class SpecifyingSameGenArgsButRearranged<T1, T2> : BasicGrain, IReceivingRearrangedGenArgs<T2, T1> { } public class GrainForTestingCastingWithRearrangedGenArgs<T1, T2> : BasicGrain, ISpecifyingRearrangedGenArgsToParentInterface<T1, T2> { } public class GrainWithGenArgsUnrelatedToFullySpecifiedGenericInterface<T1, T2> : BasicGrain, IArbitraryInterface<T1, T2>, IInterfaceUnrelatedToConcreteGenArgs<float> { } public class GrainSupplyingFurtherSpecializedGenArg<T> : BasicGrain, IInterfaceTakingFurtherSpecializedGenArg<List<T>> { } public class GrainSupplyingGenArgSpecializedIntoArray<T> : BasicGrain, IInterfaceTakingFurtherSpecializedGenArg<T[]> { } public class GrainForCastingBetweenInterfacesOfFurtherSpecializedGenArgs<T> : BasicGrain, IAnotherReceivingFurtherSpecializedGenArg<List<T>>, IYetOneMoreReceivingFurtherSpecializedGenArg<T[]> { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Int32 : IComparable, IConvertible, IFormattable, IComparable<Int32>, IEquatable<Int32>, ISpanFormattable { private int m_value; // Do not rename (binary serialization) public const int MaxValue = 0x7fffffff; public const int MinValue = unchecked((int)0x80000000); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns : // 0 if the values are equal // Negative number if _value is less than value // Positive number if _value is more than value // null is considered to be less than any instance, hence returns positive number // If object is not of type Int32, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Int32) { // NOTE: Cannot use return (_value - value) as this causes a wrap // around in cases where _value - value > MaxValue. int i = (int)value; if (m_value < i) return -1; if (m_value > i) return 1; return 0; } throw new ArgumentException(SR.Arg_MustBeInt32); } public int CompareTo(int value) { // NOTE: Cannot use return (_value - value) as this causes a wrap // around in cases where _value - value > MaxValue. if (m_value < value) return -1; if (m_value > value) return 1; return 0; } public override bool Equals(Object obj) { if (!(obj is Int32)) { return false; } return m_value == ((Int32)obj).m_value; } [NonVersionable] public bool Equals(Int32 obj) { return m_value == obj; } // The absolute value of the int contained. public override int GetHashCode() { return m_value; } public override String ToString() { return Number.FormatInt32(m_value, null, null); } public String ToString(String format) { return Number.FormatInt32(m_value, format, null); } public String ToString(IFormatProvider provider) { return Number.FormatInt32(m_value, null, provider); } public String ToString(String format, IFormatProvider provider) { return Number.FormatInt32(m_value, format, provider); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) { return Number.TryFormatInt32(m_value, format, provider, destination, out charsWritten); } public static int Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static int Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, style, NumberFormatInfo.CurrentInfo); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static int Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static int Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider)); } public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider)); } // Parses an integer from a String. Returns false rather // than throwing exceptin if input is invalid // public static bool TryParse(String s, out Int32 result) { if (s == null) { result = 0; return false; } return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan<char> s, out int result) { return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } // Parses an integer from a String in the given style. Returns false rather // than throwing exceptin if input is invalid // public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Int32; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return m_value; } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int32", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Its.Log.Instrumentation; using Microsoft.Its.Domain.Sql.CommandScheduler; using Microsoft.Its.Recipes; using NUnit.Framework; using Sample.Domain; using Sample.Domain.Ordering; using Sample.Domain.Ordering.Commands; using System; using System.Linq; using System.Reactive.Disposables; using System.Threading.Tasks; namespace Microsoft.Its.Domain.Testing.Tests { [TestFixture] public abstract class ScenarioBuilderTests { private CompositeDisposable disposables; protected ScenarioBuilderTests() { Command<CustomerAccount>.AuthorizeDefault = (customer, command) => true; Command<Order>.AuthorizeDefault = (order, command) => true; } [SetUp] public virtual void SetUp() { disposables = new CompositeDisposable( Disposable.Create(() => ConfigurationContext.Current .IfNotNull() .ThenDo(c => c.Dispose()))); } [TearDown] public virtual void TearDown() { disposables.Dispose(); } protected void RegisterForDisposal(IDisposable disposable) { disposables.Add(disposable); } [Test] public void Events_added_to_the_scenario_are_used_to_source_aggregates() { var name = Any.FullName(); var aggregateId = Any.Guid(); var orderNumber = Any.Int(2000, 5000).ToString(); var scenario = CreateScenarioBuilder() .AddEvents(new Order.Created { AggregateId = aggregateId, OrderNumber = orderNumber }, new Order.CustomerInfoChanged { AggregateId = aggregateId, CustomerName = name }).Prepare(); var order = scenario.Aggregates.Single() as Order; order.Should().NotBeNull(); order.OrderNumber.Should().Be(orderNumber); order.CustomerName.Should().Be(name); order.Id.Should().Be(aggregateId); } [Test] public void If_no_aggregate_id_is_specified_when_adding_events_then_a_default_is_chosen_and_reused() { var created = new Order.Created(); var customerInfoChanged = new Order.CustomerInfoChanged(); CreateScenarioBuilder() .AddEvents(created, customerInfoChanged); created.AggregateId.Should().NotBeEmpty(); customerInfoChanged.AggregateId.Should().Be(created.AggregateId); } [Test] public async Task If_no_aggregate_id_is_specified_when_calling_GetLatest_and_a_single_instance_is_in_the_scenario_then_it_is_returned() { var aggregateId = Any.Guid(); var created = new Order.Created { AggregateId = aggregateId }; var scenario = CreateScenarioBuilder().AddEvents(created).Prepare(); var aggregate = await scenario.GetLatestAsync<Order>(); aggregate.Should().NotBeNull(); aggregate.Id.Should().Be(aggregateId); } [Test] public void If_no_aggregate_id_is_specified_when_calling_GetLatest_and_no_instance_is_in_the_scenario_then_it_throws() { var scenario = CreateScenarioBuilder() .AddEvents(new Order.Created { AggregateId = Any.Guid() }, new Order.Created { AggregateId = Any.Guid() }).Prepare(); Action getLatest = () => scenario.GetLatestAsync<Order>().Wait(); getLatest.ShouldThrow<InvalidOperationException>(); } [Test] public void If_no_aggregate_id_is_specified_when_calling_GetLatest_and_multiple_instances_are_in_the_scenario_then_it_throws() { var scenario = CreateScenarioBuilder().Prepare(); Action getLatest = () => scenario.GetLatestAsync<Order>().Wait(); getLatest.ShouldThrow<InvalidOperationException>(); } [Test] public void When_no_sequence_numbers_are_specified_then_events_are_applied_in_order() { var aggregateId = Any.Guid(); var firstCustomerName = Any.FullName(); var scenario = CreateScenarioBuilder() .AddEvents(new Order.CustomerInfoChanged { AggregateId = aggregateId, CustomerName = Any.FullName() }, new Order.CustomerInfoChanged { AggregateId = aggregateId, CustomerName = firstCustomerName }).Prepare(); var order = scenario.Aggregates.OfType<Order>().Single(); order.CustomerName.Should().Be(firstCustomerName); } [Test] public void DynamicProjectors_registered_as_event_handlers_in_ScenarioBuilder_run_catchups_when_prepare_is_called() { var firstShipHandled = false; var secondShipHandled = false; var handler = Domain.Projector.CreateDynamic(dynamicEvent => { var @event = dynamicEvent as IEvent; @event.IfTypeIs<CommandScheduled<Order>>() .ThenDo(c => { var shipmentId = (c.Command as Ship).ShipmentId; Console.WriteLine("Handling [{0}] Shipment", shipmentId); if (shipmentId == "first") { firstShipHandled = true; } else if (shipmentId == "second") { secondShipHandled = true; } }); }, "Order.Scheduled:Ship"); CreateScenarioBuilder() .AddHandler(handler) .AddEvents( new CommandScheduled<Order> { Command = new Ship { ShipmentId = "first" }, DueTime = DateTime.Now }, new CommandScheduled<Order> { Command = new Ship { ShipmentId = "second" }, DueTime = DateTime.Now }) .Prepare(); firstShipHandled.Should().BeTrue(); secondShipHandled.Should().BeTrue(); } [Test] public void When_sequence_numbers_are_specified_it_overrides_the_order_in_which_the_events_were_added() { var aggregateId = Any.Guid(); var firstCustomerName = Any.FullName(); var scenario = CreateScenarioBuilder() .AddEvents(new Order.CustomerInfoChanged { AggregateId = aggregateId, CustomerName = firstCustomerName, SequenceNumber = 2 }, new Order.CustomerInfoChanged { AggregateId = aggregateId, CustomerName = Any.FullName(), SequenceNumber = 1 }).Prepare(); var order = scenario.Aggregates.OfType<Order>().Single(); order.CustomerName.Should().Be(firstCustomerName); } [Test] public void Multiple_aggregates_of_the_same_type_can_be_sourced_in_one_scenario() { var builder = CreateScenarioBuilder() .AddEvents(new Order.Created { AggregateId = Any.Guid() }, new Order.Created { AggregateId = Any.Guid() }); builder.Prepare().Aggregates .OfType<Order>() .Count() .Should().Be(2); } [Test] public void Multiple_aggregates_of_different_types_can_be_sourced_in_one_scenario() { // arrange var builder = CreateScenarioBuilder() .AddEvents(new Order.Created { AggregateId = Any.Guid() }, new CustomerAccount.EmailAddressChanged { AggregateId = Any.Guid() }); // act var scenario = builder.Prepare(); // assert scenario.Aggregates .Should() .ContainSingle(a => a is CustomerAccount) .And .ContainSingle(a => a is Order); } [Test] public void Multiple_aggregates_of_the_same_type_can_be_organized_using_For() { var aggregateId1 = Any.Guid(); var aggregateId2 = Any.Guid(); var builder = CreateScenarioBuilder(); builder.For<Order>(aggregateId1) .AddEvents(new Order.ItemAdded { ProductName = "one" }); builder.For<Order>(aggregateId2) .AddEvents(new Order.ItemAdded { ProductName = "two" }); var aggregates = builder.Prepare().Aggregates.OfType<Order>().ToArray(); aggregates.Count().Should().Be(2); aggregates.Should().Contain(a => a.Id == aggregateId1 && a.Items.Single().ProductName == "one"); aggregates.Should().Contain(a => a.Id == aggregateId2 && a.Items.Single().ProductName == "two"); } [Test] public void Projectors_added_before_Prepare_is_called_are_subscribed_to_all_events() { var onDeliveredCalls = 0; var onEmailAddedCalls = 0; var delivered = new Order.Delivered(); var addressChanged = new CustomerAccount.EmailAddressChanged(); CreateScenarioBuilder() .AddEvents(delivered, addressChanged) .AddHandler(new Projector { OnDelivered = e => { Console.WriteLine(e.ToLogString()); onDeliveredCalls++; }, OnEmailAdded = e => { Console.WriteLine(e.ToLogString()); onEmailAddedCalls++; } }) .Prepare(); onDeliveredCalls.Should().Be(1); onEmailAddedCalls.Should().Be(1); } [Test] public async Task Projectors_added_after_Prepare_is_called_are_subscribed_to_future_events() { // arrange var onDeliveredCalls = 0; var onEmailAddedCalls = 0; var scenarioBuilder = CreateScenarioBuilder(); var aggregateId = Any.Guid(); var scenario = scenarioBuilder .AddEvents(new Order.Created { AggregateId = aggregateId }) .Prepare(); scenarioBuilder.AddHandler(new Projector { OnDelivered = e => onDeliveredCalls++, OnEmailAdded = e => onEmailAddedCalls++ }); var order = new Order(); order.Apply(new Deliver()); var customer = new CustomerAccount(); customer.Apply(new ChangeEmailAddress(Any.Email())); // act await scenario.SaveAsync(order); await scenario.SaveAsync(customer); // assert onDeliveredCalls.Should().Be(1); onEmailAddedCalls.Should().Be(1); } [Test] public void When_event_handling_errors_occur_during_Prepare_then_an_exception_is_thrown() { // arrange var scenarioBuilder = CreateScenarioBuilder(); scenarioBuilder.AddEvents(new Order.Delivered()); scenarioBuilder.AddHandler(new Projector { OnDelivered = e => { throw new Exception("oops!"); } }); // act Action prepare = () => scenarioBuilder.Prepare(); // assert prepare.ShouldThrow<ScenarioSetupException>() .And .Message .Should() .Contain("The following event handling errors occurred during projection catchup") .And .Contain("oops!"); } [Test] public async Task When_event_handling_errors_occur_after_Prepare_then_they_can_be_verified_during_the_test() { // arrange var scenarioBuilder = CreateScenarioBuilder(); var scenario = scenarioBuilder.AddHandler(new Projector { OnDelivered = e => { throw new Exception("oops!"); } }).Prepare(); var order = new Order(); order.Apply(new Deliver()); await scenario.SaveAsync(order); // act Action verify = () => scenario.VerifyNoEventHandlingErrors(); // assert verify.ShouldThrow<AssertionException>() .And .Message .Should() .Contain("The following event handling errors occurred") .And .Contain("oops!"); } [Test] public void Consequenters_are_not_triggered_by_Prepare() { // arrange var onDeliveredCalls = 0; var scenarioBuilder = CreateScenarioBuilder(); var aggregateId = Any.Guid(); var builder = scenarioBuilder .AddEvents( new Order.Created { AggregateId = aggregateId }, new Order.Delivered()) .AddHandler(new Consequenter { OnDelivered = e => onDeliveredCalls++ }); // act builder.Prepare(); // assert onDeliveredCalls.Should().Be(0); } [Test] public async Task Events_that_are_saved_as_a_result_of_commands_can_be_verified_using_the_EventBus() { // arrange var builder = CreateScenarioBuilder(); var scenario = builder.Prepare(); var customerName = Any.FullName(); // act await scenario.SaveAsync(new Order(new CreateOrder(customerName))); // assert builder.EventBus .PublishedEvents() .OfType<Order.Created>() .Should() .ContainSingle(e => e.CustomerName == customerName); } [Test] public void AggregateBuilder_can_be_used_to_access_all_events_added_to_the_scenario_for_that_aggregate() { var scenarioBuilder = CreateScenarioBuilder(); var orderId = Any.Guid(); scenarioBuilder.For<Order>(orderId).AddEvents(new Order.Created()); scenarioBuilder.AddEvents(new Order.ItemAdded { AggregateId = orderId }); scenarioBuilder.For<Order>(orderId).InitialEvents.Count().Should().Be(2); } [Test] public void Event_timestamps_can_be_set_using_VirtualClock() { var startTime = DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(Any.PositiveInt(10000))); using (VirtualClock.Start(startTime)) { var scenario = CreateScenarioBuilder(); scenario.AddEvents(new Order.Cancelled()); scenario.InitialEvents.Last().Timestamp.Should().Be(startTime); } } [Test] public void Scenario_clock_can_be_advanced_by_a_specified_timespan() { var startTime = DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(Any.PositiveInt(10000))); var timespan = TimeSpan.FromMinutes(Any.PositiveInt(1000)); using (VirtualClock.Start(startTime)) { var scenario = CreateScenarioBuilder() .AdvanceClockTo(startTime) .AdvanceClockBy(timespan); scenario.AddEvents(new Order.Cancelled()); scenario.InitialEvents.Last().Timestamp.Should().Be(startTime + timespan); } } [Test] public void Scenario_clock_does_not_overwrite_specified_TimeStamp() { var time = Any.DateTimeOffset(); ScenarioBuilder builder; using (VirtualClock.Start(time)) { builder = CreateScenarioBuilder() .AddEvents(new Order.ItemAdded { Timestamp = time }); } builder.InitialEvents.Single().Timestamp.Should().Be(time); } [Test] public void ScenarioBuilder_StartTime_returns_clock_time_when_there_are_no_initial_events() { var clockTime = Any.DateTimeOffset(); using (VirtualClock.Start(clockTime)) { var builder = CreateScenarioBuilder().AdvanceClockTo(clockTime); builder.StartTime().Should().Be(clockTime); } } [Test] public void ScenarioBuilder_StartTime_returns_earliest_event_timestamp_if_it_is_earlier_than_clock() { var eventTime = Any.DateTimeOffset(); var clockTime = eventTime.Add(TimeSpan.FromDays(31)); using (VirtualClock.Start(clockTime)) { var builder = CreateScenarioBuilder() .AdvanceClockTo(clockTime) .AddEvents(new Order.ItemAdded { Timestamp = eventTime }); builder.StartTime().Should().Be(eventTime); } } [Test] public void ScenarioBuilder_StartTime_returns_clock_if_it_is_earlier_than_earliest_event_timestamp() { var clockTime = Any.DateTimeOffset(); using (VirtualClock.Start(clockTime)) { var eventTime = clockTime.Add(TimeSpan.FromMinutes(Any.PositiveInt(1000))); var builder = CreateScenarioBuilder() .AddEvents(new Order.ItemAdded { Timestamp = eventTime }); builder.StartTime().Should().Be(clockTime); } } [Test] public async Task Scheduled_commands_in_initial_events_are_executed_if_they_become_due_after_Prepare_is_called() { using (VirtualClock.Start(Any.DateTimeOffset())) { var customerAccountId = Any.Guid(); var scenario = CreateScenarioBuilder() .AddEvents( new CustomerAccount.Created { AggregateId= customerAccountId }, new Order.Created { CustomerName = Any.FullName(), OrderNumber = "42", CustomerId = customerAccountId }, new CommandScheduled<Order> { Command = new Cancel(), DueTime = Clock.Now().AddDays(102) }).Prepare(); scenario.AdvanceClockBy(TimeSpan.FromDays(103)); (await scenario.GetLatestAsync<Order>()) .EventHistory .Last() .Should() .BeOfType<Order.Cancelled>(); } } [Test] public async Task Recursive_scheduling_is_supported_when_the_scenario_clock_is_advanced() { // arrange using (VirtualClock.Start(DateTimeOffset.Parse("2014-10-08 06:52:10 AM -07:00"))) { var scenario = CreateScenarioBuilder() .AddEvents(new CustomerAccount.EmailAddressChanged { NewEmailAddress = Any.Email() }) .Prepare(); // act var account = (await scenario.GetLatestAsync<CustomerAccount>()) .Apply(new RequestSpam()) .Apply(new SendMarketingEmail()); await scenario.SaveAsync(account); scenario.AdvanceClockBy(TimeSpan.FromDays(30)); await scenario.CommandSchedulerDone(); account = await scenario.GetLatestAsync<CustomerAccount>(); // assert account.Events() .OfType<CommandScheduled<CustomerAccount>>() .Select(e => e.Timestamp.Date) .Should() .BeEquivalentTo(new[] { DateTime.Parse("2014-10-08"), DateTime.Parse("2014-10-15"), DateTime.Parse("2014-10-22"), DateTime.Parse("2014-10-29"), DateTime.Parse("2014-11-05") }); account.Events() .OfType<CustomerAccount.MarketingEmailSent>() .Select(e => e.Timestamp.Date) .Should() .BeEquivalentTo(new[] { DateTime.Parse("2014-10-08"), DateTime.Parse("2014-10-15"), DateTime.Parse("2014-10-22"), DateTime.Parse("2014-10-29"), DateTime.Parse("2014-11-05") }); account.Events() .Last() .Should() .BeOfType<CommandScheduled<CustomerAccount>>(); if (UsesSqlStorage) { using (var db = new CommandSchedulerDbContext()) { var scheduledCommands = db.ScheduledCommands .Where(c => c.AggregateId == account.Id) .ToArray(); // all but the last command (which didn't come due yet) should have been marked as applied scheduledCommands .Reverse() .Skip(1) .Should() .OnlyContain(c => c.AppliedTime != null); } } } } public abstract bool UsesSqlStorage { get; } [Test] public async Task Recursive_scheduling_is_supported_when_the_virtual_clock_is_advanced() { // arrange using (VirtualClock.Start(DateTimeOffset.Parse("2014-10-08 06:52:10 AM -07:00"))) { var scenario = CreateScenarioBuilder() .AddEvents(new CustomerAccount.EmailAddressChanged { NewEmailAddress = Any.Email() }) .Prepare(); // act var account = (await scenario.GetLatestAsync<CustomerAccount>()) .Apply(new RequestSpam()) .Apply(new SendMarketingEmail()); await scenario.SaveAsync(account); VirtualClock.Current.AdvanceBy(TimeSpan.FromDays((7*4) + 2)); await scenario.CommandSchedulerDone(); account = await scenario.GetLatestAsync<CustomerAccount>(); // assert account.Events() .OfType<CommandScheduled<CustomerAccount>>() .Select(e => e.Timestamp.Date) .Should() .BeEquivalentTo(new[] { DateTime.Parse("2014-10-08"), DateTime.Parse("2014-10-15"), DateTime.Parse("2014-10-22"), DateTime.Parse("2014-10-29"), DateTime.Parse("2014-11-05") }); account.Events() .OfType<CustomerAccount.MarketingEmailSent>() .Select(e => e.Timestamp.Date) .Should() .BeEquivalentTo(new[] { DateTime.Parse("2014-10-08"), DateTime.Parse("2014-10-15"), DateTime.Parse("2014-10-22"), DateTime.Parse("2014-10-29"), DateTime.Parse("2014-11-05") }); account.Events() .Last() .Should() .BeOfType<CommandScheduled<CustomerAccount>>(); if (UsesSqlStorage) { using (var db = new CommandSchedulerDbContext()) { var scheduledCommands = db.ScheduledCommands .Where(c => c.AggregateId == account.Id) .ToArray(); // all but the last command (which didn't come due yet) should have been marked as applied scheduledCommands .Reverse() .Skip(1) .Should() .OnlyContain(c => c.AppliedTime != null); } } } } [Ignore("Scenario likely being removed")] [Test] public async Task Recursive_scheduling_is_supported_when_scheduled_command_preconditions_are_satisfied_in_process() { var scenarioBuilder = CreateScenarioBuilder(); var scenario = scenarioBuilder.Prepare(); var customer = new CustomerAccount(); customer.Apply(new ChangeEmailAddress(Any.Email())); var scheduler = scenarioBuilder.Configuration.CommandScheduler<Order>(); var orderId = Any.Guid(); await scheduler.Schedule( orderId, new CreateOrder(Any.FullName()) { AggregateId = orderId }, deliveryDependsOn: customer.Events().First()); await Task.Delay(100); var order = scenario.GetLatest<Order>(orderId); order.Should().BeNull(); Console.WriteLine("saving"); // act scenario.Save(customer); Console.WriteLine("sleeping"); await Task.Delay(5000); Console.WriteLine("slept"); order = scenario.GetLatest<Order>(orderId); order.Should().NotBeNull(); } [Test] public async Task Scheduled_commands_in_initial_events_are_not_executed_if_they_become_due_before_Prepare_is_called() { var aggregateId = Any.Guid(); using (VirtualClock.Start()) { var scenario = CreateScenarioBuilder() .AddEvents(new CommandScheduled<Order> { AggregateId = aggregateId, Command = new Cancel(), DueTime = Clock.Now().AddDays(2) }) .AdvanceClockBy(TimeSpan.FromDays(3)) .Prepare(); (await scenario.GetLatestAsync<Order>(aggregateId)) .EventHistory .Last() .Should() .BeOfType<CommandScheduled<Order>>(); } } [Test] public async Task Handlers_can_be_added_by_type_and_are_instantiated_by_the_internal_container() { var customerId = Guid.NewGuid(); var customerName = Any.FullName(); var scenarioBuilder = CreateScenarioBuilder() .AddEvents(new CustomerAccount.UserNameAcquired { AggregateId = customerId, UserName = customerName }); var scenario = scenarioBuilder.Prepare(); scenarioBuilder.AddHandlers(typeof (SideEffectingConsequenter)); var customerAccount = await scenario.GetLatestAsync<CustomerAccount>(customerId); customerAccount.Apply(new RequestNoSpam()); await scenario.SaveAsync(customerAccount); await scenario.CommandSchedulerDone(); var latest = await scenario.GetLatestAsync<CustomerAccount>(customerId); latest.EmailAddress.Should().Be("devnull@nowhere.com"); } [Test] public void A_new_Scenario_can_be_prepared_while_another_is_still_active() { Configuration outerConfiguration = null; Configuration innerConfiguration = null; using (new ScenarioBuilder(c => { outerConfiguration = c; }).Prepare()) using (new ScenarioBuilder(c => { innerConfiguration = c; }).Prepare()) { Configuration.Current.Should().Be(innerConfiguration); } } protected abstract ScenarioBuilder CreateScenarioBuilder(); public class Projector : IUpdateProjectionWhen<Order.Delivered>, IUpdateProjectionWhen<CustomerAccount.EmailAddressChanged> { public Action<Order.Delivered> OnDelivered = e => { }; public Action<CustomerAccount.EmailAddressChanged> OnEmailAdded = e => { }; public void UpdateProjection(Order.Delivered @event) { OnDelivered(@event); } public void UpdateProjection(CustomerAccount.EmailAddressChanged @event) { OnEmailAdded(@event); } } public class Consequenter : IHaveConsequencesWhen<Order.Delivered> { public Action<Order.Delivered> OnDelivered = e => { }; public void HaveConsequences(Order.Delivered @event) { OnDelivered(@event); } } public class SideEffectingConsequenter : IHaveConsequencesWhen<CustomerAccount.RequestedNoSpam> { private readonly IEventSourcedRepository<CustomerAccount> customerRepository; public SideEffectingConsequenter(IEventSourcedRepository<CustomerAccount> customerRepository) { if (customerRepository == null) { throw new ArgumentNullException("customerRepository"); } this.customerRepository = customerRepository; } public void HaveConsequences(CustomerAccount.RequestedNoSpam @event) { var customer = customerRepository.GetLatest(@event.AggregateId).Result; customer.Apply(new ChangeEmailAddress { NewEmailAddress = "devnull@nowhere.com" }); customerRepository.Save(customer).Wait(); } } } }
//------------------------------------------------------------------------------ // <copyright file="EditorZoneBase.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls.WebParts { using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Util; public abstract class EditorZoneBase : ToolZone { private EditorPartCollection _editorParts; private const int baseIndex = 0; private const int applyVerbIndex = 1; private const int cancelVerbIndex = 2; private const int okVerbIndex = 3; private const int viewStateArrayLength = 4; private WebPartVerb _applyVerb; private WebPartVerb _cancelVerb; private WebPartVerb _okVerb; private bool _applyError; private EditorPartChrome _editorPartChrome; private const string applyEventArgument = "apply"; private const string cancelEventArgument = "cancel"; private const string okEventArgument = "ok"; protected EditorZoneBase() : base(WebPartManager.EditDisplayMode) { } [ DefaultValue(null), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty), WebCategory("Verbs"), WebSysDescription(SR.EditorZoneBase_ApplyVerb), ] public virtual WebPartVerb ApplyVerb { get { if (_applyVerb == null) { _applyVerb = new WebPartEditorApplyVerb(); _applyVerb.EventArgument = applyEventArgument; if (IsTrackingViewState) { ((IStateManager)_applyVerb).TrackViewState(); } } return _applyVerb; } } [ DefaultValue(null), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty), WebCategory("Verbs"), WebSysDescription(SR.EditorZoneBase_CancelVerb), ] public virtual WebPartVerb CancelVerb { get { if (_cancelVerb == null) { _cancelVerb = new WebPartEditorCancelVerb(); _cancelVerb.EventArgument = cancelEventArgument; if (IsTrackingViewState) { ((IStateManager)_cancelVerb).TrackViewState(); } } return _cancelVerb; } } protected override bool Display { get { return (base.Display && WebPartToEdit != null); } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public EditorPartChrome EditorPartChrome { get { if (_editorPartChrome == null) { _editorPartChrome = CreateEditorPartChrome(); } return _editorPartChrome; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public EditorPartCollection EditorParts { get { if (_editorParts == null) { WebPart webPartToEdit = WebPartToEdit; EditorPartCollection webPartEditorParts = null; if (webPartToEdit != null && webPartToEdit is IWebEditable) { webPartEditorParts = ((IWebEditable)webPartToEdit).CreateEditorParts(); } EditorPartCollection editorParts = new EditorPartCollection(webPartEditorParts, CreateEditorParts()); // Verify that each EditorPart has a nonempty ID. Don't throw an exception in the designer, // since we want only the offending control to render as an error block, not the whole CatalogZone. if (!DesignMode) { foreach (EditorPart editorPart in editorParts) { if (String.IsNullOrEmpty(editorPart.ID)) { throw new InvalidOperationException(SR.GetString(SR.EditorZoneBase_NoEditorPartID)); } } } _editorParts = editorParts; // Call EnsureChildControls to parent the EditorParts and set the WebPartToEdit, // WebPartManager, and Zone EnsureChildControls(); } return _editorParts; } } [ WebSysDefaultValue(SR.EditorZoneBase_DefaultEmptyZoneText) ] public override string EmptyZoneText { // Must look at viewstate directly instead of the property in the base class, // so we can distinguish between an unset property and a property set to String.Empty. get { string s = (string)ViewState["EmptyZoneText"]; return((s == null) ? SR.GetString(SR.EditorZoneBase_DefaultEmptyZoneText) : s); } set { ViewState["EmptyZoneText"] = value; } } [ Localizable(true), WebCategory("Behavior"), WebSysDefaultValue(SR.EditorZoneBase_DefaultErrorText), WebSysDescription(SR.EditorZoneBase_ErrorText), ] public virtual string ErrorText { get { string s = (string)ViewState["ErrorText"]; return((s == null) ? SR.GetString(SR.EditorZoneBase_DefaultErrorText) : s); } set { ViewState["ErrorText"] = value; } } [ WebSysDefaultValue(SR.EditorZoneBase_DefaultHeaderText) ] public override string HeaderText { get { string s = (string)ViewState["HeaderText"]; return((s == null) ? SR.GetString(SR.EditorZoneBase_DefaultHeaderText) : s); } set { ViewState["HeaderText"] = value; } } [ WebSysDefaultValue(SR.EditorZoneBase_DefaultInstructionText), ] public override string InstructionText { get { string s = (string)ViewState["InstructionText"]; return((s == null) ? SR.GetString(SR.EditorZoneBase_DefaultInstructionText) : s); } set { ViewState["InstructionText"] = value; } } [ DefaultValue(null), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty), WebCategory("Verbs"), WebSysDescription(SR.EditorZoneBase_OKVerb), ] public virtual WebPartVerb OKVerb { get { if (_okVerb == null) { _okVerb = new WebPartEditorOKVerb(); _okVerb.EventArgument = okEventArgument; if (IsTrackingViewState) { ((IStateManager)_okVerb).TrackViewState(); } } return _okVerb; } } protected WebPart WebPartToEdit { get { if (WebPartManager != null && WebPartManager.DisplayMode == WebPartManager.EditDisplayMode) { return WebPartManager.SelectedWebPart; } else { return null; } } } private void ApplyAndSyncChanges() { WebPart webPartToEdit = WebPartToEdit; Debug.Assert(webPartToEdit != null); if (webPartToEdit != null) { EditorPartCollection editorParts = EditorParts; foreach (EditorPart editorPart in editorParts) { if (editorPart.Display && editorPart.Visible && editorPart.ChromeState == PartChromeState.Normal) { if (!editorPart.ApplyChanges()) { _applyError = true; } } } if (!_applyError) { foreach (EditorPart editorPart in editorParts) { editorPart.SyncChanges(); } } } } /// <devdoc> /// Returns the Page to normal view. Does not call ApplyChanges to any EditorParts. /// </devdoc> protected override void Close() { if (WebPartManager != null) { WebPartManager.EndWebPartEditing(); } } /// <internalonly/> protected internal override void CreateChildControls() { ControlCollection controls = Controls; controls.Clear(); WebPart webPartToEdit = WebPartToEdit; foreach (EditorPart editorPart in EditorParts) { // webPartToEdit will be null if WebPartManager is null if (webPartToEdit != null) { editorPart.SetWebPartToEdit(webPartToEdit); editorPart.SetWebPartManager(WebPartManager); } editorPart.SetZone(this); controls.Add(editorPart); } } protected virtual EditorPartChrome CreateEditorPartChrome() { return new EditorPartChrome(this); } protected abstract EditorPartCollection CreateEditorParts(); // Called by a derived class if the list of EditorParts changes, and they want CreateEditorParts() // to be called again. protected void InvalidateEditorParts() { _editorParts = null; ChildControlsCreated = false; } protected override void LoadViewState(object savedState) { if (savedState == null) { base.LoadViewState(null); } else { object[] myState = (object[]) savedState; if (myState.Length != viewStateArrayLength) { throw new ArgumentException(SR.GetString(SR.ViewState_InvalidViewState)); } base.LoadViewState(myState[baseIndex]); if (myState[applyVerbIndex] != null) { ((IStateManager) ApplyVerb).LoadViewState(myState[applyVerbIndex]); } if (myState[cancelVerbIndex] != null) { ((IStateManager) CancelVerb).LoadViewState(myState[cancelVerbIndex]); } if (myState[okVerbIndex] != null) { ((IStateManager) OKVerb).LoadViewState(myState[okVerbIndex]); } } } protected override void OnDisplayModeChanged(object sender, WebPartDisplayModeEventArgs e) { InvalidateEditorParts(); base.OnDisplayModeChanged(sender, e); } protected internal override void OnPreRender(EventArgs e) { base.OnPreRender(e); EditorPartChrome.PerformPreRender(); } protected override void OnSelectedWebPartChanged(object sender, WebPartEventArgs e) { if (WebPartManager != null && WebPartManager.DisplayMode == WebPartManager.EditDisplayMode) { InvalidateEditorParts(); // SelectedWebPartChanged is raised when a WebPart is entering or exiting Edit mode. // We only want to call SyncChanges when a WebPart is entering Edit mode // (e.WebPart will be non-null). if (e.WebPart != null) { foreach (EditorPart editorPart in EditorParts) { editorPart.SyncChanges(); } } } base.OnSelectedWebPartChanged(sender, e); } protected override void RaisePostBackEvent(string eventArgument) { if (String.Equals(eventArgument, applyEventArgument, StringComparison.OrdinalIgnoreCase)) { if (ApplyVerb.Visible && ApplyVerb.Enabled && WebPartToEdit != null) { ApplyAndSyncChanges(); } } else if (String.Equals(eventArgument, cancelEventArgument, StringComparison.OrdinalIgnoreCase)) { if (CancelVerb.Visible && CancelVerb.Enabled && WebPartToEdit != null) { Close(); } } else if (String.Equals(eventArgument, okEventArgument, StringComparison.OrdinalIgnoreCase)) { if (OKVerb.Visible && OKVerb.Enabled && WebPartToEdit != null) { ApplyAndSyncChanges(); if (!_applyError) { // Only close the EditorZone if there were no errors applying the EditorParts Close(); } } } else { base.RaisePostBackEvent(eventArgument); } } protected internal override void Render(HtmlTextWriter writer) { if (Page != null) { Page.VerifyRenderingInServerForm(this); } base.Render(writer); } protected override void RenderBody(HtmlTextWriter writer) { RenderBodyTableBeginTag(writer); if (DesignMode) { RenderDesignerRegionBeginTag(writer, Orientation.Vertical); } if (HasControls()) { bool firstCell = true; RenderInstructionText(writer, ref firstCell); if (_applyError) { RenderErrorText(writer, ref firstCell); } EditorPartChrome chrome = EditorPartChrome; foreach (EditorPart editorPart in EditorParts) { if ((!editorPart.Display) || (!editorPart.Visible)) { continue; } writer.RenderBeginTag(HtmlTextWriterTag.Tr); if (!firstCell) { writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingTop, "0"); } else { firstCell = false; } writer.RenderBeginTag(HtmlTextWriterTag.Td); chrome.RenderEditorPart(writer, editorPart); writer.RenderEndTag(); // Td writer.RenderEndTag(); // Tr } writer.RenderBeginTag(HtmlTextWriterTag.Tr); // Mozilla renders padding on an empty TD without this attribute writer.AddStyleAttribute(HtmlTextWriterStyle.Padding, "0"); // Add an extra row with height of 100%, to [....] up any extra space // if the height of the zone is larger than its contents // Mac IE needs height=100% set on <td> instead of <tr> writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "100%"); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.RenderEndTag(); // Td writer.RenderEndTag(); // Tr } else { RenderEmptyZoneText(writer); } if (DesignMode) { RenderDesignerRegionEndTag(writer); } RenderBodyTableEndTag(writer); } private void RenderEmptyZoneText(HtmlTextWriter writer) { string emptyZoneText = EmptyZoneText; if (!String.IsNullOrEmpty(emptyZoneText)) { writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.AddAttribute(HtmlTextWriterAttribute.Valign, "top"); Style emptyZoneTextStyle = EmptyZoneTextStyle; if (!emptyZoneTextStyle.IsEmpty) { emptyZoneTextStyle.AddAttributesToRender(writer, this); } writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(emptyZoneText); writer.RenderEndTag(); // Td writer.RenderEndTag(); // Tr } } private void RenderErrorText(HtmlTextWriter writer, ref bool firstCell) { string errorText = ErrorText; if (!String.IsNullOrEmpty(errorText)) { writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.RenderBeginTag(HtmlTextWriterTag.Td); firstCell = false; Label label = new Label(); label.Text = errorText; label.Page = Page; label.ApplyStyle(ErrorStyle); label.RenderControl(writer); writer.RenderEndTag(); // Td writer.RenderEndTag(); // Tr } } private void RenderInstructionText(HtmlTextWriter writer, ref bool firstCell) { string instructionText = InstructionText; if (!String.IsNullOrEmpty(instructionText)) { writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.RenderBeginTag(HtmlTextWriterTag.Td); firstCell = false; Label label = new Label(); label.Text = instructionText; label.Page = Page; label.ApplyStyle(InstructionTextStyle); label.RenderControl(writer); writer.RenderEndTag(); // Td writer.RenderEndTag(); // Tr } } protected override void RenderVerbs(HtmlTextWriter writer) { RenderVerbsInternal(writer, new WebPartVerb[] {OKVerb, CancelVerb, ApplyVerb}); } protected override object SaveViewState() { object[] myState = new object[viewStateArrayLength]; myState[baseIndex] = base.SaveViewState(); myState[applyVerbIndex] = (_applyVerb != null) ? ((IStateManager)_applyVerb).SaveViewState() : null; myState[cancelVerbIndex] = (_cancelVerb != null) ? ((IStateManager)_cancelVerb).SaveViewState() : null; myState[okVerbIndex] = (_okVerb != null) ? ((IStateManager)_okVerb).SaveViewState() : null; for (int i=0; i < viewStateArrayLength; i++) { if (myState[i] != null) { return myState; } } // More performant to return null than an array of null values return null; } protected override void TrackViewState() { base.TrackViewState(); if (_applyVerb != null) { ((IStateManager) _applyVerb).TrackViewState(); } if (_cancelVerb != null) { ((IStateManager) _cancelVerb).TrackViewState(); } if (_okVerb != null) { ((IStateManager) _okVerb).TrackViewState(); } } } }
using System.Collections.Generic; using GitTools.Testing; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; using GitVersionCore.Tests.Helpers; using LibGit2Sharp; using NUnit.Framework; namespace GitVersionCore.Tests.IntegrationTests { [TestFixture] public class DevelopScenarios : TestBase { [Test] public void WhenDevelopHasMultipleCommitsSpecifyExistingCommitId() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); var thirdCommit = fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.3", commitId: thirdCommit.Sha); } [Test] public void WhenDevelopHasMultipleCommitsSpecifyNonExistingCommitId() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.5", commitId: "nonexistingcommitid"); } [Test] public void WhenDevelopBranchedFromTaggedCommitOnMasterVersionDoesNotChange() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.AssertFullSemver("1.0.0"); } [Test] public void CanChangeDevelopTagViaConfig() { var config = new Config { Branches = { { "develop", new BranchConfig { Tag = "alpha", SourceBranches = new List<string>() } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1", config); } [Test] public void WhenDeveloperBranchExistsDontTreatAsDevelop() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("developer")); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.0.1-developer.1+1"); // this tag should be the branch name by default, not unstable } [Test] public void WhenDevelopBranchedFromMasterMinorIsIncreased() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1"); } [Test] public void MergingReleaseBranchBackIntoDevelopWithMergingToMasterDoesBumpDevelopVersion() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("release-2.0.0")); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, "master"); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); fixture.AssertFullSemver("2.1.0-alpha.2"); } [Test] public void CanHandleContinuousDelivery() { var config = new Config { Branches = { {"develop", new BranchConfig { VersioningMode = VersioningMode.ContinuousDelivery } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeATaggedCommit("1.1.0-alpha7"); fixture.AssertFullSemver("1.1.0-alpha.7", config); } [Test] public void WhenDevelopBranchedFromMasterDetachedHeadMinorIsIncreased() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); var commit = fixture.Repository.Head.Tip; fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, commit); fixture.AssertFullSemver("1.1.0-alpha.1", onlyTrackedBranches: false); } [Test] public void InheritVersionFromReleaseBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.MakeATaggedCommit("1.0.0"); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/2.0.0"); fixture.MakeACommit(); fixture.MakeACommit(); fixture.Checkout("develop"); fixture.AssertFullSemver("1.1.0-alpha.1"); fixture.MakeACommit(); fixture.AssertFullSemver("2.1.0-alpha.1"); fixture.MergeNoFF("release/2.0.0"); fixture.AssertFullSemver("2.1.0-alpha.4"); fixture.BranchTo("feature/MyFeature"); fixture.MakeACommit(); fixture.AssertFullSemver("2.1.0-MyFeature.1+5"); } [Test] public void WhenMultipleDevelopBranchesExistAndCurrentBranchHasIncrementInheritPolicyAndCurrentCommitIsAMerge() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("bob_develop"); fixture.Repository.CreateBranch("develop"); fixture.Repository.CreateBranch("feature/x"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, "feature/x"); fixture.Repository.MakeACommit(); fixture.Repository.MergeNoFF("develop"); fixture.AssertFullSemver("1.1.0-x.1+3"); } [Test] public void TagOnHotfixShouldNotAffectDevelop() { using var fixture = new BaseGitFlowRepositoryFixture("1.2.0"); Commands.Checkout(fixture.Repository, "master"); var hotfix = fixture.Repository.CreateBranch("hotfix-1.2.1"); Commands.Checkout(fixture.Repository, hotfix); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.2.1-beta.1+1"); fixture.Repository.ApplyTag("1.2.1-beta.1"); fixture.AssertFullSemver("1.2.1-beta.1"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.3.0-alpha.2"); } [Test] public void CommitsSinceVersionSourceShouldNotGoDownUponGitFlowReleaseFinish() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); fixture.ApplyTag("1.1.0"); fixture.BranchTo("develop"); fixture.MakeACommit("commit in develop - 1"); fixture.AssertFullSemver("1.2.0-alpha.1"); fixture.BranchTo("release/1.2.0"); fixture.AssertFullSemver("1.2.0-beta.1+0"); fixture.Checkout("develop"); fixture.MakeACommit("commit in develop - 2"); fixture.MakeACommit("commit in develop - 3"); fixture.MakeACommit("commit in develop - 4"); fixture.MakeACommit("commit in develop - 5"); fixture.AssertFullSemver("1.3.0-alpha.4"); fixture.Checkout("release/1.2.0"); fixture.MakeACommit("commit in release/1.2.0 - 1"); fixture.MakeACommit("commit in release/1.2.0 - 2"); fixture.MakeACommit("commit in release/1.2.0 - 3"); fixture.AssertFullSemver("1.2.0-beta.1+3"); fixture.Checkout("master"); fixture.MergeNoFF("release/1.2.0"); fixture.ApplyTag("1.2.0"); fixture.Checkout("develop"); fixture.MergeNoFF("release/1.2.0"); fixture.MakeACommit("commit in develop - 6"); fixture.AssertFullSemver("1.3.0-alpha.9"); fixture.SequenceDiagram.Destroy("release/1.2.0"); fixture.Repository.Branches.Remove("release/1.2.0"); var expectedFullSemVer = "1.3.0-alpha.9"; fixture.AssertFullSemver(expectedFullSemVer, config); } [Test] public void CommitsSinceVersionSourceShouldNotGoDownUponMergingFeatureOnlyToDevelop() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit("commit in master - 1"); fixture.ApplyTag("1.1.0"); fixture.BranchTo("develop"); fixture.MakeACommit("commit in develop - 1"); fixture.AssertFullSemver("1.2.0-alpha.1"); fixture.BranchTo("release/1.2.0"); fixture.MakeACommit("commit in release - 1"); fixture.MakeACommit("commit in release - 2"); fixture.MakeACommit("commit in release - 3"); fixture.AssertFullSemver("1.2.0-beta.1+3"); fixture.ApplyTag("1.2.0"); fixture.Checkout("develop"); fixture.MakeACommit("commit in develop - 2"); fixture.AssertFullSemver("1.3.0-alpha.1"); fixture.MergeNoFF("release/1.2.0"); fixture.AssertFullSemver("1.3.0-alpha.5"); fixture.SequenceDiagram.Destroy("release/1.2.0"); fixture.Repository.Branches.Remove("release/1.2.0"); var expectedFullSemVer = "1.3.0-alpha.5"; fixture.AssertFullSemver(expectedFullSemVer, config); } [Test] public void PreviousPreReleaseTagShouldBeRespectedWhenCountingCommits() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeATaggedCommit("1.0.0-alpha.3"); // manual bump version fixture.MakeACommit(); fixture.MakeACommit(); fixture.AssertFullSemver("1.0.0-alpha.5"); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// LoadBalancersOperations operations. /// </summary> internal partial class LoadBalancersOperations : IServiceOperations<NetworkClient>, ILoadBalancersOperations { /// <summary> /// Initializes a new instance of the LoadBalancersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal LoadBalancersOperations(NetworkClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkClient /// </summary> public NetworkClient Client { get; private set; } /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LoadBalancer>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LoadBalancer>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<LoadBalancer>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<LoadBalancer> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LoadBalancer>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.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"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LoadBalancer>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Xml.Linq; namespace WixSharp { /// <summary> /// Enumeration representing Generic* attributes of PermissionEx element /// </summary> [Flags] public enum GenericPermission { /// <summary> /// None does not map to a valid WiX representation /// </summary> None = 0, /// <summary> /// Maps to GenericExecute='yes' of PermissionEx /// </summary> Execute = 0x001, /// <summary> /// Maps to GenericWrite='yes' of PermissionEx /// </summary> Write = 0x010, /// <summary> /// Maps to GenericRead='yes' of PermissionEx /// </summary> Read = 0x100, /// <summary> /// Maps to GenericAll='yes' of PermissionEx /// </summary> All = Execute | Write | Read } /// <summary> /// Equivalent of https://wixtoolset.org/documentation/manual/v3/xsd/wix/permission.html /// </summary> public class Permission : WixObject { /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? Append; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? ChangePermission; /// <summary> /// For a directory, the right to create a subdirectory. Only valid under a 'CreateFolder' parent. /// </summary> [Xml] public bool? CreateChild; /// <summary> /// For a directory, the right to create a file in the directory. Only valid under a 'CreateFolder' parent. /// </summary> [Xml] public bool? CreateFile; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? CreateLink; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? CreateSubkeys; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? Delete; /// <summary> /// For a directory, the right to delete a directory and all the files it contains, including read-only files. Only valid under a 'CreateFolder' parent. /// </summary> [Xml] public bool? DeleteChild; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public string Domain; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? EnumerateSubkeys; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? Execute; /// <summary> /// Bit mask for FILE_ALL_ACCESS from WinNT.h (0x001F01FF). /// </summary> [Xml] public bool? FileAllRights; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? GenericAll; /// <summary> /// The documentation is unavailable on WiX /// </summary> public bool? GenericExecute; /// <summary> /// specifying this will fail to grant read access /// </summary> [Xml] public bool? GenericRead; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? GenericWrite; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? Notify; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? Read; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? ReadAttributes; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? ReadExtendedAttributes; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? ReadPermission; /// <summary> /// Bit mask for SPECIFIC_RIGHTS_ALL from WinNT.h (0x0000FFFF). /// </summary> [Xml] public bool? SpecificRightsAll; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? Synchronize; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? TakeOwnership; /// <summary> /// For a directory, the right to traverse the directory. By default, users are assigned the BYPASS_TRAVERSE_CHECKING privilege, which ignores the FILE_TRAVERSE access right. Only valid under a 'CreateFolder' parent. /// </summary> [Xml] public bool? Traverse; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public string User; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? Write; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? WriteAttributes; /// <summary> /// The documentation is unavailable on WiX /// </summary> [Xml] public bool? WriteExtendedAttributes; } /// <summary> /// Represents applying permission(s) to the containing File entity /// </summary> /// <remarks> /// DirPermission is a Wix# representation of WiX Util:PermissionEx /// </remarks> public class DirPermission : WixEntity { /// <summary> /// Initializes a new instance of the <see cref="DirPermission"/> class. /// </summary> public DirPermission() { } /// <summary> /// Creates a FilePermission instance for <paramref name="user"/>. /// <para>Note that <see cref="DirPermission"/> inherits its parent <see cref="Dir"/> features unless /// it has it own features specified.</para> /// </summary> /// <param name="user"></param> public DirPermission(string user) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; } /// <summary> /// Creates a FilePermission instance for <paramref name="user"/>@<paramref name="domain"/> /// <para>Note that <see cref="DirPermission"/> inherits its parent <see cref="Dir"/> features unless /// it has it own features specified.</para> /// </summary> /// <param name="user"></param> /// <param name="domain"></param> public DirPermission(string user, string domain) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; Domain = domain; } /// <summary> /// Creates a FilePermission instance for <paramref name="user"/> with generic permissions described by <paramref name="permission"/> /// <para>Note that <see cref="DirPermission"/> inherits its parent <see cref="Dir"/> features unless /// it has it own features specified.</para> /// </summary> /// <param name="user"></param> /// <param name="permission"></param> public DirPermission(string user, GenericPermission permission) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; SetGenericPermission(permission); } /// <summary> /// Creates a FilePermission instance for <paramref name="user"/>@<paramref name="domain"/> with generic permissions described by <paramref name="permission"/> /// <para>Note that <see cref="DirPermission"/> inherits its parent <see cref="Dir"/> features unless /// it has it own features specified.</para> /// </summary> /// <param name="user"></param> /// <param name="domain"></param> /// <param name="permission"></param> public DirPermission(string user, string domain, GenericPermission permission) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; Domain = domain; SetGenericPermission(permission); } private void SetGenericPermission(GenericPermission permission) { if (permission == GenericPermission.All) { GenericAll = true; return; } if ((permission & GenericPermission.Execute) == GenericPermission.Execute) GenericExecute = true; if ((permission & GenericPermission.Write) == GenericPermission.Write) GenericWrite = true; if ((permission & GenericPermission.Read) == GenericPermission.Read) GenericRead = true; } /// <summary> /// Maps to the User property of PermissionEx /// </summary> public string User { get; set; } /// <summary> /// Maps to the Domain property of PermissionEx /// </summary> public string Domain { get; set; } /// <summary> /// Maps to the Append property of PermissionEx /// </summary> public bool? Append { get; set; } /// <summary> /// Maps to the ChangePermission property of PermissionEx /// </summary> public bool? ChangePermission { get; set; } /// <summary> /// Maps to the CreateChild property of PermissionEx /// </summary> public bool? CreateChild { get; set; } /// <summary> /// Maps to the CreateFile property of PermissionEx /// </summary> public bool? CreateFile { get; set; } /// <summary> /// Maps to the CreateLink property of PermissionEx /// </summary> public bool? CreateLink { get; set; } /// <summary> /// Maps to the CreateSubkeys property of PermissionEx /// </summary> public bool? CreateSubkeys { get; set; } /// <summary> /// Maps to the Delete property of PermissionEx /// </summary> public bool? Delete { get; set; } /// <summary> /// Maps to the DeleteChild property of PermissionEx /// </summary> public bool? DeleteChild { get; set; } /// <summary> /// Maps to the EnumerateSubkeys property of PermissionEx /// </summary> public bool? EnumerateSubkeys { get; set; } /// <summary> /// Maps to the Execute property of PermissionEx /// </summary> public bool? Execute { get; set; } /// <summary> /// Maps to the GenericAll property of PermissionEx /// </summary> public bool? GenericAll { get; set; } /// <summary> /// Maps to the GenericExecute property of PermissionEx /// </summary> public bool? GenericExecute { get; set; } /// <summary> /// Maps to the GenericRead property of PermissionEx /// </summary> public bool? GenericRead { get; set; } /// <summary> /// Maps to the GenericWrite property of PermissionEx /// </summary> public bool? GenericWrite { get; set; } /// <summary> /// Maps to the Notify property of PermissionEx /// </summary> public bool? Notify { get; set; } /// <summary> /// Maps to the Read property of PermissionEx /// </summary> public bool? Read { get; set; } /// <summary> /// Maps to the Readattributes property of PermissionEx /// </summary> public bool? Readattributes { get; set; } /// <summary> /// Maps to the ReadExtendedAttributes property of PermissionEx /// </summary> public bool? ReadExtendedAttributes { get; set; } /// <summary> /// Maps to the ReadPermission property of PermissionEx /// </summary> public bool? ReadPermission { get; set; } /// <summary> /// Maps to the Synchronize property of PermissionEx /// </summary> public bool? Synchronize { get; set; } /// <summary> /// Maps to the TakeOwnership property of PermissionEx /// </summary> public bool? TakeOwnership { get; set; } /// <summary> /// Maps to the Traverse property of PermissionEx /// </summary> public bool? Traverse { get; set; } /// <summary> /// Maps to the Write property of PermissionEx /// </summary> public bool? Write { get; set; } /// <summary> /// Maps to the WriteAttributes property of PermissionEx /// </summary> public bool? WriteAttributes { get; set; } /// <summary> /// Maps to the WriteExtendedAttributes property of PermissionEx /// </summary> public bool? WriteExtendedAttributes { get; set; } } /// <summary> /// Represents applying permission(s) to the containing File entity /// </summary> /// <remarks> /// FilePermission is a Wix# representation of WiX Util:PermissionEx /// </remarks> public class FilePermission : WixEntity { /// <summary> /// Creates a FilePermission instance for <paramref name="user"/> /// </summary> /// <param name="user"></param> public FilePermission(string user) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; } /// <summary> /// Creates a FilePermission instance for <paramref name="user"/>@<paramref name="domain"/> /// </summary> /// <param name="user"></param> /// <param name="domain"></param> public FilePermission(string user, string domain) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; Domain = domain; } /// <summary> /// Creates a FilePermission instance for <paramref name="user"/> with generic permissions described by <paramref name="permission"/> /// </summary> /// <param name="user"></param> /// <param name="permission"></param> public FilePermission(string user, GenericPermission permission) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; SetGenericPermission(permission); } /// <summary> /// Creates a FilePermission instance for <paramref name="user"/>@<paramref name="domain"/> with generic permissions described by <paramref name="permission"/> /// </summary> /// <param name="user"></param> /// <param name="domain"></param> /// <param name="permission"></param> public FilePermission(string user, string domain, GenericPermission permission) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; Domain = domain; SetGenericPermission(permission); } private void SetGenericPermission(GenericPermission permission) { if (permission == GenericPermission.All) { GenericAll = true; return; } if ((permission & GenericPermission.Execute) == GenericPermission.Execute) GenericExecute = true; if ((permission & GenericPermission.Write) == GenericPermission.Write) GenericWrite = true; if ((permission & GenericPermission.Read) == GenericPermission.Read) GenericRead = true; } /// <summary> /// Maps to the User property of PermissionEx /// </summary> public string User { get; set; } /// <summary> /// Maps to the Domain property of PermissionEx /// </summary> public string Domain { get; set; } /// <summary> /// Maps to the Append property of PermissionEx /// </summary> public bool? Append { get; set; } /// <summary> /// Maps to the ChangePermission property of PermissionEx /// </summary> public bool? ChangePermission { get; set; } /// <summary> /// Maps to the CreateLink property of PermissionEx /// </summary> public bool? CreateLink { get; set; } /// <summary> /// Maps to the CreateSubkeys property of PermissionEx /// </summary> public bool? CreateSubkeys { get; set; } /// <summary> /// Maps to the Delete property of PermissionEx /// </summary> public bool? Delete { get; set; } /// <summary> /// Maps to the EnumerateSubkeys property of PermissionEx /// </summary> public bool? EnumerateSubkeys { get; set; } /// <summary> /// Maps to the Execute property of PermissionEx /// </summary> public bool? Execute { get; set; } /// <summary> /// Maps to the GenericAll property of PermissionEx /// </summary> public bool? GenericAll { get; set; } /// <summary> /// Maps to the GenericExecute property of PermissionEx /// </summary> public bool? GenericExecute { get; set; } /// <summary> /// Maps to the GenericRead property of PermissionEx /// </summary> public bool? GenericRead { get; set; } /// <summary> /// Maps to the GenericWrite property of PermissionEx /// </summary> public bool? GenericWrite { get; set; } /// <summary> /// Maps to the Notify property of PermissionEx /// </summary> public bool? Notify { get; set; } /// <summary> /// Maps to the Read property of PermissionEx /// </summary> public bool? Read { get; set; } /// <summary> /// Maps to the Readattributes property of PermissionEx /// </summary> public bool? Readattributes { get; set; } /// <summary> /// Maps to the ReadExtendedAttributes property of PermissionEx /// </summary> public bool? ReadExtendedAttributes { get; set; } /// <summary> /// Maps to the ReadPermission property of PermissionEx /// </summary> public bool? ReadPermission { get; set; } /// <summary> /// Maps to the Synchronize property of PermissionEx /// </summary> public bool? Synchronize { get; set; } /// <summary> /// Maps to the TakeOwnership property of PermissionEx /// </summary> public bool? TakeOwnership { get; set; } /// <summary> /// Maps to the Write property of PermissionEx /// </summary> public bool? Write { get; set; } /// <summary> /// Maps to the WriteAttributes property of PermissionEx /// </summary> public bool? WriteAttributes { get; set; } /// <summary> /// Maps to the WriteExtendedAttributes property of PermissionEx /// </summary> public bool? WriteExtendedAttributes { get; set; } } internal static class PermissionExtensions { static void Do<T>(this T? nullable, Action<T> action) where T : struct { if (!nullable.HasValue) return; action(nullable.Value); } /// <summary> /// Adds attributes to <paramref name="permissionElement"/> representing the state of <paramref name="dirPermission"/> /// </summary> /// <param name="dirPermission"></param> /// <param name="permissionElement"></param> public static void EmitAttributes(this DirPermission dirPermission, XElement permissionElement) { //required permissionElement.SetAttributeValue("User", dirPermission.User); //optional if (dirPermission.Domain.IsNotEmpty()) permissionElement.SetAttributeValue("Domain", dirPermission.Domain); //optional dirPermission.Append.Do(b => permissionElement.SetAttributeValue("Append", b.ToYesNo())); dirPermission.ChangePermission.Do(b => permissionElement.SetAttributeValue("ChangePermission", b.ToYesNo())); dirPermission.CreateLink.Do(b => permissionElement.SetAttributeValue("CreateLink", b.ToYesNo())); dirPermission.CreateChild.Do(b => permissionElement.SetAttribute("CreateChild", b.ToYesNo())); dirPermission.CreateFile.Do(b => permissionElement.SetAttribute("CreateFile", b.ToYesNo())); dirPermission.CreateSubkeys.Do(b => permissionElement.SetAttributeValue("CreateSubkeys", b.ToYesNo())); dirPermission.Delete.Do(b => permissionElement.SetAttributeValue("Delete", b.ToYesNo())); dirPermission.DeleteChild.Do(b => permissionElement.SetAttribute("DeleteChild", b.ToYesNo())); dirPermission.EnumerateSubkeys.Do(b => permissionElement.SetAttributeValue("EnumerateSubkeys", b.ToYesNo())); dirPermission.Execute.Do(b => permissionElement.SetAttributeValue("Execute", b.ToYesNo())); dirPermission.GenericAll.Do(b => permissionElement.SetAttributeValue("GenericAll", b.ToYesNo())); dirPermission.GenericExecute.Do(b => permissionElement.SetAttributeValue("GenericExecute", b.ToYesNo())); dirPermission.GenericRead.Do(b => permissionElement.SetAttributeValue("GenericRead", b.ToYesNo())); dirPermission.GenericWrite.Do(b => permissionElement.SetAttributeValue("GenericWrite", b.ToYesNo())); dirPermission.Notify.Do(b => permissionElement.SetAttributeValue("Notify", b.ToYesNo())); dirPermission.Read.Do(b => permissionElement.SetAttributeValue("Read", b.ToYesNo())); dirPermission.Readattributes.Do(b => permissionElement.SetAttributeValue("Readattributes", b.ToYesNo())); dirPermission.ReadExtendedAttributes.Do(b => permissionElement.SetAttributeValue("ReadExtendedAttributes", b.ToYesNo())); dirPermission.ReadPermission.Do(b => permissionElement.SetAttributeValue("ReadPermission", b.ToYesNo())); dirPermission.Synchronize.Do(b => permissionElement.SetAttributeValue("Synchronize", b.ToYesNo())); dirPermission.TakeOwnership.Do(b => permissionElement.SetAttributeValue("TakeOwnership", b.ToYesNo())); dirPermission.Traverse.Do(b => permissionElement.SetAttribute("Traverse", b.ToYesNo())); dirPermission.Write.Do(b => permissionElement.SetAttributeValue("Write", b.ToYesNo())); dirPermission.WriteAttributes.Do(b => permissionElement.SetAttributeValue("WriteAttributes", b.ToYesNo())); dirPermission.WriteExtendedAttributes.Do(b => permissionElement.SetAttributeValue("WriteExtendedAttributes", b.ToYesNo())); } /// <summary> /// Adds attributes to <paramref name="permissionElement"/> representing the state of <paramref name="filePermission"/> /// </summary> /// <param name="filePermission"></param> /// <param name="permissionElement"></param> public static void EmitAttributes(this FilePermission filePermission, XElement permissionElement) { //required permissionElement.SetAttributeValue("User", filePermission.User); //optional if (filePermission.Domain.IsNotEmpty()) permissionElement.SetAttributeValue("Domain", filePermission.Domain); //optional filePermission.Append.Do(b => permissionElement.SetAttributeValue("Append", b.ToYesNo())); filePermission.ChangePermission.Do(b => permissionElement.SetAttributeValue("ChangePermission", b.ToYesNo())); filePermission.CreateLink.Do(b => permissionElement.SetAttributeValue("CreateLink", b.ToYesNo())); filePermission.CreateSubkeys.Do(b => permissionElement.SetAttributeValue("CreateSubkeys", b.ToYesNo())); filePermission.Delete.Do(b => permissionElement.SetAttributeValue("Delete", b.ToYesNo())); filePermission.EnumerateSubkeys.Do(b => permissionElement.SetAttributeValue("EnumerateSubkeys", b.ToYesNo())); filePermission.Execute.Do(b => permissionElement.SetAttributeValue("Execute", b.ToYesNo())); filePermission.GenericAll.Do(b => permissionElement.SetAttributeValue("GenericAll", b.ToYesNo())); filePermission.GenericExecute.Do(b => permissionElement.SetAttributeValue("GenericExecute", b.ToYesNo())); filePermission.GenericRead.Do(b => permissionElement.SetAttributeValue("GenericRead", b.ToYesNo())); filePermission.GenericWrite.Do(b => permissionElement.SetAttributeValue("GenericWrite", b.ToYesNo())); filePermission.Notify.Do(b => permissionElement.SetAttributeValue("Notify", b.ToYesNo())); filePermission.Read.Do(b => permissionElement.SetAttributeValue("Read", b.ToYesNo())); filePermission.Readattributes.Do(b => permissionElement.SetAttributeValue("Readattributes", b.ToYesNo())); filePermission.ReadExtendedAttributes.Do(b => permissionElement.SetAttributeValue("ReadExtendedAttributes", b.ToYesNo())); filePermission.ReadPermission.Do(b => permissionElement.SetAttributeValue("ReadPermission", b.ToYesNo())); filePermission.Synchronize.Do(b => permissionElement.SetAttributeValue("Synchronize", b.ToYesNo())); filePermission.TakeOwnership.Do(b => permissionElement.SetAttributeValue("TakeOwnership", b.ToYesNo())); filePermission.Write.Do(b => permissionElement.SetAttributeValue("Write", b.ToYesNo())); filePermission.WriteAttributes.Do(b => permissionElement.SetAttributeValue("WriteAttributes", b.ToYesNo())); filePermission.WriteExtendedAttributes.Do(b => permissionElement.SetAttributeValue("WriteExtendedAttributes", b.ToYesNo())); } } }
#region Header // // CmdDeleteUnusedRefPlanes.cs - delete unnamed non-hosting reference planes // // Copyright (C) 2014-2021 by Jeremy Tammik, Autodesk Inc. All rights reserved. // // Keywords: The Building Coder Revit API C# .NET add-in. // #endregion // Header #region Namespaces using System.Collections.Generic; using System.Linq; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.Exceptions; using Autodesk.Revit.UI; #endregion // Namespaces namespace BuildingCoder { #region Obsolete solution for Revit 2014 // Original problem description and solution: // http://thebuildingcoder.typepad.com/blog/2012/03/melbourne-devlab.html#2 // Fix for Revit 2014: // http://thebuildingcoder.typepad.com/blog/2014/02/deleting-unnamed-non-hosting-reference-planes.html /// <summary> /// Delete all reference planes that have not been /// named and are not hosting any elements. /// In other words, check whether the reference /// plane has been named. /// If not, check whether it hosts any elements. /// If not, delete it. /// Actually, to check whether it hosts any /// elements, we delete it temporarily anyway, as /// described in /// Object Relationships http://thebuildingcoder.typepad.com/blog/2010/03/object-relationships.html /// Object Relationships in VB http://thebuildingcoder.typepad.com/blog/2010/03/object-relationships-in-vb.html /// Temporary Transaction Trick Touchup http://thebuildingcoder.typepad.com/blog/2012/11/temporary-transaction-trick-touchup.html /// The deletion returns the number of elements /// deleted. If this number is greater than one (the /// ref plane itself), it hosted something. In that /// case, roll back the transaction and do not delete. /// </summary> [Transaction(TransactionMode.Manual)] internal class CmdDeleteUnusedRefPlanes_2014 : IExternalCommand { private static int _i; public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { var uiapp = commandData.Application; var uidoc = uiapp.ActiveUIDocument; var app = uiapp.Application; var doc = uidoc.Document; // Construct a parameter filter to get only // unnamed reference planes, i.e. reference // planes whose name equals the empty string: var bip = BuiltInParameter.DATUM_TEXT; var provider = new ParameterValueProvider( new ElementId(bip)); FilterStringRuleEvaluator evaluator = new FilterStringEquals(); //FilterStringRule rule = new FilterStringRule( // 2021 // provider, evaluator, "", false ); var rule = new FilterStringRule( // 2022 provider, evaluator, ""); var filter = new ElementParameterFilter(rule); var col = new FilteredElementCollector(doc) .OfClass(typeof(ReferencePlane)) .WherePasses(filter); var n = 0; var nDeleted = 0; // No need to cast ... this is pretty nifty, // I find ... grab the elements as ReferencePlane // instances, since the filter guarantees that // only ReferencePlane instances are selected. // In Revit 2014, this attempt to delete the // reference planes while iterating over the // filtered element collector throws an exception: // Autodesk.Revit.Exceptions.InvalidOperationException: // HResult=-2146233088 // Message=The iterator cannot proceed due to // changes made to the Element table in Revit's // database (typically, This can be the result // of an Element deletion). // //foreach( ReferencePlane rp in col ) //{ // ++n; // nDeleted += DeleteIfNotHosting( rp ) ? 1 : 0; //} var ids = col.ToElementIds(); n = ids.Count(); if (0 < n) { using var tx = new Transaction(doc); tx.Start($"Delete {n} ReferencePlane{Util.PluralSuffix(n)}"); // This also causes the exception "One or more of // the elementIds cannot be deleted. Parameter // name: elementIds // //ICollection<ElementId> ids2 = doc.Delete( // ids ); //nDeleted = ids2.Count(); var ids2 = new List<ElementId>( ids); foreach (var id in ids2) try { var ids3 = doc.Delete( id); nDeleted += ids3.Count; } catch (ArgumentException) { } tx.Commit(); } Util.InfoMsg(string.Format( "{0} unnamed reference plane{1} examined, " + "{2} element{3} in total were deleted.", n, Util.PluralSuffix(n), nDeleted, Util.PluralSuffix(nDeleted))); return Result.Succeeded; } /// <summary> /// Delete the given reference plane /// if it is not hosting anything. /// </summary> /// <returns> /// True if the given reference plane /// was in fact deleted, else false. /// </returns> private bool DeleteIfNotHosting(ReferencePlane rp) { var rc = false; var doc = rp.Document; using var tx = new Transaction(doc); tx.Start($"Delete ReferencePlane {++_i}"); // Deletion simply fails if the reference // plane hosts anything. If so, the return // value ids collection is null. // In Revit 2014, in that case, the call // throws an exception "ArgumentException: // ElementId cannot be deleted." try { var ids = doc.Delete( rp.Id); tx.Commit(); rc = true; } catch (System.ArgumentException) { tx.RollBack(); } return rc; } } #endregion // Obsolete solution for Revit 2014 #region Broken command in Revit 2019 shared by Austin Sudtelgte [TransactionAttribute(TransactionMode.Manual)] public class BrokenCommand : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { var uiapp = commandData.Application; var uidoc = uiapp.ActiveUIDocument; var doc = uidoc.Document; // There is likely an easier way to do this using // an exclusion filter but this being my first foray // into filtering with Revit, I couldn't get that working. var filt = new FilteredElementCollector(doc); var refIDs = filt.OfClass(typeof(ReferencePlane)).ToElementIds().ToList(); using var tg = new TransactionGroup(doc); tg.Start("Remove Un-Used Reference Planes"); foreach (var id in refIDs) { var filt2 = new ElementClassFilter(typeof(FamilyInstance)); var filt3 = new ElementParameterFilter(new FilterElementIdRule(new ParameterValueProvider(new ElementId(BuiltInParameter.HOST_ID_PARAM)), new FilterNumericEquals(), id)); var filt4 = new LogicalAndFilter(filt2, filt3); var thing = new FilteredElementCollector(doc); using var t = new Transaction(doc); // Check for hosted elements on the plane if (thing.WherePasses(filt4).Count() == 0) { t.Start("Do The Thing"); #if Revit2018 if (doc.GetElement(id).GetDependentElements(new ElementClassFilter(typeof(FamilyInstance))).Count == 0) { doc.Delete(id); } t.Commit(); #else // Make sure there is nothing measuring to the plane if (doc.Delete(id).Count() > 1) t.Dispose(); // Skipped else // Deleted t.Commit(); #endif } } tg.Assimilate(); return Result.Succeeded; } } #endregion // Broken command in Revit 2019 by Austin Sudtelgte #region New working command in Revit 2019 by Austin Sudtelgte [TransactionAttribute(TransactionMode.Manual)] public class CmdDeleteUnusedRefPlanes : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { var uiapp = commandData.Application; var uidoc = uiapp.ActiveUIDocument; var doc = uidoc.Document; var refplaneids = new FilteredElementCollector(doc) .OfClass(typeof(ReferencePlane)) .ToElementIds(); using var tg = new TransactionGroup(doc); tg.Start("Remove unused reference planes"); var instances = new FilteredElementCollector(doc) .OfClass(typeof(FamilyInstance)); var toKeep = new Dictionary<ElementId, int>(); foreach (FamilyInstance i in instances) // Ensure the element is hosted if (null != i.Host) { var hostId = i.Host.Id; // Check list to see if we've already added this plane if (!toKeep.ContainsKey(hostId)) toKeep.Add(hostId, 0); ++toKeep[hostId]; } // Loop through reference planes and // delete the ones not in the list toKeep. foreach (var refid in refplaneids) if (!toKeep.ContainsKey(refid)) { using var t = new Transaction(doc); t.Start($"Removing plane {doc.GetElement(refid).Name}"); // Ensure there are no dimensions measuring to the plane if (doc.Delete(refid).Count > 1) t.Dispose(); else t.Commit(); } tg.Assimilate(); return Result.Succeeded; } } #endregion // New working command in Revit 2019 by Austin Sudtelgte }
/* Copyright (c) 2006-2008 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. */ /* Change history * Oct 13 2008 Joe Feser joseph.feser@gmail.com * Converted ArrayLists and other .NET 1.1 collections to use Generics * Combined IExtensionElement and IExtensionElementFactory interfaces * */ using System; using System.Collections; using System.Text; using System.Xml; using Google.GData.Client; using System.Globalization; using System.Collections.Generic; namespace Google.GData.Extensions { /// <summary> /// base class to implement extensions holding extensions /// TODO: at one point think about using this as the base for atom:base /// as there is some utility overlap between the 2 of them /// </summary> public class SimpleContainer : ExtensionBase, IExtensionContainer { private ExtensionList extensions; private ExtensionList extensionFactories; /// <summary> /// constructor /// </summary> /// <param name="name">the xml name</param> /// <param name="prefix">the xml prefix</param> /// <param name="ns">the xml namespace</param> protected SimpleContainer(string name, string prefix, string ns) : base(name, prefix, ns) { } #region overloaded for persistence ////////////////////////////////////////////////////////////////////// /// <summary>the list of extensions for this container /// the elements in that list MUST implement IExtensionElementFactory /// and IExtensionElement</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public ExtensionList ExtensionElements { get { if (this.extensions == null) { this.extensions = new ExtensionList(this); } return this.extensions; } } /// <summary> /// Finds a specific ExtensionElement based on it's local name /// and it's namespace. If namespace is NULL, the first one where /// the localname matches is found. If there are extensionelements that do /// not implment ExtensionElementFactory, they will not be taken into account /// </summary> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the elementToPersist</param> /// <returns>Object</returns> public IExtensionElementFactory FindExtension(string localName, string ns) { return Utilities.FindExtension(this.ExtensionElements, localName, ns); } /// <summary> /// all extension elements that match a namespace/localname /// given will be removed and the new one will be inserted /// </summary> /// <param name="localName">the local name to find</param> /// <param name="ns">the namespace to match, if null, ns is ignored</param> /// <param name="obj">the new element to put in</param> public void ReplaceExtension(string localName, string ns, IExtensionElementFactory obj) { DeleteExtensions(localName, ns); this.ExtensionElements.Add(obj); } /// <summary> /// all extension element factories that match a namespace/localname /// given will be removed and the new one will be inserted /// </summary> /// <param name="localName">the local name to find</param> /// <param name="ns">the namespace to match, if null, ns is ignored</param> /// <param name="obj">the new element to put in</param> public void ReplaceFactory(string localName, string ns, IExtensionElementFactory obj) { ExtensionList arr = Utilities.FindExtensions(this.ExtensionFactories, localName, ns, new ExtensionList(this)); foreach (IExtensionElementFactory ob in arr) { this.ExtensionFactories.Remove(ob); } this.ExtensionFactories.Add(obj); } /// <summary> /// Finds all ExtensionElement based on it's local name /// and it's namespace. If namespace is NULL, allwhere /// the localname matches is found. If there are extensionelements that do /// not implment ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the element to find</param> /// <returns>none</returns> public ExtensionList FindExtensions(string localName, string ns) { return Utilities.FindExtensions(this.ExtensionElements, localName, ns, new ExtensionList(this)); } /// <summary> /// Finds all ExtensionElement based on it's local name /// and it's namespace. If namespace is NULL, allwhere /// the localname matches is found. If there are extensionelements that do /// not implment ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the element to find</param> /// <returns>none</returns> public List<T> FindExtensions<T>(string localName, string ns) where T : IExtensionElementFactory { return Utilities.FindExtensions<T>(this.ExtensionElements, localName, ns); } /// <summary> /// Delete's all Extensions from the Extension list that match /// a localName and a Namespace. /// </summary> /// <param name="localName">the local name to find</param> /// <param name="ns">the namespace to match, if null, ns is ignored</param> /// <returns>int - the number of deleted extensions</returns> public int DeleteExtensions(string localName, string ns) { // Find them first ExtensionList arr = FindExtensions(localName, ns); foreach (IExtensionElementFactory ob in arr) { this.extensions.Remove(ob); } return arr.Count; } ////////////////////////////////////////////////////////////////////// /// <summary>the list of extensions for this container /// the elements in that list MUST implement IExtensionElementFactory /// and IExtensionElement</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public ExtensionList ExtensionFactories { get { if (this.extensionFactories == null) { this.extensionFactories = new ExtensionList(this); } return this.extensionFactories; } } // end of accessor public ExtensionList Extensions ////////////////////////////////////////////////////////////////////// /// <summary>Parses an xml node to create a Who object.</summary> /// <param name="node">the node to work on, can be NULL</param> /// <param name="parser">the xml parser to use if we need to dive deeper</param> /// <returns>the created SimpleElement object</returns> ////////////////////////////////////////////////////////////////////// public override IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { Tracing.TraceCall("for: " + XmlName); if (node != null) { object localname = node.LocalName; if (localname.Equals(this.XmlName) == false || node.NamespaceURI.Equals(this.XmlNameSpace) == false) { return null; } } SimpleContainer sc = null; // create a new container sc = this.MemberwiseClone() as SimpleContainer; sc.InitInstance(this); sc.ProcessAttributes(node); sc.ProcessChildNodes(node, parser); return sc; } /// <summary> /// need so setup the namespace based on the version information /// </summary> protected override void VersionInfoChanged() { base.VersionInfoChanged(); this.VersionInfo.ImprintVersion(this.extensions); this.VersionInfo.ImprintVersion(this.extensionFactories); } /// <summary> /// used to copy the unknown childnodes for later saving /// </summary> /// <param name="node">the node to process</param> /// <param name="parser">the feed parser to pass down if need be</param> public override void ProcessChildNodes(XmlNode node, AtomFeedParser parser) { if (node != null && node.HasChildNodes) { XmlNode childNode = node.FirstChild; while (childNode != null) { bool fProcessed = false; if (childNode is XmlElement) { foreach (IExtensionElementFactory f in this.ExtensionFactories) { if (String.Compare(childNode.NamespaceURI, f.XmlNameSpace) == 0) { if (String.Compare(childNode.LocalName, f.XmlName) == 0) { Tracing.TraceMsg("Added extension to SimpleContainer for: " + f.XmlName); ExtensionElements.Add(f.CreateInstance(childNode, parser)); fProcessed = true; break; } } } } if (fProcessed == false) { this.ChildNodes.Add(childNode); } childNode = childNode.NextSibling; } } } /// <summary> /// saves out the inner xml, so all of our subelements /// get's called from Save, whcih takes care of saving attributes /// </summary> /// <param name="writer"></param> public override void SaveInnerXml(XmlWriter writer) { if (this.extensions != null) { foreach (IExtensionElementFactory e in this.ExtensionElements) { e.Save(writer); } } } protected void SetStringValue<T>(string value, string elementName, string ns) where T : SimpleElement, new() { T v = null; if (String.IsNullOrEmpty(value) == false) { v = new T(); v.Value = value; } ReplaceExtension(elementName, ns, v); } protected string GetStringValue<T>(string elementName, string ns) where T : SimpleElement { T e = FindExtension(elementName, ns) as T; if (e!= null) { return e.Value; } return null; } #endregion } }
//--------------------------------------------------------------------------- // // <copyright file="XamlFilter.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // Implements an indexing filter for XAML streams. // Invoked by the PackageFilter. // // History: // 02/02/2004: BruceMac: Stubs // 02/16/2004: JohnLarc: Initial implementation // 08/26/2004: JohnLarc: Removed access to indexing filters from managed code. // 07/18/2005: ArindamB: Moved from XamlFilterImpl to XamlFilter, which // implements IManagedFilter instead of ManagedFilterBase. //--------------------------------------------------------------------------- #if DEBUG // #define TRACE #endif using System; using System.IO; using System.Xml; using MS.Win32; // For SafeNativeMethods using System.Globalization; // For CultureInfo using System.Diagnostics; // For Assert using System.Collections; // For Stack and Hashtable using System.Collections.Generic; // For List<> using System.Runtime.InteropServices; // For COMException using System.Runtime.InteropServices.ComTypes; // For IStream, etc. using System.Windows; // for ExceptionStringTable using MS.Internal.Interop; // for CHUNK_BREAKTYPE (and other IFilter-related definitions) using MS.Internal; // for Invariant namespace MS.Internal.IO.Packaging { #region XamlFilter /// <summary> /// The class that supports content extraction from XAML files for indexing purposes. /// Note: It would be nice to have fixed page content extractor look for flow elements in a fixed page. /// This however, is not really doable: FixedPageContentExtractor is XSLT-based, not reader-based. /// It cannot do anything more efficiently than what XamlFilter is currently doing. /// The "flow pass" on a DOM reader for a fixed page does not entail any redundant IO or DOM building. /// </summary> internal partial class XamlFilter : IManagedFilter { #region Nested Types /// <summary> /// The following enumeration makes it easier to keep track of the filter's multi-modal behavior. /// /// Each state implements a distinct method for collecting the next content unit, as follows: /// /// Uninitialized Return appropriate errors from GetChunk and GetText. /// FindNextUnit Standard mode. Return content as it is discovered in markup. /// UseContentExtractor Retrieve content from a FixedPageContentExtractor object (expected to /// perform adjacency analysis). /// FindNextFlowUnit Look for content in markup ignoring fixed-format markup (second pass over a /// fixed page). /// EndOfStream Return appropriate errors from GetChunk and GetText. /// /// /// Transitions between these states are handled as follows: /// /// state | transition | action | next state /// -------- | ------------ | -------- | ------------ /// Uninitialized | constructor | create an XML reader | FindNextUnit /// | | | /// FindNextUnit | end of reader | clean up | EndOfStream /// | | | /// FindNextUnit | FixedPage tag | create FixedPageContentExtractor, | UseContentExtractor /// | | save a DOM of the FixedPage | /// | | | /// UseContentExtractor | end of extractor | create sub-reader from FixedPage DOM,| FindNextFlowUnit /// | | save top-level reader | /// | | | /// FindNextFlowUnit | end of reader | restore top-level reader | FindNextUnit /// | | | /// /// </summary> internal enum FilterState { Uninitialized =1, FindNextUnit, FindNextFlowUnit, UseContentExtractor, EndOfStream }; /// <summary> /// A single reader position on an element start may correspond to 3 distinct states depending on /// whether the title and/or content property in the start tag has already been processed. /// </summary> [Flags] internal enum AttributesToIgnore { None =0, Title =1, Content =2 }; #endregion Nested Types #region Internal Constructors /// <summary> /// The class constructor initializes trace and event logging. /// </summary> static XamlFilter() { #if TRACE EventLog xamlFilterEventLog = new EventLog(); xamlFilterEventLog.Log = "Application"; xamlFilterEventLog.Source = "XAML filter"; Trace.Listeners.Add(new EventLogTraceListener(xamlFilterEventLog)); #endif } /// <summary> /// Constructor. Does initialization. /// </summary> /// <param name="stream">xaml stream to filter</param> internal XamlFilter(Stream stream) { #if TRACE System.Diagnostics.Trace.TraceInformation("New Xaml filter created."); #endif _lcidDictionary = new Dictionary<string, uint>(StringComparer.OrdinalIgnoreCase); _contextStack = new Stack(32); InitializeDeclaredFields(); _xamlStream = stream; // Create a XAML reader (field _xamlReader) on the stream. CreateXmlReader(); // Reflect load in filter's state. _filterState = FilterState.FindNextUnit; } /// <remarks> /// This function is called from the constructor. It makes the object re-initializable, /// which would come in handy if the XamlFilter is ever made visible to unmanaged code /// and Load is allowed to be called multiple times. /// </remarks> private void InitializeDeclaredFields() { // Initialize context variables. ClearStack(); _filterState = FilterState.Uninitialized; // Initialize current ID. _currentChunkID = 0; // Initialize the content model dictionary. // Note: Hashtable is not IDisposable. LoadContentDescriptorDictionary(); // Misc. initializations. _countOfCharactersReturned = 0; _currentContent = null; _indexingContentUnit = null; _expectingBlockStart = true; // If text data occurred at top level, it would be a block start. _topLevelReader = null; _fixedPageContentExtractor = null; _fixedPageDomTree = null; } #endregion Internal Constructors #region Managed IFilter API /// <summary> /// Managed counterpart of IFilter.Init. /// </summary> /// <param name="grfFlags">Usage flags. Only IFILTER_INIT_CANON_PARAGRAPHS can be meaningfully /// honored by the XAML filter.</param> /// <param name="aAttributes">array of Managed FULLPROPSPEC structs to restrict responses</param> /// <returns>IFILTER_FLAGS_NONE, meaning the caller should not try to retrieve OLE property using /// IPropertyStorage on the Xaml part.</returns> /// <remarks>Input parameters are ignored because this filter never returns any property value.</remarks> public IFILTER_FLAGS Init( IFILTER_INIT grfFlags, // IFILTER_INIT value ManagedFullPropSpec[] aAttributes) // restrict responses to the specified attributes { // // Content is filtered either if no attributes are specified, // or if there are attributes specified, the attribute with PSGUID_STORAGE // property set and PID_STG_CONTENTS property id is present. // _filterContents = true; if (aAttributes != null && aAttributes.Length > 0) { _filterContents = false; for (int i = 0; i < aAttributes.Length; i++) { if (aAttributes[i].Guid == IndexingFilterMarshaler.PSGUID_STORAGE && aAttributes[i].Property.PropType == PropSpecType.Id && aAttributes[i].Property.PropId == (uint)MS.Internal.Interop.PID_STG.CONTENTS) { _filterContents = true; break; } } } // The only flag in grfFlags that makes sense to honor is IFILTER_INIT_CANON_PARAGRAPHS _returnCanonicalParagraphBreaks = ((grfFlags & IFILTER_INIT.IFILTER_INIT_CANON_PARAGRAPHS) != 0); // Return zero value to indicate that the client code should not take any special steps // to retrieve OLE properties. This might have to change if filtering loose Xaml is supported. return IFILTER_FLAGS.IFILTER_FLAGS_NONE; } /// <summary> /// Managed counterpart of IFilter.GetChunk. /// </summary> /// <returns> /// Chunk descriptor. /// </returns> /// <remarks> /// On end of stream, this function will return null. /// </remarks> public ManagedChunk GetChunk() { if (!_filterContents) { // Contents not being filtered, no chunks to return in that case. _currentContent = null; // End of chunks. return null; } IndexingContentUnit contentUnit; // If client code forgot to load the stream, throw appropriate exception. if (_xamlReader == null) { throw new COMException(SR.Get(SRID.FilterGetChunkNoStream), (int)FilterErrorCode.FILTER_E_ACCESS); } // If at end of chunks, report the condition. if (_filterState == FilterState.EndOfStream) { //Ensure _xamlReader has been closed EnsureXmlReaderIsClosed(); // End of chunks. return null; } try { contentUnit = NextContentUnit(); } catch (XmlException xmlException) { //Ensure _xamlReader has been closed EnsureXmlReaderIsClosed(); // Return FILTER_E_UNKNOWNFORMAT for ill-formed documents. throw new COMException(xmlException.Message, (int)FilterErrorCode.FILTER_E_UNKNOWNFORMAT); } if (contentUnit == null) { // Update text information. _currentContent = null; //Ensure _xamlReader has been closed EnsureXmlReaderIsClosed(); // Report end of stream by indicating end of chunks. return null; } // Store the text for returning in GetText. _currentContent = contentUnit.Text; // Record the fact that GetText hasn't been called on this chunk. _countOfCharactersReturned = 0; return contentUnit; } /// <summary> /// Return a maximum of bufferCharacterCount characters (*not* bytes) from the current content unit. /// </summary> public String GetText(int bufferCharacterCount) { //BufferCharacterCount should be non-negative Debug.Assert(bufferCharacterCount >= 0); if (_currentContent == null) { SecurityHelper.ThrowExceptionForHR((int)FilterErrorCode.FILTER_E_NO_TEXT); } int numCharactersToReturn = _currentContent.Length - _countOfCharactersReturned; if (numCharactersToReturn <= 0) { SecurityHelper.ThrowExceptionForHR((int)FilterErrorCode.FILTER_E_NO_MORE_TEXT); } // Return at most bufferCharacterCount characters. The marshaler makes sure it can add a terminating // NULL beyond the end of the string that is returned. if (numCharactersToReturn > bufferCharacterCount) { numCharactersToReturn = bufferCharacterCount; } String result = _currentContent.Substring(_countOfCharactersReturned, numCharactersToReturn); _countOfCharactersReturned += numCharactersToReturn; return result; } /// <summary> /// The XAML indexing filter never returns property values. /// </summary> public Object GetValue() { SecurityHelper.ThrowExceptionForHR((int)FilterErrorCode.FILTER_E_NO_VALUES); return null; } #endregion Managed IFilter API #region Internal Methods #if DEBUG internal string DumpElementTable() { ICollection keys = _xamlElementContentDescriptorDictionary.Keys; ICollection values = _xamlElementContentDescriptorDictionary.Values; int length = keys.Count; ElementTableKey[] keyList = new ElementTableKey[length]; ContentDescriptor[] valueList = new ContentDescriptor[length]; keys.CopyTo(keyList, 0); values.CopyTo(valueList,0); string result = ""; for (int i = 0; i < length; ++i) { result += string.Format("{0}: [{1} -> {2}]\n", i, keyList[i], valueList[i]); } return result; } #endif ///<summary>Return the next text chunk, or null at end of stream.</summary> internal IndexingContentUnit NextContentUnit() { // Loop until we are able to return some content or encounter an end of file. IndexingContentUnit nextContentUnit = null; while (nextContentUnit == null) { // If we have a content extractor delivering content units for us, use it. if (_filterState == FilterState.UseContentExtractor) { Debug.Assert(_fixedPageContentExtractor != null); // If we've consumed all the glyph run info, switch to a mode in which only the flow content // of the fixed page just scanned will be returned. if (_fixedPageContentExtractor.AtEndOfPage) { // Discard extractor. _fixedPageContentExtractor = null; // Set up reader. _topLevelReader = _xamlReader; _xamlReader = new XmlNodeReader(_fixedPageDomTree.DocumentElement); // Transition to flow-only mode. _filterState = FilterState.FindNextFlowUnit; } else { bool chunkIsInline; uint lcid; string chunk = _fixedPageContentExtractor.NextGlyphContent(out chunkIsInline, out lcid); _expectingBlockStart = !chunkIsInline; return BuildIndexingContentUnit(chunk, lcid); } } if (_xamlReader.EOF) { switch (_filterState) { // If in standard mode, return a null chunk to signal the end of all chunks. case FilterState.FindNextUnit: // A non-empty stack at this point could only be attributable to an internal error, // for an early EOF would have been reported as an XML exception by the XML reader. Debug.Assert(_contextStack.Count == 0); _filterState = FilterState.EndOfStream; return null; // If processing a fixed page, revert to top-level XML reader. case FilterState.FindNextFlowUnit: Debug.Assert(_topLevelReader != null); _xamlReader.Close(); _xamlReader = _topLevelReader; _filterState = FilterState.FindNextUnit; break; default: Debug.Assert(false); break; } } switch (_xamlReader.NodeType) { // If current token is a text element, // if it can be part of its parent's content, return a chunk; // else, skip. case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: nextContentUnit = HandleTextData(); continue; // If current token is an element start, then, // if appropriate, extract chunk text from an attribute // else, record content information and recurse. case XmlNodeType.Element: nextContentUnit = HandleElementStart(); continue; // On end of element, restore context data (pop, etc.) and look further. case XmlNodeType.EndElement: nextContentUnit = HandleElementEnd(); continue; // Default action is to ignore current token and look further. // Note that non-significant whitespace is handled here. default: _xamlReader.Read(); // Consume current token. continue; } } return nextContentUnit; } /// <summary> /// Load a hash table to map qualified element names to content descriptors. /// </summary> private void LoadContentDescriptorDictionary() { // Invoke init function that is generated at build time. InitElementDictionary(); } #endregion Internal Methods #region Private Methods /// <summary>Ancillary function of NextContentUnit(). Create new chunk, taking _contextStack into /// account, and updating it if needed.</summary> private IndexingContentUnit BuildIndexingContentUnit(string text, uint lcid) { CHUNK_BREAKTYPE breakType = CHUNK_BREAKTYPE.CHUNK_NO_BREAK; // If a paragraph break is expected, reflect this in the new chunk. if (_expectingBlockStart) { breakType = CHUNK_BREAKTYPE.CHUNK_EOP; if (_returnCanonicalParagraphBreaks) text = _paragraphSeparator + text; } if (_indexingContentUnit == null) { _indexingContentUnit = new IndexingContentUnit(text, AllocateChunkID(), breakType, _propSpec, lcid); } else { // Optimization: reuse indexing content unit. _indexingContentUnit.InitIndexingContentUnit(text, AllocateChunkID(), breakType, _propSpec, lcid); } // Until proven separated (by the occurrence of a block tag), right neighbors are contiguous. _expectingBlockStart = false; return _indexingContentUnit; } ///<summary>Obtain a content descriptor for a custom element not found in the dictionary.</summary> /// <remarks> /// There is currently no general way of extracting information about custom elements, /// so the default descriptor is systematically returned. /// </remarks> private ContentDescriptor GetContentInformationAboutCustomElement(ElementTableKey customElement) { return _defaultContentDescriptor; } ///<summary> /// If current token is a text element, /// assume it can be part of its parent's content and return a chunk. ///</summary> ///<remarks> /// Ancillary function of NextContentUnit. ///</remarks> private IndexingContentUnit HandleTextData() { ContentDescriptor topOfStack = TopOfStack(); if (topOfStack != null) { // The descendants of elements with HasIndexableContent set to false get skipped. Debug.Assert(topOfStack.HasIndexableContent); // Return a chunk with appropriate block-break information. IndexingContentUnit result = BuildIndexingContentUnit(_xamlReader.Value, GetCurrentLcid()); _xamlReader.Read(); // Move past data just processed. return result; } else { // Bad Xaml (no top-level element). The Xaml filter should at some point raise an exception. // Just to be safe, ignore all content when in this state. _xamlReader.Read(); // Skip data. return null; } } ///<summary> /// If current token is an element start, then, /// if appropriate, extract chunk text from an attribute /// else, record content information and recurse. ///</summary> ///<remarks> /// Ancillary function of NextContentUnit. ///</remarks> private IndexingContentUnit HandleElementStart() { ElementTableKey elementFullName = new ElementTableKey(_xamlReader.NamespaceURI, _xamlReader.LocalName); string propertyName; // Handle the case of a complex property (e.g. Button.Content). if (IsPrefixedPropertyName(elementFullName.BaseName, out propertyName)) { ContentDescriptor topOfStack = TopOfStack(); // Handle the semantically incorrect case of a compound property occurring at the root // by ignoring it totally. if (topOfStack == null) { SkipCurrentElement(); return null; } // Index the text children of property elements only if they are content or title properties. bool elementIsIndexable = ( elementFullName.XmlNamespace.Equals(ElementTableKey.XamlNamespace, StringComparison.Ordinal) && ( propertyName == topOfStack.ContentProp || propertyName == topOfStack.TitleProp )); if (!elementIsIndexable) { // Skip element together with all its descendants. SkipCurrentElement(); return null; } // Push descriptor, advance reader, and have caller look further. Push( new ContentDescriptor( elementIsIndexable, TopOfStack().IsInline, String.Empty, // has potential text content, but no content property null)); // no title property _xamlReader.Read(); return null; } // Handle fixed-format markup in a special way (because assumptions for building // content descriptors don't work for these and they require actions beyond what // is stated in content descriptors). // Note: The elementFullyHandled boolean is required as the nextUnit returned can // be null in both cases - when element is fully handled and when its not. bool elementFullyHandled; IndexingContentUnit nextUnit = HandleFixedFormatTag(elementFullName, out elementFullyHandled); if (elementFullyHandled) return nextUnit; else { // When HandleFixedFormatTag declines to handle a tag because it is not fixed-format, it // will return null. Invariant.Assert(nextUnit == null); } // Obtain a content descriptor for the current element. ContentDescriptor elementDescriptor = (ContentDescriptor) _xamlElementContentDescriptorDictionary[elementFullName]; if (elementDescriptor == null) { if (elementFullName.XmlNamespace.Equals(ElementTableKey.XamlNamespace, StringComparison.Ordinal)) { elementDescriptor = _defaultContentDescriptor; } else if (elementFullName.XmlNamespace.Equals(_inDocumentCodeURI, StringComparison.Ordinal)) { elementDescriptor = _nonIndexableElementDescriptor; } else { elementDescriptor = GetContentInformationAboutCustomElement(elementFullName); } _xamlElementContentDescriptorDictionary.Add(elementFullName, elementDescriptor); } // If the element has no indexable content, skip all its descendants. if (!elementDescriptor.HasIndexableContent) { SkipCurrentElement(); return null; } // If appropriate, retrieve title from an attribute. string title = null; if ( elementDescriptor.TitleProp != null && (_attributesToIgnore & AttributesToIgnore.Title) == 0 ) { title = GetPropertyAsAttribute(elementDescriptor.TitleProp); if (title != null && title.Length > 0) { // Leave the reader in its present state, but return the title as a block chunk, // and mark this attribute as processed. _attributesToIgnore |= AttributesToIgnore.Title; _expectingBlockStart = true; IndexingContentUnit titleContent = BuildIndexingContentUnit(title, GetCurrentLcid()); _expectingBlockStart = true; // Simulate a stack pop for a block element. return titleContent; } } // If appropriate, retrieve content from an attribute. string content = null; if ( elementDescriptor.ContentProp != null && (_attributesToIgnore & AttributesToIgnore.Content) == 0 ) { content = GetPropertyAsAttribute(elementDescriptor.ContentProp); if (content != null && content.Length > 0) { // Leave the reader in its present state, but mark the content attribute // as processed. _attributesToIgnore |= AttributesToIgnore.Content; // Create a new chunk with appropriate break data. if (!elementDescriptor.IsInline) { _expectingBlockStart = true; } IndexingContentUnit result = BuildIndexingContentUnit(content, GetCurrentLcid()); // Emulate a stack pop for the content attribute (which never gets pushed on the stack). _expectingBlockStart = !elementDescriptor.IsInline; return result; } } // Reset the attribute flag, since we are going to change the reader's state. _attributesToIgnore = AttributesToIgnore.None; // Handle the special case of an empty element: no descendants, but a possible paragraph break. if (_xamlReader.IsEmptyElement) { if (!elementDescriptor.IsInline) _expectingBlockStart = true; // Have caller search for content past the tag. _xamlReader.Read(); return null; } // Have caller look for content in descendants. Push(elementDescriptor); _xamlReader.Read(); // skip start-tag return null; } ///<summary> /// On end of element, restore context data (pop, etc.) and look further. ///</summary> ///<remarks> /// Ancillary function of NextContentUnit. ///</remarks> private IndexingContentUnit HandleElementEnd() { // Pop current descriptor. ContentDescriptor item = Pop(); // Consume end-tag. _xamlReader.Read(); return null; } /// <summary> /// If the current tag is one of Glyphs, FixedPage or PageContent, process it adequately /// and return the next content unit or null (if not supposed to return content from fixed format). /// Otherwise, set 'handled' to false to tell the caller we didn't do anything useful. /// </summary> private IndexingContentUnit HandleFixedFormatTag(ElementTableKey elementFullName, out bool handled) { handled = true; // Not true until we return, but this is the most convenient default. if (!elementFullName.XmlNamespace.Equals(ElementTableKey.FixedMarkupNamespace, StringComparison.Ordinal)) { handled = false; // Let caller handle that tag. return null; } if (String.CompareOrdinal(elementFullName.BaseName, _glyphRunName) == 0) { // Ignore glyph runs during flow pass over a FixedPage. if (_filterState == FilterState.FindNextFlowUnit) { SkipCurrentElement(); return null; } else { return ProcessGlyphRun(); } } if (String.CompareOrdinal(elementFullName.BaseName, _fixedPageName) == 0) { // Ignore FixedPage element (i.e. root element) during flow pass over a fixed page. if (_filterState == FilterState.FindNextFlowUnit) { Push(_defaultContentDescriptor); _xamlReader.Read(); return null; } else { return ProcessFixedPage(); } } if (String.CompareOrdinal(elementFullName.BaseName, _pageContentName) == 0) { // If the element has a Source attribute, any inlined content should be ignored. string sourceUri = _xamlReader.GetAttribute(_pageContentSourceAttribute); if (sourceUri != null) { SkipCurrentElement(); return null; } else { // Have NextContentUnit() look for content in descendants. Push( _defaultContentDescriptor); _xamlReader.Read(); return null; } } // No useful work was done. Report 'unhandled'. handled = false; return null; } /// <summary> /// Handle the presence of a glyph run in the middle of flow markup by extracting /// its UnicodeString attribute and considering it a separate paragraph. /// </summary> /// <remarks> /// The handling of glyph runs inside fixed pages is performed in ProcessFixedPage. /// </remarks> private IndexingContentUnit ProcessGlyphRun() { Debug.Assert(_xamlReader != null); string textContent = _xamlReader.GetAttribute(_unicodeStringAttribute); if (textContent == null || textContent.Length == 0) { SkipCurrentElement(); return null; } _expectingBlockStart = true; // Read Lcid at current position and advance reader to next element before returning. uint lcid = GetCurrentLcid(); SkipCurrentElement(); return BuildIndexingContentUnit(textContent, lcid); } /// <summary> /// Load FixedPage element into a DOM tree to initialize a FixedPageContentExtractor. /// The content extractor will then be used to incrementally return the content of the fixed page. /// </summary> private IndexingContentUnit ProcessFixedPage() { // Reader is positioned on the start-tag for a FixedPage element. Debug.Assert(String.CompareOrdinal(_xamlReader.LocalName, _fixedPageName) == 0); // A FixedPage nested in a FixedPage is invalid. // XmlException gets handled inside this class (see GetChunk). if (_filterState == FilterState.FindNextFlowUnit) { throw new XmlException(SR.Get(SRID.XamlFilterNestedFixedPage)); } // Create a DOM for the current FixedPage. string fixedPageMarkup = _xamlReader.ReadOuterXml(); XmlDocument fixedPageTree = new XmlDocument(); fixedPageTree.LoadXml(fixedPageMarkup); // Preserve the current language ID if (_xamlReader.XmlLang.Length > 0) { fixedPageTree.DocumentElement.SetAttribute(_xmlLangAttribute, _xamlReader.XmlLang); } // Initialize a content extractor with this DOM tree. _fixedPageContentExtractor = new FixedPageContentExtractor(fixedPageTree.DocumentElement); // Save the DOM (to search for flow elements in it once the extractor is done) // and switch to extractor mode. _fixedPageDomTree = fixedPageTree; _filterState = FilterState.UseContentExtractor; // Have NextContentUnit look for the appropriate unit in the new mode. return null; } ///<summary> /// Create an XmlTextReader on _xamlStream with the appropriate settings. ///</summary> private void CreateXmlReader() { if (_xamlReader != null) { _xamlReader.Close(); } _xamlReader = new XmlTextReader(_xamlStream); // Do not return pretty-pretting spacing between tags as data. ((XmlTextReader)_xamlReader).WhitespaceHandling = WhitespaceHandling.Significant; // Initialize reader state. _attributesToIgnore = AttributesToIgnore.None; // not in the middle of processing a start-tag } private void EnsureXmlReaderIsClosed() { if (_xamlReader != null) { _xamlReader.Close(); } } ///<summary> /// Return the LCID in scope for the current node or, if there is none, /// the system's default LCID. /// Note: XmlGlyphRunInfo.LanguageID is an internal property that also has /// similar logic and will default to CultureInfo.InvariantCulture.LCID /// CultureInfo.InvariantCulture will never be null ///</summary> private uint GetCurrentLcid() { string languageString = GetLanguageString(); if (languageString.Length == 0) return (uint)CultureInfo.InvariantCulture.LCID; else if (_lcidDictionary.ContainsKey(languageString)) return _lcidDictionary[languageString]; else { CultureInfo cultureInfo = new CultureInfo(languageString); _lcidDictionary.Add(languageString, (uint)cultureInfo.LCID); return (uint)cultureInfo.LCID; } } private string GetLanguageString() { string languageString = _xamlReader.XmlLang; if (languageString.Length == 0) { // Check whether there is a parent XAML reader. if (_topLevelReader != null) { languageString = _topLevelReader.XmlLang; } } return languageString; } private void SkipCurrentElement() { _xamlReader.Skip(); } private bool IsPrefixedPropertyName(string name, out string propertyName) { int suffixStart = name.IndexOf('.'); if (suffixStart == -1) { propertyName = null; return false; } propertyName = name.Substring(suffixStart + 1); return true; } /// <remarks> /// 0 is an illegal value, so this function never returns 0. /// After the counter reaches UInt32.MaxValue we assert, since such a /// high number for chunks is most likely an indicator of some other /// problem in the system/code. /// </remarks> private uint AllocateChunkID() { Invariant.Assert(_currentChunkID <= UInt32.MaxValue); ++_currentChunkID; return _currentChunkID; } /// <summary> /// Find an attribute named propertyName or X.propertyName. /// </summary> private string GetPropertyAsAttribute(string propertyName) { string value = _xamlReader.GetAttribute(propertyName); if (value != null) { return value; } bool attributeFound = _xamlReader.MoveToFirstAttribute(); while (attributeFound) { string attributePropertyName; if ( IsPrefixedPropertyName(_xamlReader.LocalName, out attributePropertyName) && attributePropertyName.Equals(propertyName, StringComparison.Ordinal)) { value = _xamlReader.Value; break; } // Advance reader. attributeFound = _xamlReader.MoveToNextAttribute(); } // Reposition reader on owner element. _xamlReader.MoveToElement(); return value; } #region Context Stack Accessors private ContentDescriptor TopOfStack() { return (ContentDescriptor) _contextStack.Peek(); } private void Push(ContentDescriptor contentDescriptor) { if (!contentDescriptor.IsInline) { _expectingBlockStart = true; } _contextStack.Push(contentDescriptor); } private ContentDescriptor Pop() { ContentDescriptor topOfStack = (ContentDescriptor) _contextStack.Pop(); // If we reach an end of block, we expect the next item to // start with a block separator. if (!topOfStack.IsInline) { _expectingBlockStart = true; } return topOfStack; } private void ClearStack() { _contextStack.Clear(); } #endregion Context Stack Accessors #endregion Private Methods #region Private Constants ///<summary>XML namespace URI for in-document code.</summary> private const string _inDocumentCodeURI = "http://schemas.microsoft.com/winfx/2006/xaml"; // Tag and attribute names. private const string _pageContentName = "PageContent"; private const string _glyphRunName = "Glyphs"; private const string _pageContentSourceAttribute = "Source"; private const string _fixedPageName = "FixedPage"; private const string _xmlLangAttribute = "xml:lang"; private const string _paragraphSeparator = "\u2029"; private const string _unicodeStringAttribute = "UnicodeString"; /// <summary> /// The default content descriptor has content in child nodes, no title, and block-type content. /// </summary> private readonly ContentDescriptor _defaultContentDescriptor = new ContentDescriptor(true /*hasIndexableContent*/, false /*isInline*/, null, null); private readonly ContentDescriptor _nonIndexableElementDescriptor = new ContentDescriptor(false); // Static fields. private static readonly ManagedFullPropSpec _propSpec = new ManagedFullPropSpec(IndexingFilterMarshaler.PSGUID_STORAGE, (uint)MS.Internal.Interop.PID_STG.CONTENTS); #endregion Private Constants #region Private Fields // Variables initialized in constructor and InitializeDeclaredFields. private Stack _contextStack; private FilterState _filterState; private string _currentContent; private uint _currentChunkID; private int _countOfCharactersReturned; private IndexingContentUnit _indexingContentUnit; private bool _expectingBlockStart; private XmlReader _topLevelReader; private FixedPageContentExtractor _fixedPageContentExtractor; private XmlDocument _fixedPageDomTree; // Variables initialized in constructor and (potentially, if implemented some day) in IPersistFile.Load. private Stream _xamlStream; // Variables initialized in Init. private bool _filterContents; //defaults to false private bool _returnCanonicalParagraphBreaks; //defaults to false // Reader state variables (initialized in CreateXmlReader). private XmlReader _xamlReader; private AttributesToIgnore _attributesToIgnore; ///<summary>Map from fully qualified element name to content location information.</summary> private Hashtable _xamlElementContentDescriptorDictionary; //Dictionary of Language strings and the corresponding LCID. private Dictionary<string, uint> _lcidDictionary; #endregion Private Fields } // class XamlFilter #endregion XamlFilter } // namespace MS.Internal.IO.Packaging
#region Using declarations using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Xml.Serialization; using NinjaTrader.Cbi; using NinjaTrader.Gui; using NinjaTrader.Gui.Chart; using NinjaTrader.Gui.SuperDom; using NinjaTrader.Gui.Tools; using NinjaTrader.Data; using NinjaTrader.NinjaScript; using NinjaTrader.Core.FloatingPoint; using NinjaTrader.NinjaScript.DrawingTools; using System.Web.Script.Serialization; using System.Net; #endregion //This namespace holds Indicators in this folder and is required. Do not change it. namespace NinjaTrader.NinjaScript.Indicators { public class SignificantMove2 : Indicator { //private const string baseUrl = "http://127.0.0.1:8888/query?ticker={0}&date={1}"; private LinReg RL30; private MAX periodMax; private MIN periodMin; private double signalThreshold = -1; private int lastSignal = 0, lastNotSignal = 0; protected override void OnStateChange() { if (State == State.SetDefaults) { Description = @""; Name = "SignificantMove2"; Calculate = Calculate.OnBarClose; IsOverlay = false; DisplayInDataBox = true; DrawOnPricePanel = true; DrawHorizontalGridLines = true; DrawVerticalGridLines = true; PaintPriceMarkers = true; ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right; //Disable this property if your indicator requires custom values that cumulate with each new market data event. //See Help Guide for additional information. IsSuspendedWhileInactive = true; Period = 20; Threshold = 0.5; SignalAreaColor = Brushes.Orange; SignalAreaOpacity = 30; AddPlot(Brushes.Transparent, "MarketAnalyzerPlot"); } else if (State == State.Configure) { RL30 = LinReg(Period); periodMax = MAX(RL30, Period); periodMin = MIN(RL30, Period); } } protected override void OnBarUpdate() { if (CurrentBar < Period) { return; } // update signalThreshold if needed if (signalThreshold < 0 || Time[0].Date != Time[1].Date) { //FrogModel fm = getFrogModel(); signalThreshold = Threshold; } if (periodMax[0] - periodMin[0] > signalThreshold) { // Log(String.Format("isSignal: {0}, diff: {1}, threshold: {2}", periodMax[0] - periodMin[0] > signalThreshold, periodMax[0] - periodMin[0], signalThreshold), LogLevel.Information); MarketAnalyzerPlot[0] = 1; if (lastSignal > lastNotSignal) // indicates the previous bar is a signal bar too { RemoveDrawObject(getTagString(CurrentBar)); } else { lastSignal = CurrentBar; } Draw.Rectangle(this, getTagString(lastSignal), true, CurrentBar - lastSignal, periodMin[0], -1, periodMax[0], Brushes.Transparent, SignalAreaColor, (int)SignalAreaOpacity); } else { // Log(String.Format("isSignal: {0}, diff: {1}, threshold: {2}", periodMax[0] - periodMin[0] > signalThreshold, periodMax[0] - periodMin[0], signalThreshold), LogLevel.Information); MarketAnalyzerPlot[0] = 0; lastNotSignal = CurrentBar; } } private string getTagString(int bar) { return "SignificantMove2" + bar; } // private FrogModel getFrogModel() // { // string url = String.Format(baseUrl, base.Instrument.FullName, Time[0].Date.ToString("yyyy-MM-dd")); // using (var client = new WebClient()) // { // var json = client.DownloadString(url); // var serializer = new JavaScriptSerializer(); // var model = serializer.Deserialize<FrogModel>(json); // model.range = model.rangestat; // return model; // } // } // public class FrogModel // { // public double rangestat {get;set;} // public double fb {get;set;} // public double hfb {get;set;} // public double range {get;set;} // } #region Properties [NinjaScriptProperty] [Range(1, int.MaxValue)] [Display(Name="Period", Order=1, GroupName="Parameters")] public int Period { get; set; } [NinjaScriptProperty] [Range(0, double.MaxValue)] [Display(Name="Threshold", Order=2, GroupName="Parameters")] public double Threshold { get; set; } [NinjaScriptProperty] [XmlIgnore] [Display(Name="SignalAreaColor", Order=3, GroupName="Parameters")] public Brush SignalAreaColor { get; set; } [Browsable(false)] public string SignalAreaColorSerializable { get { return Serialize.BrushToString(SignalAreaColor); } set { SignalAreaColor = Serialize.StringToBrush(value); } } [NinjaScriptProperty] [Range(0, double.MaxValue)] [Display(Name="SignalAreaOpacity", Order=4, GroupName="Parameters")] public double SignalAreaOpacity { get; set; } [Browsable(false)] [XmlIgnore] public Series<double> MarketAnalyzerPlot { get { return Values[0]; } } #endregion } } #region NinjaScript generated code. Neither change nor remove. namespace NinjaTrader.NinjaScript.Indicators { public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase { private SignificantMove2[] cacheSignificantMove2; public SignificantMove2 SignificantMove2(int period, double threshold, Brush signalAreaColor, double signalAreaOpacity) { return SignificantMove2(Input, period, threshold, signalAreaColor, signalAreaOpacity); } public SignificantMove2 SignificantMove2(ISeries<double> input, int period, double threshold, Brush signalAreaColor, double signalAreaOpacity) { if (cacheSignificantMove2 != null) for (int idx = 0; idx < cacheSignificantMove2.Length; idx++) if (cacheSignificantMove2[idx] != null && cacheSignificantMove2[idx].Period == period && cacheSignificantMove2[idx].Threshold == threshold && cacheSignificantMove2[idx].SignalAreaColor == signalAreaColor && cacheSignificantMove2[idx].SignalAreaOpacity == signalAreaOpacity && cacheSignificantMove2[idx].EqualsInput(input)) return cacheSignificantMove2[idx]; return CacheIndicator<SignificantMove2>(new SignificantMove2(){ Period = period, Threshold = threshold, SignalAreaColor = signalAreaColor, SignalAreaOpacity = signalAreaOpacity }, input, ref cacheSignificantMove2); } } } namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns { public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase { public Indicators.SignificantMove2 SignificantMove2(int period, double threshold, Brush signalAreaColor, double signalAreaOpacity) { return indicator.SignificantMove2(Input, period, threshold, signalAreaColor, signalAreaOpacity); } public Indicators.SignificantMove2 SignificantMove2(ISeries<double> input , int period, double threshold, Brush signalAreaColor, double signalAreaOpacity) { return indicator.SignificantMove2(input, period, threshold, signalAreaColor, signalAreaOpacity); } } } namespace NinjaTrader.NinjaScript.Strategies { public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase { public Indicators.SignificantMove2 SignificantMove2(int period, double threshold, Brush signalAreaColor, double signalAreaOpacity) { return indicator.SignificantMove2(Input, period, threshold, signalAreaColor, signalAreaOpacity); } public Indicators.SignificantMove2 SignificantMove2(ISeries<double> input , int period, double threshold, Brush signalAreaColor, double signalAreaOpacity) { return indicator.SignificantMove2(input, period, threshold, signalAreaColor, signalAreaOpacity); } } } #endregion
//! \file ImageMGD.cs //! \date Thu Nov 24 14:37:18 2016 //! \brief NSystem image format. // // Copyright (C) 2016 by morkt // // 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.ComponentModel.Composition; using System.IO; using System.Windows.Media; using System.Windows.Media.Imaging; namespace GameRes.Formats.NSystem { internal class MgdMetaData : ImageMetaData { public int DataOffset; public int UnpackedSize; public int Mode; } [Export(typeof(ImageFormat))] public class MgdFormat : ImageFormat { public override string Tag { get { return "MGD/NSystem"; } } public override string Description { get { return "NSystem image format"; } } public override uint Signature { get { return 0x2044474D; } } // 'MGD ' public override ImageMetaData ReadMetaData (IBinaryStream file) { var header = file.ReadHeader (0x1C); int header_size = header.ToUInt16 (4); uint width = header.ToUInt16 (0xC); uint height = header.ToUInt16 (0xE); int unpacked_size = header.ToInt32 (0x10); int mode = header.ToInt32 (0x18); if (mode < 0 || mode > 2) return null; return new MgdMetaData { Width = width, Height = height, BPP = 32, DataOffset = header_size, UnpackedSize = unpacked_size, Mode = mode, }; } public override ImageData Read (IBinaryStream file, ImageMetaData info) { var meta = (MgdMetaData)info; file.Position = meta.DataOffset; int data_size = file.ReadInt32(); switch (meta.Mode) { case 0: { var pixels = file.ReadBytes (data_size); var format = PixelFormats.Bgr32; for (int i = 3; i < data_size; i += 4) { if (pixels[i] != 0) { format = PixelFormats.Bgra32; break; } } return ImageData.Create (info, format, null, pixels); } case 1: { var decoder = new MgdDecoder (file, meta, data_size); decoder.Unpack(); return ImageData.Create (info, decoder.Format, null, decoder.Data); } case 2: using (var png = new StreamRegion (file.AsStream, file.Position, data_size, true)) { var decoder = new PngBitmapDecoder (png, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); var frame = decoder.Frames[0]; frame.Freeze(); return new ImageData (frame, info); } default: throw new InvalidFormatException(); } } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("MgdFormat.Write not implemented"); } } internal class MgdDecoder { IBinaryStream m_input; MgdMetaData m_info; byte[] m_output; public byte[] Data { get { return m_output; } } public PixelFormat Format { get; private set; } public MgdDecoder (IBinaryStream input, MgdMetaData info, int packed_size) { m_input = input; m_info = info; m_output = new byte[m_info.UnpackedSize]; Format = PixelFormats.Bgra32; } public void Unpack () { int alpha_size = m_input.ReadInt32(); if (!UnpackAlpha (alpha_size)) Format = PixelFormats.Bgr32; int rgb_size = m_input.ReadInt32(); UnpackColor (rgb_size); } bool UnpackAlpha (int length) { bool has_alpha = false; int dst = 3; while (length > 0) { int count = m_input.ReadInt16(); length -= 2; if (count < 0) { count = (count & 0x7FFF) + 1; byte a = m_input.ReadUInt8(); has_alpha = has_alpha || a != 0; length--; for (int i = 0; i < count; ++i) { m_output[dst] = a; dst += 4; } } else { for (int i = 0; i < count; ++i) { byte a = m_input.ReadUInt8(); has_alpha = has_alpha || a != 0; m_output[dst] = a; dst += 4; } length -= count; } } return has_alpha; } void UnpackColor (int length) { int dst = 0; while (length > 0) { int count = m_input.ReadUInt8(); length--; switch (count & 0xC0) { case 0x80: count &= 0x3F; int b = m_output[dst-4]; int g = m_output[dst-3]; int r = m_output[dst-2]; for (int i = 0; i < count; ++i) { ushort delta = m_input.ReadUInt16(); length -= 2; if (0 != (delta & 0x8000)) { r += (delta >> 10) & 0x1F; g += (delta >> 5) & 0x1F; b += delta & 0x1F; } else { if (0 != (delta & 0x4000)) r -= (delta >> 10) & 0xF; else r += (delta >> 10) & 0xF; if (0 != (delta & 0x0200)) g -= (delta >> 5) & 0xF; else g += (delta >> 5) & 0xF; if (0 != (delta & 0x0010)) b -= delta & 0xF; else b += delta & 0xF; } m_output[dst ] = (byte)b; m_output[dst+1] = (byte)g; m_output[dst+2] = (byte)r; dst += 4; } break; case 0x40: count &= 0x3F; m_input.Read (m_output, dst, 3); length -= 3; int src = dst; dst += 4; for (int i = 0; i < count; ++i) { m_output[dst ] = m_output[src ]; m_output[dst+1] = m_output[src+1]; m_output[dst+2] = m_output[src+2]; dst += 4; } break; case 0: for (int i = 0; i < count; ++i) { m_input.Read (m_output, dst, 3); length -= 3; dst += 4; } break; default: throw new InvalidFormatException(); } } } } }
/* ==================================================================== 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 TestCases.HSSF.UserModel { using System; using System.Reflection; using NUnit.Framework; using NPOI.HSSF.Model; using NPOI.HSSF.Record; using NPOI.HSSF.UserModel; using NPOI.SS.Formula; using NPOI.SS.Formula.PTG; using NPOI.SS.UserModel; using NPOI.SS.Util; using TestCases.SS.UserModel; /** * Tests various functionality having to do with {@link NPOI.SS.usermodel.Name}. * * @author Andrew C. Oliver (acoliver at apache dot org) * @author ROMANL * @author Danny Mui (danny at muibros.com) * @author Amol S. Deshmukh &lt; amol at ap ache dot org &gt; */ [TestFixture] public class TestHSSFName : BaseTestNamedRange { public TestHSSFName() : base(HSSFITestDataProvider.Instance) { } /** * For manipulating the internals of {@link HSSFName} during Testing.<br/> * Some Tests need a {@link NameRecord} with unusual state, not normally producible by POI. * This method achieves the aims at low cost without augmenting the POI usermodel api. * @return a reference to the wrapped {@link NameRecord} */ public static NameRecord GetNameRecord(IName definedName) { FieldInfo f; f = typeof(HSSFName).GetField("_definedNameRec",BindingFlags.Instance|BindingFlags.NonPublic); //f.SetAccessible(true); return (NameRecord)f.GetValue(definedName); } [Test] public void TestRepeatingRowsAndColumsNames() { // First Test that Setting RR&C for same sheet more than once only Creates a // single Print_Titles built-in record HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = (HSSFSheet)wb.CreateSheet("FirstSheet"); // set repeating rows and columns twice for the first sheet for (int i = 0; i < 2; i++) { wb.SetRepeatingRowsAndColumns(0, 0, 0, 0, 3 - 1); sheet.CreateFreezePane(0, 3); } Assert.AreEqual(1, wb.NumberOfNames); IName nr1 = wb.GetNameAt(0); Assert.AreEqual("Print_Titles", nr1.NameName); if (false) { #if !HIDE_UNREACHABLE_CODE // TODO - full column references not rendering properly, absolute markers not present either Assert.AreEqual("FirstSheet!$A:$A,FirstSheet!$1:$3", nr1.RefersToFormula); #endif } else { Assert.AreEqual("FirstSheet!A:A,FirstSheet!$A$1:$IV$3", nr1.RefersToFormula); } // Save and re-open HSSFWorkbook nwb = HSSFTestDataSamples.WriteOutAndReadBack(wb); Assert.AreEqual(1, nwb.NumberOfNames); nr1 = nwb.GetNameAt(0); Assert.AreEqual("Print_Titles", nr1.NameName); Assert.AreEqual("FirstSheet!A:A,FirstSheet!$A$1:$IV$3", nr1.RefersToFormula); // check that Setting RR&C on a second sheet causes a new Print_Titles built-in // name to be Created sheet = (HSSFSheet)nwb.CreateSheet("SecondSheet"); nwb.SetRepeatingRowsAndColumns(1, 1, 2, 0, 0); Assert.AreEqual(2, nwb.NumberOfNames); IName nr2 = nwb.GetNameAt(1); Assert.AreEqual("Print_Titles", nr2.NameName); Assert.AreEqual("SecondSheet!B:C,SecondSheet!$A$1:$IV$1", nr2.RefersToFormula); //if (false) { // // In case you fancy Checking in excel, to ensure it // // won't complain about the file now // File tempFile = File.CreateTempFile("POI-45126-", ".xls"); // FileOutputStream fout = new FileOutputStream(tempFile); // nwb.Write(fout); // fout.close(); // Console.WriteLine("check out " + tempFile.GetAbsolutePath()); //} } [Test] public void TestNamedRange() { HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("Simple.xls"); //Creating new Named Range IName newNamedRange = wb.CreateName(); //Getting Sheet Name for the reference String sheetName = wb.GetSheetName(0); //Setting its name newNamedRange.NameName = "RangeTest"; //Setting its reference newNamedRange.RefersToFormula = sheetName + "!$D$4:$E$8"; //Getting NAmed Range IName namedRange1 = wb.GetNameAt(0); //Getting it sheet name sheetName = namedRange1.SheetName; // sanity check SanityChecker c = new SanityChecker(); c.CheckHSSFWorkbook(wb); wb = HSSFTestDataSamples.WriteOutAndReadBack(wb); IName nm = wb.GetNameAt(wb.GetNameIndex("RangeTest")); Assert.IsTrue("RangeTest".Equals(nm.NameName), "Name is " + nm.NameName); Assert.AreEqual(wb.GetSheetName(0) + "!$D$4:$E$8", nm.RefersToFormula); } /** * Reads an excel file already Containing a named range. * <p> * Addresses Bug <a href="http://issues.apache.org/bugzilla/Show_bug.cgi?id=9632" tarGet="_bug">#9632</a> */ [Test] public void TestNamedRead() { HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("namedinput.xls"); //Get index of the named range with the name = "NamedRangeName" , which was defined in input.xls as A1:D10 int NamedRangeIndex = wb.GetNameIndex("NamedRangeName"); //Getting NAmed Range IName namedRange1 = wb.GetNameAt(NamedRangeIndex); String sheetName = wb.GetSheetName(0); //Getting its reference String reference = namedRange1.RefersToFormula; Assert.AreEqual(sheetName + "!$A$1:$D$10", reference); IName namedRange2 = wb.GetNameAt(1); Assert.AreEqual(sheetName + "!$D$17:$G$27", namedRange2.RefersToFormula); Assert.AreEqual("SecondNamedRange", namedRange2.NameName); } /** * Reads an excel file already Containing a named range and updates it * <p> * Addresses Bug <a href="http://issues.apache.org/bugzilla/Show_bug.cgi?id=16411" tarGet="_bug">#16411</a> */ [Test] public void TestNamedReadModify() { HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("namedinput.xls"); IName name = wb.GetNameAt(0); String sheetName = wb.GetSheetName(0); Assert.AreEqual(sheetName + "!$A$1:$D$10", name.RefersToFormula); name = wb.GetNameAt(1); String newReference = sheetName + "!$A$1:$C$36"; name.RefersToFormula = newReference; Assert.AreEqual(newReference, name.RefersToFormula); } /** * Test to see if the print area can be retrieved from an excel Created file */ [Test] public void TestPrintAreaFileRead() { HSSFWorkbook workbook = HSSFTestDataSamples.OpenSampleWorkbook("SimpleWithPrintArea.xls"); String sheetName = workbook.GetSheetName(0); String reference = sheetName + "!$A$1:$C$5"; Assert.AreEqual(reference, workbook.GetPrintArea(0)); } [Test] public void TestDeletedReference() { HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("24207.xls"); Assert.AreEqual(2, wb.NumberOfNames); IName name1 = wb.GetNameAt(0); Assert.AreEqual("a", name1.NameName); Assert.AreEqual("Sheet1!$A$1", name1.RefersToFormula); new AreaReference(name1.RefersToFormula); Assert.IsTrue(true, "Successfully constructed first reference"); IName name2 = wb.GetNameAt(1); Assert.AreEqual("b", name2.NameName); Assert.AreEqual("Sheet1!#REF!", name2.RefersToFormula); Assert.IsTrue(name2.IsDeleted); try { new AreaReference(name2.RefersToFormula); Assert.Fail("attempt to supply an invalid reference to AreaReference constructor results in exception"); } catch (ArgumentException) { // TODO - use a different exception for this condition // expected during successful Test } } /** * When Setting A1 type of references with HSSFName.SetRefersToFormula * must set the type of operands to Ptg.CLASS_REF, * otherwise Created named don't appear in the drop-down to the left of formula bar in Excel */ [Test] public void TestTypeOfRootPtg() { HSSFWorkbook wb = new HSSFWorkbook(); wb.CreateSheet("CSCO"); Ptg[] ptgs = HSSFFormulaParser.Parse("CSCO!$E$71", wb, FormulaType.NamedRange, 0); for (int i = 0; i < ptgs.Length; i++) { Assert.AreEqual('R', ptgs[i].RVAType); } } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfileResponseAdaptBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileResponseAdaptResponseAdaptProfileStatistics))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileEnabledState))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileString))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileULong))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileAdaptServiceDownAction))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStatisticsByVirtual))] public partial class LocalLBProfileResponseAdapt : iControlInterface { public LocalLBProfileResponseAdapt() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void create( string [] profile_names ) { this.Invoke("create", new object [] { profile_names}); } public System.IAsyncResult Begincreate(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { profile_names}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_profiles //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void delete_all_profiles( ) { this.Invoke("delete_all_profiles", new object [0]); } public System.IAsyncResult Begindelete_all_profiles(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_profiles", new object[0], callback, asyncState); } public void Enddelete_all_profiles(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void delete_profile( string [] profile_names ) { this.Invoke("delete_profile", new object [] { profile_names}); } public System.IAsyncResult Begindelete_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_profile", new object[] { profile_names}, callback, asyncState); } public void Enddelete_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_all_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileResponseAdaptResponseAdaptProfileStatistics get_all_statistics( ) { object [] results = this.Invoke("get_all_statistics", new object [0]); return ((LocalLBProfileResponseAdaptResponseAdaptProfileStatistics)(results[0])); } public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState); } public LocalLBProfileResponseAdaptResponseAdaptProfileStatistics Endget_all_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileResponseAdaptResponseAdaptProfileStatistics)(results[0])); } //----------------------------------------------------------------------- // get_allow_http_10_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_allow_http_10_state( string [] profile_names ) { object [] results = this.Invoke("get_allow_http_10_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_allow_http_10_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_allow_http_10_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_allow_http_10_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_default_profile( string [] profile_names ) { object [] results = this.Invoke("get_default_profile", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_default_profile", new object[] { profile_names}, callback, asyncState); } public string [] Endget_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] profile_names ) { object [] results = this.Invoke("get_description", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { profile_names}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_enabled_state( string [] profile_names ) { object [] results = this.Invoke("get_enabled_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_enabled_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_enabled_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_internal_virtual_server //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileString [] get_internal_virtual_server( string [] profile_names ) { object [] results = this.Invoke("get_internal_virtual_server", new object [] { profile_names}); return ((LocalLBProfileString [])(results[0])); } public System.IAsyncResult Beginget_internal_virtual_server(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_internal_virtual_server", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileString [] Endget_internal_virtual_server(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileString [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_preview_size //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_preview_size( string [] profile_names ) { object [] results = this.Invoke("get_preview_size", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_preview_size(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_preview_size", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_preview_size(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_service_down_action //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileAdaptServiceDownAction [] get_service_down_action( string [] profile_names ) { object [] results = this.Invoke("get_service_down_action", new object [] { profile_names}); return ((LocalLBProfileAdaptServiceDownAction [])(results[0])); } public System.IAsyncResult Beginget_service_down_action(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_service_down_action", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileAdaptServiceDownAction [] Endget_service_down_action(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileAdaptServiceDownAction [])(results[0])); } //----------------------------------------------------------------------- // get_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileResponseAdaptResponseAdaptProfileStatistics get_statistics( string [] profile_names ) { object [] results = this.Invoke("get_statistics", new object [] { profile_names}); return ((LocalLBProfileResponseAdaptResponseAdaptProfileStatistics)(results[0])); } public System.IAsyncResult Beginget_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileResponseAdaptResponseAdaptProfileStatistics Endget_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileResponseAdaptResponseAdaptProfileStatistics)(results[0])); } //----------------------------------------------------------------------- // get_statistics_by_virtual //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileStatisticsByVirtual get_statistics_by_virtual( string [] profile_names, string [] [] virtual_names ) { object [] results = this.Invoke("get_statistics_by_virtual", new object [] { profile_names, virtual_names}); return ((LocalLBProfileStatisticsByVirtual)(results[0])); } public System.IAsyncResult Beginget_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics_by_virtual", new object[] { profile_names, virtual_names}, callback, asyncState); } public LocalLBProfileStatisticsByVirtual Endget_statistics_by_virtual(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileStatisticsByVirtual)(results[0])); } //----------------------------------------------------------------------- // get_timeout //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_timeout( string [] profile_names ) { object [] results = this.Invoke("get_timeout", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_timeout(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_timeout", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_timeout(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_timeout_v2 //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_timeout_v2( string [] profile_names ) { object [] results = this.Invoke("get_timeout_v2", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_timeout_v2(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_timeout_v2", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_timeout_v2(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // is_base_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_base_profile( string [] profile_names ) { object [] results = this.Invoke("is_base_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_base_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_base_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // is_system_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_system_profile( string [] profile_names ) { object [] results = this.Invoke("is_system_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_system_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_system_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // reset_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void reset_statistics( string [] profile_names ) { this.Invoke("reset_statistics", new object [] { profile_names}); } public System.IAsyncResult Beginreset_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics", new object[] { profile_names}, callback, asyncState); } public void Endreset_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_statistics_by_virtual //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void reset_statistics_by_virtual( string [] profile_names, string [] [] virtual_names ) { this.Invoke("reset_statistics_by_virtual", new object [] { profile_names, virtual_names}); } public System.IAsyncResult Beginreset_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics_by_virtual", new object[] { profile_names, virtual_names}, callback, asyncState); } public void Endreset_statistics_by_virtual(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_allow_http_10_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void set_allow_http_10_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_allow_http_10_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_allow_http_10_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_allow_http_10_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_allow_http_10_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void set_default_profile( string [] profile_names, string [] defaults ) { this.Invoke("set_default_profile", new object [] { profile_names, defaults}); } public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_default_profile", new object[] { profile_names, defaults}, callback, asyncState); } public void Endset_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void set_description( string [] profile_names, string [] descriptions ) { this.Invoke("set_description", new object [] { profile_names, descriptions}); } public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { profile_names, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void set_enabled_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_enabled_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_enabled_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_enabled_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_internal_virtual_server //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void set_internal_virtual_server( string [] profile_names, LocalLBProfileString [] virtuals ) { this.Invoke("set_internal_virtual_server", new object [] { profile_names, virtuals}); } public System.IAsyncResult Beginset_internal_virtual_server(string [] profile_names,LocalLBProfileString [] virtuals, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_internal_virtual_server", new object[] { profile_names, virtuals}, callback, asyncState); } public void Endset_internal_virtual_server(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_preview_size //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void set_preview_size( string [] profile_names, LocalLBProfileULong [] values ) { this.Invoke("set_preview_size", new object [] { profile_names, values}); } public System.IAsyncResult Beginset_preview_size(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_preview_size", new object[] { profile_names, values}, callback, asyncState); } public void Endset_preview_size(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_service_down_action //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void set_service_down_action( string [] profile_names, LocalLBProfileAdaptServiceDownAction [] values ) { this.Invoke("set_service_down_action", new object [] { profile_names, values}); } public System.IAsyncResult Beginset_service_down_action(string [] profile_names,LocalLBProfileAdaptServiceDownAction [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_service_down_action", new object[] { profile_names, values}, callback, asyncState); } public void Endset_service_down_action(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_timeout //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void set_timeout( string [] profile_names, LocalLBProfileULong [] values ) { this.Invoke("set_timeout", new object [] { profile_names, values}); } public System.IAsyncResult Beginset_timeout(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_timeout", new object[] { profile_names, values}, callback, asyncState); } public void Endset_timeout(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_timeout_v2 //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileResponseAdapt", RequestNamespace="urn:iControl:LocalLB/ProfileResponseAdapt", ResponseNamespace="urn:iControl:LocalLB/ProfileResponseAdapt")] public void set_timeout_v2( string [] profile_names, LocalLBProfileULong [] values ) { this.Invoke("set_timeout_v2", new object [] { profile_names, values}); } public System.IAsyncResult Beginset_timeout_v2(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_timeout_v2", new object[] { profile_names, values}, callback, asyncState); } public void Endset_timeout_v2(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileResponseAdapt.ResponseAdaptProfileStatisticEntry", Namespace = "urn:iControl")] public partial class LocalLBProfileResponseAdaptResponseAdaptProfileStatisticEntry { private string profile_nameField; public string profile_name { get { return this.profile_nameField; } set { this.profile_nameField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileResponseAdapt.ResponseAdaptProfileStatistics", Namespace = "urn:iControl")] public partial class LocalLBProfileResponseAdaptResponseAdaptProfileStatistics { private LocalLBProfileResponseAdaptResponseAdaptProfileStatisticEntry [] statisticsField; public LocalLBProfileResponseAdaptResponseAdaptProfileStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; }
// The following code was generated by JFlex 1.5.1 using YAF.Lucene.Net.Analysis.TokenAttributes; using System; using System.IO; namespace YAF.Lucene.Net.Analysis.Standard { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// This class implements Word Break rules from the Unicode Text Segmentation /// algorithm, as specified in /// <a href="http://unicode.org/reports/tr29/">Unicode Standard Annex #29</a>. /// <para/> /// Tokens produced are of the following types: /// <list type="bullet"> /// <item><description>&lt;ALPHANUM&gt;: A sequence of alphabetic and numeric characters</description></item> /// <item><description>&lt;NUM&gt;: A number</description></item> /// <item><description>&lt;SOUTHEAST_ASIAN&gt;: A sequence of characters from South and Southeast /// Asian languages, including Thai, Lao, Myanmar, and Khmer</description></item> /// <item><description>&lt;IDEOGRAPHIC&gt;: A single CJKV ideographic character</description></item> /// <item><description>&lt;HIRAGANA&gt;: A single hiragana character</description></item> /// <item><description>&lt;KATAKANA&gt;: A sequence of katakana characters</description></item> /// <item><description>&lt;HANGUL&gt;: A sequence of Hangul characters</description></item> /// </list> /// </summary> public sealed class StandardTokenizerImpl : IStandardTokenizerInterface { /// <summary> /// This character denotes the end of file </summary> public static readonly int YYEOF = -1; /// <summary> /// initial size of the lookahead buffer </summary> private static readonly int ZZ_BUFFERSIZE = 4096; /// <summary> /// lexical states </summary> public const int YYINITIAL = 0; /// <summary> /// ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l /// ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l /// at the beginning of a line /// l is of the form l = 2*k, k a non negative integer /// </summary> private static readonly int[] ZZ_LEXSTATE = { 0, 0 }; /// <summary> /// Translates characters to character classes /// </summary> private const string ZZ_CMAP_PACKED = "\x0022\x0000\x0001\x008B\x0004\x0000\x0001\x008A\x0004\x0000\x0001\x0083\x0001\x0000\x0001\x0084\x0001\x0000\x000A\x0080" + "\x0001\x0082\x0001\x0083\x0005\x0000\x001A\x007E\x0004\x0000\x0001\x0085\x0001\x0000\x001A\x007E\x002F\x0000\x0001\x007E" + "\x0002\x0000\x0001\x007F\x0007\x0000\x0001\x007E\x0001\x0000\x0001\x0082\x0002\x0000\x0001\x007E\x0005\x0000\x0017\x007E" + "\x0001\x0000\x001F\x007E\x0001\x0000\u01ca\x007E\x0004\x0000\x000C\x007E\x0005\x0000\x0001\x0082\x0008\x0000\x0005\x007E" + "\x0007\x0000\x0001\x007E\x0001\x0000\x0001\x007E\x0011\x0000\x0070\x007F\x0005\x007E\x0001\x0000\x0002\x007E\x0002\x0000" + "\x0004\x007E\x0001\x0083\x0007\x0000\x0001\x007E\x0001\x0082\x0003\x007E\x0001\x0000\x0001\x007E\x0001\x0000\x0014\x007E" + "\x0001\x0000\x0053\x007E\x0001\x0000\x008B\x007E\x0001\x0000\x0007\x007F\x009E\x007E\x0009\x0000\x0026\x007E\x0002\x0000" + "\x0001\x007E\x0007\x0000\x0027\x007E\x0001\x0000\x0001\x0083\x0007\x0000\x002D\x007F\x0001\x0000\x0001\x007F\x0001\x0000" + "\x0002\x007F\x0001\x0000\x0002\x007F\x0001\x0000\x0001\x007F\x0008\x0000\x001B\x008C\x0005\x0000\x0003\x008C\x0001\x007E" + "\x0001\x0082\x000B\x0000\x0005\x007F\x0007\x0000\x0002\x0083\x0002\x0000\x000B\x007F\x0001\x0000\x0001\x007F\x0003\x0000" + "\x002B\x007E\x0015\x007F\x000A\x0080\x0001\x0000\x0001\x0080\x0001\x0083\x0001\x0000\x0002\x007E\x0001\x007F\x0063\x007E" + "\x0001\x0000\x0001\x007E\x0007\x007F\x0001\x007F\x0001\x0000\x0006\x007F\x0002\x007E\x0002\x007F\x0001\x0000\x0004\x007F" + "\x0002\x007E\x000A\x0080\x0003\x007E\x0002\x0000\x0001\x007E\x000F\x0000\x0001\x007F\x0001\x007E\x0001\x007F\x001E\x007E" + "\x001B\x007F\x0002\x0000\x0059\x007E\x000B\x007F\x0001\x007E\x000E\x0000\x000A\x0080\x0021\x007E\x0009\x007F\x0002\x007E" + "\x0002\x0000\x0001\x0083\x0001\x0000\x0001\x007E\x0005\x0000\x0016\x007E\x0004\x007F\x0001\x007E\x0009\x007F\x0001\x007E" + "\x0003\x007F\x0001\x007E\x0005\x007F\x0012\x0000\x0019\x007E\x0003\x007F\x0044\x0000\x0001\x007E\x0001\x0000\x000B\x007E" + "\x0037\x0000\x001B\x007F\x0001\x0000\x0004\x007F\x0036\x007E\x0003\x007F\x0001\x007E\x0012\x007F\x0001\x007E\x0007\x007F" + "\x000A\x007E\x0002\x007F\x0002\x0000\x000A\x0080\x0001\x0000\x0007\x007E\x0001\x0000\x0007\x007E\x0001\x0000\x0003\x007F" + "\x0001\x0000\x0008\x007E\x0002\x0000\x0002\x007E\x0002\x0000\x0016\x007E\x0001\x0000\x0007\x007E\x0001\x0000\x0001\x007E" + "\x0003\x0000\x0004\x007E\x0002\x0000\x0001\x007F\x0001\x007E\x0007\x007F\x0002\x0000\x0002\x007F\x0002\x0000\x0003\x007F" + "\x0001\x007E\x0008\x0000\x0001\x007F\x0004\x0000\x0002\x007E\x0001\x0000\x0003\x007E\x0002\x007F\x0002\x0000\x000A\x0080" + "\x0002\x007E\x000F\x0000\x0003\x007F\x0001\x0000\x0006\x007E\x0004\x0000\x0002\x007E\x0002\x0000\x0016\x007E\x0001\x0000" + "\x0007\x007E\x0001\x0000\x0002\x007E\x0001\x0000\x0002\x007E\x0001\x0000\x0002\x007E\x0002\x0000\x0001\x007F\x0001\x0000" + "\x0005\x007F\x0004\x0000\x0002\x007F\x0002\x0000\x0003\x007F\x0003\x0000\x0001\x007F\x0007\x0000\x0004\x007E\x0001\x0000" + "\x0001\x007E\x0007\x0000\x000A\x0080\x0002\x007F\x0003\x007E\x0001\x007F\x000B\x0000\x0003\x007F\x0001\x0000\x0009\x007E" + "\x0001\x0000\x0003\x007E\x0001\x0000\x0016\x007E\x0001\x0000\x0007\x007E\x0001\x0000\x0002\x007E\x0001\x0000\x0005\x007E" + "\x0002\x0000\x0001\x007F\x0001\x007E\x0008\x007F\x0001\x0000\x0003\x007F\x0001\x0000\x0003\x007F\x0002\x0000\x0001\x007E" + "\x000F\x0000\x0002\x007E\x0002\x007F\x0002\x0000\x000A\x0080\x0011\x0000\x0003\x007F\x0001\x0000\x0008\x007E\x0002\x0000" + "\x0002\x007E\x0002\x0000\x0016\x007E\x0001\x0000\x0007\x007E\x0001\x0000\x0002\x007E\x0001\x0000\x0005\x007E\x0002\x0000" + "\x0001\x007F\x0001\x007E\x0007\x007F\x0002\x0000\x0002\x007F\x0002\x0000\x0003\x007F\x0008\x0000\x0002\x007F\x0004\x0000" + "\x0002\x007E\x0001\x0000\x0003\x007E\x0002\x007F\x0002\x0000\x000A\x0080\x0001\x0000\x0001\x007E\x0010\x0000\x0001\x007F" + "\x0001\x007E\x0001\x0000\x0006\x007E\x0003\x0000\x0003\x007E\x0001\x0000\x0004\x007E\x0003\x0000\x0002\x007E\x0001\x0000" + "\x0001\x007E\x0001\x0000\x0002\x007E\x0003\x0000\x0002\x007E\x0003\x0000\x0003\x007E\x0003\x0000\x000C\x007E\x0004\x0000" + "\x0005\x007F\x0003\x0000\x0003\x007F\x0001\x0000\x0004\x007F\x0002\x0000\x0001\x007E\x0006\x0000\x0001\x007F\x000E\x0000" + "\x000A\x0080\x0011\x0000\x0003\x007F\x0001\x0000\x0008\x007E\x0001\x0000\x0003\x007E\x0001\x0000\x0017\x007E\x0001\x0000" + "\x000A\x007E\x0001\x0000\x0005\x007E\x0003\x0000\x0001\x007E\x0007\x007F\x0001\x0000\x0003\x007F\x0001\x0000\x0004\x007F" + "\x0007\x0000\x0002\x007F\x0001\x0000\x0002\x007E\x0006\x0000\x0002\x007E\x0002\x007F\x0002\x0000\x000A\x0080\x0012\x0000" + "\x0002\x007F\x0001\x0000\x0008\x007E\x0001\x0000\x0003\x007E\x0001\x0000\x0017\x007E\x0001\x0000\x000A\x007E\x0001\x0000" + "\x0005\x007E\x0002\x0000\x0001\x007F\x0001\x007E\x0007\x007F\x0001\x0000\x0003\x007F\x0001\x0000\x0004\x007F\x0007\x0000" + "\x0002\x007F\x0007\x0000\x0001\x007E\x0001\x0000\x0002\x007E\x0002\x007F\x0002\x0000\x000A\x0080\x0001\x0000\x0002\x007E" + "\x000F\x0000\x0002\x007F\x0001\x0000\x0008\x007E\x0001\x0000\x0003\x007E\x0001\x0000\x0029\x007E\x0002\x0000\x0001\x007E" + "\x0007\x007F\x0001\x0000\x0003\x007F\x0001\x0000\x0004\x007F\x0001\x007E\x0008\x0000\x0001\x007F\x0008\x0000\x0002\x007E" + "\x0002\x007F\x0002\x0000\x000A\x0080\x000A\x0000\x0006\x007E\x0002\x0000\x0002\x007F\x0001\x0000\x0012\x007E\x0003\x0000" + "\x0018\x007E\x0001\x0000\x0009\x007E\x0001\x0000\x0001\x007E\x0002\x0000\x0007\x007E\x0003\x0000\x0001\x007F\x0004\x0000" + "\x0006\x007F\x0001\x0000\x0001\x007F\x0001\x0000\x0008\x007F\x0012\x0000\x0002\x007F\x000D\x0000\x0030\x0086\x0001\x0087" + "\x0002\x0086\x0007\x0087\x0005\x0000\x0007\x0086\x0008\x0087\x0001\x0000\x000A\x0080\x0027\x0000\x0002\x0086\x0001\x0000" + "\x0001\x0086\x0002\x0000\x0002\x0086\x0001\x0000\x0001\x0086\x0002\x0000\x0001\x0086\x0006\x0000\x0004\x0086\x0001\x0000" + "\x0007\x0086\x0001\x0000\x0003\x0086\x0001\x0000\x0001\x0086\x0001\x0000\x0001\x0086\x0002\x0000\x0002\x0086\x0001\x0000" + "\x0004\x0086\x0001\x0087\x0002\x0086\x0006\x0087\x0001\x0000\x0002\x0087\x0001\x0086\x0002\x0000\x0005\x0086\x0001\x0000" + "\x0001\x0086\x0001\x0000\x0006\x0087\x0002\x0000\x000A\x0080\x0002\x0000\x0004\x0086\x0020\x0000\x0001\x007E\x0017\x0000" + "\x0002\x007F\x0006\x0000\x000A\x0080\x000B\x0000\x0001\x007F\x0001\x0000\x0001\x007F\x0001\x0000\x0001\x007F\x0004\x0000" + "\x0002\x007F\x0008\x007E\x0001\x0000\x0024\x007E\x0004\x0000\x0014\x007F\x0001\x0000\x0002\x007F\x0005\x007E\x000B\x007F" + "\x0001\x0000\x0024\x007F\x0009\x0000\x0001\x007F\x0039\x0000\x002B\x0086\x0014\x0087\x0001\x0086\x000A\x0080\x0006\x0000" + "\x0006\x0086\x0004\x0087\x0004\x0086\x0003\x0087\x0001\x0086\x0003\x0087\x0002\x0086\x0007\x0087\x0003\x0086\x0004\x0087" + "\x000D\x0086\x000C\x0087\x0001\x0086\x0001\x0087\x000A\x0080\x0004\x0087\x0002\x0086\x0026\x007E\x0001\x0000\x0001\x007E" + "\x0005\x0000\x0001\x007E\x0002\x0000\x002B\x007E\x0001\x0000\x0004\x007E\u0100\x008D\x0049\x007E\x0001\x0000\x0004\x007E" + "\x0002\x0000\x0007\x007E\x0001\x0000\x0001\x007E\x0001\x0000\x0004\x007E\x0002\x0000\x0029\x007E\x0001\x0000\x0004\x007E" + "\x0002\x0000\x0021\x007E\x0001\x0000\x0004\x007E\x0002\x0000\x0007\x007E\x0001\x0000\x0001\x007E\x0001\x0000\x0004\x007E" + "\x0002\x0000\x000F\x007E\x0001\x0000\x0039\x007E\x0001\x0000\x0004\x007E\x0002\x0000\x0043\x007E\x0002\x0000\x0003\x007F" + "\x0020\x0000\x0010\x007E\x0010\x0000\x0055\x007E\x000C\x0000\u026c\x007E\x0002\x0000\x0011\x007E\x0001\x0000\x001A\x007E" + "\x0005\x0000\x004B\x007E\x0003\x0000\x0003\x007E\x000F\x0000\x000D\x007E\x0001\x0000\x0004\x007E\x0003\x007F\x000B\x0000" + "\x0012\x007E\x0003\x007F\x000B\x0000\x0012\x007E\x0002\x007F\x000C\x0000\x000D\x007E\x0001\x0000\x0003\x007E\x0001\x0000" + "\x0002\x007F\x000C\x0000\x0034\x0086\x0020\x0087\x0003\x0000\x0001\x0086\x0004\x0000\x0001\x0086\x0001\x0087\x0002\x0000" + "\x000A\x0080\x0021\x0000\x0003\x007F\x0001\x007F\x0001\x0000\x000A\x0080\x0006\x0000\x0058\x007E\x0008\x0000\x0029\x007E" + "\x0001\x007F\x0001\x007E\x0005\x0000\x0046\x007E\x000A\x0000\x001D\x007E\x0003\x0000\x000C\x007F\x0004\x0000\x000C\x007F" + "\x000A\x0000\x000A\x0080\x001E\x0086\x0002\x0000\x0005\x0086\x000B\x0000\x002C\x0086\x0004\x0000\x0011\x0087\x0007\x0086" + "\x0002\x0087\x0006\x0000\x000A\x0080\x0001\x0086\x0003\x0000\x0002\x0086\x0020\x0000\x0017\x007E\x0005\x007F\x0004\x0000" + "\x0035\x0086\x000A\x0087\x0001\x0000\x001D\x0087\x0002\x0000\x0001\x007F\x000A\x0080\x0006\x0000\x000A\x0080\x0006\x0000" + "\x000E\x0086\x0052\x0000\x0005\x007F\x002F\x007E\x0011\x007F\x0007\x007E\x0004\x0000\x000A\x0080\x0011\x0000\x0009\x007F" + "\x000C\x0000\x0003\x007F\x001E\x007E\x000D\x007F\x0002\x007E\x000A\x0080\x002C\x007E\x000E\x007F\x000C\x0000\x0024\x007E" + "\x0014\x007F\x0008\x0000\x000A\x0080\x0003\x0000\x0003\x007E\x000A\x0080\x0024\x007E\x0052\x0000\x0003\x007F\x0001\x0000" + "\x0015\x007F\x0004\x007E\x0001\x007F\x0004\x007E\x0003\x007F\x0002\x007E\x0009\x0000\x00C0\x007E\x0027\x007F\x0015\x0000" + "\x0004\x007F\u0116\x007E\x0002\x0000\x0006\x007E\x0002\x0000\x0026\x007E\x0002\x0000\x0006\x007E\x0002\x0000\x0008\x007E" + "\x0001\x0000\x0001\x007E\x0001\x0000\x0001\x007E\x0001\x0000\x0001\x007E\x0001\x0000\x001F\x007E\x0002\x0000\x0035\x007E" + "\x0001\x0000\x0007\x007E\x0001\x0000\x0001\x007E\x0003\x0000\x0003\x007E\x0001\x0000\x0007\x007E\x0003\x0000\x0004\x007E" + "\x0002\x0000\x0006\x007E\x0004\x0000\x000D\x007E\x0005\x0000\x0003\x007E\x0001\x0000\x0007\x007E\x000F\x0000\x0002\x007F" + "\x0002\x007F\x0008\x0000\x0002\x0084\x000A\x0000\x0001\x0084\x0002\x0000\x0001\x0082\x0002\x0000\x0005\x007F\x0010\x0000" + "\x0002\x0085\x0003\x0000\x0001\x0083\x000F\x0000\x0001\x0085\x000B\x0000\x0005\x007F\x0001\x0000\x000A\x007F\x0001\x0000" + "\x0001\x007E\x000D\x0000\x0001\x007E\x0010\x0000\x000D\x007E\x0033\x0000\x0021\x007F\x0011\x0000\x0001\x007E\x0004\x0000" + "\x0001\x007E\x0002\x0000\x000A\x007E\x0001\x0000\x0001\x007E\x0003\x0000\x0005\x007E\x0006\x0000\x0001\x007E\x0001\x0000" + "\x0001\x007E\x0001\x0000\x0001\x007E\x0001\x0000\x0004\x007E\x0001\x0000\x000B\x007E\x0002\x0000\x0004\x007E\x0005\x0000" + "\x0005\x007E\x0004\x0000\x0001\x007E\x0011\x0000\x0029\x007E\u032d\x0000\x0034\x007E\u0716\x0000\x002F\x007E\x0001\x0000" + "\x002F\x007E\x0001\x0000\x0085\x007E\x0006\x0000\x0004\x007E\x0003\x007F\x0002\x007E\x000C\x0000\x0026\x007E\x0001\x0000" + "\x0001\x007E\x0005\x0000\x0001\x007E\x0002\x0000\x0038\x007E\x0007\x0000\x0001\x007E\x000F\x0000\x0001\x007F\x0017\x007E" + "\x0009\x0000\x0007\x007E\x0001\x0000\x0007\x007E\x0001\x0000\x0007\x007E\x0001\x0000\x0007\x007E\x0001\x0000\x0007\x007E" + "\x0001\x0000\x0007\x007E\x0001\x0000\x0007\x007E\x0001\x0000\x0007\x007E\x0001\x0000\x0020\x007F\x002F\x0000\x0001\x007E" + "\x0050\x0000\x001A\x0088\x0001\x0000\x0059\x0088\x000C\x0000\x00D6\x0088\x002F\x0000\x0001\x007E\x0001\x0000\x0001\x0088" + "\x0019\x0000\x0009\x0088\x0006\x007F\x0001\x0000\x0005\x0081\x0002\x0000\x0003\x0088\x0001\x007E\x0001\x007E\x0004\x0000" + "\x0056\x0089\x0002\x0000\x0002\x007F\x0002\x0081\x0003\x0089\x005B\x0081\x0001\x0000\x0004\x0081\x0005\x0000\x0029\x007E" + "\x0003\x0000\x005E\x008D\x0011\x0000\x001B\x007E\x0035\x0000\x0010\x0081\x00D0\x0000\x002F\x0081\x0001\x0000\x0058\x0081" + "\x00A8\x0000\u19b6\x0088\x004A\x0000\u51cd\x0088\x0033\x0000\u048d\x007E\x0043\x0000\x002E\x007E\x0002\x0000\u010d\x007E" + "\x0003\x0000\x0010\x007E\x000A\x0080\x0002\x007E\x0014\x0000\x002F\x007E\x0004\x007F\x0001\x0000\x000A\x007F\x0001\x0000" + "\x0019\x007E\x0007\x0000\x0001\x007F\x0050\x007E\x0002\x007F\x0025\x0000\x0009\x007E\x0002\x0000\x0067\x007E\x0002\x0000" + "\x0004\x007E\x0001\x0000\x0004\x007E\x000C\x0000\x000B\x007E\x004D\x0000\x000A\x007E\x0001\x007F\x0003\x007E\x0001\x007F" + "\x0004\x007E\x0001\x007F\x0017\x007E\x0005\x007F\x0018\x0000\x0034\x007E\x000C\x0000\x0002\x007F\x0032\x007E\x0011\x007F" + "\x000B\x0000\x000A\x0080\x0006\x0000\x0012\x007F\x0006\x007E\x0003\x0000\x0001\x007E\x0004\x0000\x000A\x0080\x001C\x007E" + "\x0008\x007F\x0002\x0000\x0017\x007E\x000D\x007F\x000C\x0000\x001D\x008D\x0003\x0000\x0004\x007F\x002F\x007E\x000E\x007F" + "\x000E\x0000\x0001\x007E\x000A\x0080\x0026\x0000\x0029\x007E\x000E\x007F\x0009\x0000\x0003\x007E\x0001\x007F\x0008\x007E" + "\x0002\x007F\x0002\x0000\x000A\x0080\x0006\x0000\x001B\x0086\x0001\x0087\x0004\x0000\x0030\x0086\x0001\x0087\x0001\x0086" + "\x0003\x0087\x0002\x0086\x0002\x0087\x0005\x0086\x0002\x0087\x0001\x0086\x0001\x0087\x0001\x0086\x0018\x0000\x0005\x0086" + "\x000B\x007E\x0005\x007F\x0002\x0000\x0003\x007E\x0002\x007F\x000A\x0000\x0006\x007E\x0002\x0000\x0006\x007E\x0002\x0000" + "\x0006\x007E\x0009\x0000\x0007\x007E\x0001\x0000\x0007\x007E\x0091\x0000\x0023\x007E\x0008\x007F\x0001\x0000\x0002\x007F" + "\x0002\x0000\x000A\x0080\x0006\x0000\u2ba4\x008D\x000C\x0000\x0017\x008D\x0004\x0000\x0031\x008D\x0004\x0000\x0001\x0024" + "\x0001\x0020\x0001\x0037\x0001\x0034\x0001\x001B\x0001\x0018\x0002\x0000\x0001\x0014\x0001\x0011\x0002\x0000\x0001\x000F" + "\x0001\x000D\x000C\x0000\x0001\x0003\x0001\x0006\x0010\x0000\x0001\x006E\x0007\x0000\x0001\x0049\x0001\x0008\x0005\x0000" + "\x0001\x0001\x0001\x007A\x0003\x0000\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073" + "\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073" + "\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073" + "\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073" + "\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0074\x0001\x0073\x0001\x0073\x0001\x0073\x0001\x0078\x0001\x0076" + "\x000F\x0000\x0001\x0070\u02c1\x0000\x0001\x004C\x00BF\x0000\x0001\x006F\x0001\x004D\x0001\x000E\x0003\x0077\x0002\x0032" + "\x0001\x0077\x0001\x0032\x0002\x0077\x0001\x001E\x0011\x0077\x0002\x0046\x0007\x004F\x0001\x004E\x0007\x004F\x0007\x0042" + "\x0001\x001F\x0001\x0042\x0001\x0060\x0002\x0036\x0001\x0035\x0001\x0060\x0001\x0036\x0001\x0035\x0008\x0060\x0002\x0047" + "\x0005\x0043\x0002\x003D\x0005\x0043\x0001\x0012\x0008\x002B\x0005\x0013\x0003\x0021\x000A\x0052\x0010\x0021\x0003\x0033" + "\x001A\x0023\x0001\x0022\x0002\x0031\x0002\x0056\x0001\x0057\x0002\x0056\x0002\x0057\x0002\x0056\x0001\x0057\x0003\x0031" + "\x0001\x0030\x0002\x0031\x000A\x0048\x0001\x005E\x0001\x0028\x0001\x0025\x0001\x0048\x0006\x0028\x0001\x0025\x000B\x0028" + "\x0019\x0031\x0007\x0028\x000A\x0053\x0001\x0028\x0005\x000B\x0003\x005F\x0003\x0041\x0001\x0040\x0004\x0041\x0002\x0040" + "\x0008\x0041\x0001\x0040\x0007\x001D\x0001\x001C\x0002\x001D\x0007\x0041\x000E\x005F\x0001\x0069\x0004\x0054\x0001\x0004" + "\x0004\x0051\x0001\x0004\x0005\x0068\x0001\x0067\x0001\x0068\x0003\x0067\x0007\x0068\x0001\x0067\x0013\x0068\x0005\x004B" + "\x0003\x0068\x0006\x004B\x0002\x004B\x0006\x004A\x0005\x004A\x0003\x0064\x0002\x0041\x0007\x0063\x001E\x0041\x0004\x0063" + "\x0005\x0041\x0005\x005F\x0006\x005D\x0002\x005F\x0001\x005D\x0004\x001D\x000B\x0066\x000A\x0051\x000C\x0066\x000A\x007D" + "\x000D\x007C\x0001\x0065\x0002\x007C\x0001\x007B\x0003\x006A\x0001\x000B\x0002\x006A\x0005\x0071\x0004\x006A\x0004\x0072" + "\x0001\x0071\x0003\x0072\x0001\x0071\x0005\x0072\x0002\x0038\x0001\x003B\x0002\x0038\x0001\x003B\x0001\x0038\x0002\x003B" + "\x0001\x0038\x0001\x003B\x000A\x0038\x0001\x003B\x0004\x0005\x0001\x006C\x0001\x006B\x0001\x006D\x0001\x000A\x0003\x0075" + "\x0001\x006D\x0002\x0075\x0001\x0061\x0002\x0062\x0002\x0075\x0001\x000A\x0001\x0075\x0001\x000A\x0001\x0075\x0001\x000A" + "\x0001\x0075\x0003\x000A\x0001\x0075\x0002\x000A\x0001\x0075\x0001\x000A\x0002\x0075\x0001\x000A\x0001\x0075\x0001\x000A" + "\x0001\x0075\x0001\x000A\x0001\x0075\x0001\x000A\x0001\x0075\x0001\x000A\x0001\x003E\x0002\x003A\x0001\x003E\x0001\x003A" + "\x0002\x003E\x0004\x003A\x0001\x003E\x0007\x003A\x0001\x003E\x0004\x003A\x0001\x003E\x0004\x003A\x0001\x0075\x0001\x000A" + "\x0001\x0075\x000A\x0019\x0001\x002F\x0011\x0019\x0001\x002F\x0003\x001A\x0001\x002F\x0003\x0019\x0001\x002F\x0001\x0019" + "\x0002\x0002\x0002\x0019\x0001\x002F\x000D\x005C\x0004\x0027\x0004\x002C\x0001\x0050\x0001\x002E\x0008\x0050\x0007\x002C" + "\x0006\x0075\x0004\x0015\x0001\x0017\x001F\x0015\x0001\x0017\x0004\x0015\x0015\x0045\x0001\x0079\x0009\x0045\x0011\x0016" + "\x0005\x0045\x0001\x0007\x000A\x002D\x0005\x0045\x0006\x0044\x0004\x003E\x0001\x003F\x0001\x0016\x0005\x005B\x000A\x0059" + "\x000F\x005B\x0001\x003C\x0003\x0039\x000C\x0058\x0001\x0009\x0009\x0026\x0001\x002A\x0005\x0026\x0004\x005A\x000B\x0029" + "\x0002\x000C\x0009\x0026\x0001\x002A\x0019\x0026\x0001\x002A\x0004\x0009\x0004\x0026\x0002\x002A\x0002\x0055\x0001\x0010" + "\x0005\x0055\x002A\x0010\u1900\x0000\u016e\x0088\x0002\x0000\x006A\x0088\x0026\x0000\x0007\x007E\x000C\x0000\x0005\x007E" + "\x0005\x0000\x0001\x008C\x0001\x007F\x000A\x008C\x0001\x0000\x000D\x008C\x0001\x0000\x0005\x008C\x0001\x0000\x0001\x008C" + "\x0001\x0000\x0002\x008C\x0001\x0000\x0002\x008C\x0001\x0000\x000A\x008C\x0062\x007E\x0021\x0000\u016b\x007E\x0012\x0000" + "\x0040\x007E\x0002\x0000\x0036\x007E\x0028\x0000\x000C\x007E\x0004\x0000\x0010\x007F\x0001\x0083\x0002\x0000\x0001\x0082" + "\x0001\x0083\x000B\x0000\x0007\x007F\x000C\x0000\x0002\x0085\x0018\x0000\x0003\x0085\x0001\x0083\x0001\x0000\x0001\x0084" + "\x0001\x0000\x0001\x0083\x0001\x0082\x001A\x0000\x0005\x007E\x0001\x0000\x0087\x007E\x0002\x0000\x0001\x007F\x0007\x0000" + "\x0001\x0084\x0004\x0000\x0001\x0083\x0001\x0000\x0001\x0084\x0001\x0000\x000A\x0080\x0001\x0082\x0001\x0083\x0005\x0000" + "\x001A\x007E\x0004\x0000\x0001\x0085\x0001\x0000\x001A\x007E\x000B\x0000\x0038\x0081\x0002\x007F\x001F\x008D\x0003\x0000" + "\x0006\x008D\x0002\x0000\x0006\x008D\x0002\x0000\x0006\x008D\x0002\x0000\x0003\x008D\x001C\x0000\x0003\x007F\x0004\x0000"; /// <summary> /// Translates characters to character classes /// </summary> private static readonly char[] ZZ_CMAP = ZzUnpackCMap(ZZ_CMAP_PACKED); /// <summary> /// Translates DFA states to action switch labels. /// </summary> private static readonly int[] ZZ_ACTION = ZzUnpackAction(); private const string ZZ_ACTION_PACKED_0 = "\x0001\x0000\x0016\x0001\x0001\x0002\x0001\x0003\x0001\x0004\x0001\x0001\x0001\x0005\x0001\x0006" + "\x0001\x0007\x0001\x0002\x0001\x0008\x0011\x0000\x0001\x0002\x0001\x0000\x0001\x0002\x000A\x0000" + "\x0001\x0003\x0011\x0000\x0001\x0002\x0015\x0000\x0001\x0002\x004D\x0000\x0001\x0001\x0010\x0000"; private static int[] ZzUnpackAction() { int[] result = new int[197]; int offset = 0; offset = ZzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int ZzUnpackAction(string packed, int offset, int[] result) { int i = 0; // index in packed string int j = offset; // index in unpacked array int l = packed.Length; while (i < l) { int count = packed[i++]; int value = packed[i++]; do { result[j++] = value; } while (--count > 0); } return j; } /// <summary> /// Translates a state to a row index in the transition table /// </summary> private static readonly int[] ZZ_ROWMAP = ZzUnpackRowMap(); private const string ZZ_ROWMAP_PACKED_0 = "\x0000\x0000\x0000\x008E\x0000\u011c\x0000\u01aa\x0000\u0238\x0000\u02c6\x0000\u0354\x0000\u03e2" + "\x0000\u0470\x0000\u04fe\x0000\u058c\x0000\u061a\x0000\u06a8\x0000\u0736\x0000\u07c4\x0000\u0852" + "\x0000\u08e0\x0000\u096e\x0000\u09fc\x0000\u0a8a\x0000\u0b18\x0000\u0ba6\x0000\u0c34\x0000\u0cc2" + "\x0000\u0d50\x0000\u0dde\x0000\u0e6c\x0000\u0efa\x0000\u0f88\x0000\u1016\x0000\u10a4\x0000\u1132" + "\x0000\u11c0\x0000\u011c\x0000\u01aa\x0000\u124e\x0000\u12dc\x0000\u0354\x0000\u03e2\x0000\u0470" + "\x0000\u04fe\x0000\u136a\x0000\u13f8\x0000\u1486\x0000\u1514\x0000\u07c4\x0000\u15a2\x0000\u1630" + "\x0000\u16be\x0000\u174c\x0000\u17da\x0000\u1868\x0000\u18f6\x0000\u02c6\x0000\u1984\x0000\u1a12" + "\x0000\u06a8\x0000\u1aa0\x0000\u1b2e\x0000\u1bbc\x0000\u1c4a\x0000\u1cd8\x0000\u1d66\x0000\u1df4" + "\x0000\u1e82\x0000\u1f10\x0000\u1f9e\x0000\u202c\x0000\u20ba\x0000\u2148\x0000\u21d6\x0000\u2264" + "\x0000\u22f2\x0000\u2380\x0000\u240e\x0000\u249c\x0000\u252a\x0000\u25b8\x0000\u2646\x0000\u0e6c" + "\x0000\u26d4\x0000\u2762\x0000\u27f0\x0000\u287e\x0000\u290c\x0000\u299a\x0000\u2a28\x0000\u2ab6" + "\x0000\u2b44\x0000\u2bd2\x0000\u2c60\x0000\u2cee\x0000\u2d7c\x0000\u2e0a\x0000\u2e98\x0000\u2f26" + "\x0000\u2fb4\x0000\u3042\x0000\u30d0\x0000\u315e\x0000\u31ec\x0000\u327a\x0000\u3308\x0000\u3396" + "\x0000\u3424\x0000\u34b2\x0000\u3540\x0000\u35ce\x0000\u365c\x0000\u36ea\x0000\u3778\x0000\u3806" + "\x0000\u3894\x0000\u3922\x0000\u39b0\x0000\u3a3e\x0000\u3acc\x0000\u3b5a\x0000\u3be8\x0000\u3c76" + "\x0000\u3d04\x0000\u3d92\x0000\u3e20\x0000\u3eae\x0000\u3f3c\x0000\u3fca\x0000\u4058\x0000\u40e6" + "\x0000\u4174\x0000\u4202\x0000\u4290\x0000\u431e\x0000\u43ac\x0000\u443a\x0000\u44c8\x0000\u4556" + "\x0000\u45e4\x0000\u4672\x0000\u4700\x0000\u478e\x0000\u481c\x0000\u48aa\x0000\u4938\x0000\u49c6" + "\x0000\u4a54\x0000\u4ae2\x0000\u4b70\x0000\u4bfe\x0000\u4c8c\x0000\u4d1a\x0000\u4da8\x0000\u4e36" + "\x0000\u4ec4\x0000\u4f52\x0000\u4fe0\x0000\u506e\x0000\u50fc\x0000\u518a\x0000\u5218\x0000\u52a6" + "\x0000\u5334\x0000\u53c2\x0000\u5450\x0000\u54de\x0000\u556c\x0000\u55fa\x0000\u5688\x0000\u5716" + "\x0000\u57a4\x0000\u5832\x0000\u58c0\x0000\u594e\x0000\u59dc\x0000\u5a6a\x0000\u5af8\x0000\u5b86" + "\x0000\u5c14\x0000\u5ca2\x0000\u5d30\x0000\u5dbe\x0000\u5e4c\x0000\u5eda\x0000\u5f68\x0000\u5ff6" + "\x0000\u6084\x0000\u6112\x0000\u61a0\x0000\u622e\x0000\u62bc\x0000\u634a\x0000\u63d8\x0000\u6466" + "\x0000\u64f4\x0000\u6582\x0000\u6610\x0000\u669e\x0000\u672c"; private static int[] ZzUnpackRowMap() { int[] result = new int[197]; int offset = 0; offset = ZzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int ZzUnpackRowMap(string packed, int offset, int[] result) { int i = 0; // index in packed string int j = offset; // index in unpacked array int l = packed.Length; while (i < l) { int high = packed[i++] << 16; result[j++] = high | packed[i++]; } return j; } /// <summary> /// The transition table of the DFA /// </summary> private static readonly int[] ZZ_TRANS = ZzUnpackTrans(); private const string ZZ_TRANS_PACKED_0 = "\x0001\x0002\x0001\x0003\x0001\x0002\x0001\x0004\x0002\x0002\x0001\x0005\x0001\x0002\x0001\x0006" + "\x0004\x0002\x0001\x0007\x0001\x0002\x0001\x0008\x0001\x0002\x0001\x0009\x0002\x0002\x0001\x000A" + "\x0003\x0002\x0001\x000B\x0002\x0002\x0001\x000C\x0004\x0002\x0001\x000D\x0003\x0002\x0001\x000E" + "\x000F\x0002\x0001\x000F\x0002\x0002\x0001\x0010\x0036\x0002\x0001\x0011\x0001\x0002\x0001\x0012" + "\x0002\x0002\x0001\x0013\x0001\x0014\x0001\x0002\x0001\x0015\x0001\x0002\x0001\x0016\x0001\x0002" + "\x0001\x0017\x0003\x0002\x0001\x0018\x0001\x0002\x0001\x0019\x0001\x001A\x0003\x0002\x0001\x001B" + "\x0002\x001C\x0001\x001D\x0001\x001E\x0002\x0002\x0001\x001F\x0001\x0020\x0090\x0000\x0001\x0018" + "\x0002\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x000E\x0000\x0001\x0018\x000D\x0000\x0001\x0018" + "\x0010\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0021\x0000\x0001\x0018\x0004\x0000\x0001\x0018" + "\x0008\x0000\x0002\x0018\x0005\x0000\x0002\x0018\x0008\x0000\x0001\x0018\x0016\x0000\x0002\x0018" + "\x0005\x0000\x0001\x0018\x0002\x0000\x0001\x0018\x0003\x0000\x0002\x0018\x0008\x0000\x0004\x0018" + "\x0001\x0000\x0003\x0018\x0001\x0000\x0001\x0018\x0002\x0000\x0001\x0018\x0002\x0000\x0001\x0018" + "\x0004\x0000\x0004\x0018\x0001\x0000\x0002\x0018\x0001\x0000\x0001\x0018\x0002\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0018\x0002\x0000\x0004\x0018\x0002\x0000\x0003\x0018\x0001\x0000\x0002\x0018" + "\x0001\x0000\x0003\x0018\x0001\x0000\x0004\x0018\x0001\x0000\x0002\x0018\x0005\x0000\x0004\x0018" + "\x0002\x0000\x0008\x0018\x0001\x0000\x0001\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0002\x0018" + "\x0004\x0000\x0001\x0018\x0003\x0000\x0003\x0018\x0017\x0000\x0001\x0018\x0004\x0000\x0001\x0018" + "\x0009\x0000\x0001\x0018\x0012\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0017\x0000\x0001\x0018" + "\x0033\x0000\x0001\x0018\x0019\x0000\x0001\x0018\x0003\x0000\x0004\x0018\x0001\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0019\x0002\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000\x0002\x0018" + "\x0002\x0000\x0003\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0002\x0000\x0004\x0018" + "\x0001\x0000\x0003\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0003\x0018\x0001\x0000\x0002\x0018" + "\x0001\x0000\x0004\x0018\x0001\x0000\x0002\x0018\x0002\x0000\x0008\x0018\x0001\x0000\x0002\x0018" + "\x0001\x0000\x0008\x0018\x0001\x0019\x0001\x0000\x0007\x0018\x0001\x0000\x0008\x0018\x0001\x0000" + "\x0006\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x0003\x0000\x0003\x0018\x001E\x0000\x0001\x0018\x000F\x0000\x0001\x0018\x0013\x0000" + "\x0001\x0018\x0013\x0000\x0001\x0018\x0006\x0000\x0003\x0018\x001F\x0000\x0001\x0018\x0007\x0000" + "\x0001\x0018\x0018\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0001\x0000\x0001\x0018\x0001\x0000" + "\x0004\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0001\x0000" + "\x0003\x0018\x0001\x0000\x0002\x0018\x0001\x0000\x0004\x0018\x0001\x0000\x0003\x0018\x0001\x0000" + "\x000F\x0018\x0001\x0000\x0002\x0018\x0001\x0000\x0011\x0018\x0001\x0000\x0002\x0018\x0001\x0000" + "\x0021\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0003\x0018\x001E\x0000\x0001\x0018\x0003\x0000" + "\x0002\x0018\x000A\x0000\x0002\x0018\x000B\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0002\x0000" + "\x0002\x0018\x0006\x0000\x0001\x0018\x0004\x0000\x0002\x0018\x0002\x0000\x0002\x0018\x0005\x0000" + "\x0003\x0018\x0010\x0000\x0001\x0018\x000E\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0018\x0000" + "\x0001\x0018\x0001\x0000\x0002\x0018\x0001\x0000\x0001\x0018\x0002\x0000\x0002\x0018\x0002\x0000" + "\x0001\x0018\x0003\x0000\x0002\x0018\x0001\x0000\x0003\x0018\x0001\x0000\x0002\x0018\x0001\x0000" + "\x0004\x0018\x0001\x0000\x0003\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000" + "\x0009\x0018\x0001\x0000\x0002\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0001\x0000" + "\x000C\x0018\x0001\x0000\x0002\x0018\x0001\x0000\x0008\x0018\x0001\x0000\x0002\x0018\x0001\x0000" + "\x0001\x0018\x0001\x0000\x0013\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0003\x0018\x0012\x0000" + "\x0001\x0018\x0016\x0000\x0002\x0018\x0013\x0000\x0001\x0019\x0001\x0018\x0020\x0000\x0001\x0019" + "\x0041\x0000\x0001\x0019\x0017\x0000\x0004\x0018\x0002\x0000\x0002\x0018\x000C\x0000\x0003\x0018" + "\x000D\x0000\x0003\x0018\x0003\x0000\x0001\x0018\x0007\x0000\x0002\x0018\x0001\x0000\x0004\x0019" + "\x0001\x0000\x0002\x0018\x000B\x0000\x0001\x0018\x0013\x0000\x0001\x0018\x0024\x0000\x0001\x0018" + "\x0003\x0000\x0002\x0018\x000A\x0000\x0002\x0018\x0001\x0000\x0003\x0018\x0007\x0000\x0001\x0018" + "\x0006\x0000\x0002\x0018\x0001\x0000\x0002\x0018\x0006\x0000\x0001\x0018\x0004\x0000\x0002\x0018" + "\x0002\x0000\x0002\x0018\x0005\x0000\x0003\x0018\x0002\x0000\x0001\x0018\x0003\x0000\x0002\x0019" + "\x0008\x0000\x0001\x0018\x000E\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0018\x0000\x0001\x0018" + "\x0004\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0006\x0000\x0001\x0018" + "\x0005\x0000\x0001\x0018\x0002\x0000\x0002\x0018\x0001\x0000\x000F\x0018\x0002\x0000\x0001\x0018" + "\x000B\x0000\x0007\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0002\x0018" + "\x0002\x0000\x0001\x0018\x0001\x0000\x0003\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0006\x0000\x0002\x0018\x0006\x0000\x0001\x0018" + "\x0007\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0022\x0000\x0001\x0018\x000F\x0000\x0002\x0018" + "\x0012\x0000\x0001\x0018\x0002\x0000\x0002\x0018\x000B\x0000\x0001\x0018\x0003\x0000\x0002\x0018" + "\x0005\x0000\x0003\x0018\x0010\x0000\x0001\x0018\x000E\x0000\x0001\x0018\x0007\x0000\x0001\x0018" + "\x001D\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0003\x0000\x0001\x0018" + "\x0007\x0000\x0001\x0018\x0019\x0000\x0010\x0018\x0005\x0000\x0003\x0018\x0004\x0000\x0001\x0018" + "\x0006\x0000\x0001\x0018\x0003\x0000\x0002\x0018\x0002\x0000\x0002\x0018\x0004\x0000\x0001\x0018" + "\x0005\x0000\x0001\x0018\x0002\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0001\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0018\x005F\x0000\x0001\x001E\x0021\x0000\x0001\x001A\x0022\x0000\x0001\x001D" + "\x0006\x0000\x0001\x001D\x0002\x0000\x0001\x001D\x0003\x0000\x0002\x001D\x0008\x0000\x0004\x001D" + "\x0001\x0000\x0003\x001D\x0001\x0000\x0001\x001D\x0002\x0000\x0001\x001D\x0002\x0000\x0001\x001D" + "\x0004\x0000\x0004\x001D\x0001\x0000\x0002\x001D\x0006\x0000\x0001\x001D\x0002\x0000\x0004\x001D" + "\x0002\x0000\x0003\x001D\x0001\x0000\x0002\x001D\x0001\x0000\x0003\x001D\x0001\x0000\x0004\x001D" + "\x0001\x0000\x0002\x001D\x0005\x0000\x0004\x001D\x0002\x0000\x0008\x001D\x0004\x0000\x0001\x001D" + "\x0001\x0000\x0002\x001D\x0004\x0000\x0001\x001D\x0003\x0000\x0003\x001D\x0012\x0000\x0001\x001D" + "\x0001\x0000\x0002\x001D\x0001\x0000\x0001\x001D\x0001\x0000\x0004\x001D\x0001\x0000\x0001\x001D" + "\x0001\x0000\x0001\x001D\x0001\x0000\x0002\x001D\x0001\x0000\x0003\x001D\x0001\x0000\x0002\x001D" + "\x0001\x0000\x0004\x001D\x0001\x0000\x0003\x001D\x0001\x0000\x000F\x001D\x0001\x0000\x0002\x001D" + "\x0001\x0000\x0011\x001D\x0001\x0000\x0002\x001D\x0001\x0000\x0021\x001D\x0001\x0000\x0001\x001D" + "\x0001\x0000\x0002\x001D\x0002\x0000\x0001\x001D\x0001\x0000\x0001\x001D\x0001\x0000\x0001\x001D" + "\x0001\x0000\x0003\x001D\x0012\x0000\x0001\x001D\x0001\x0000\x0002\x001D\x0001\x0000\x0001\x001D" + "\x0001\x0000\x0004\x001D\x0001\x0000\x0001\x001D\x0001\x0000\x0001\x001D\x0001\x0000\x0002\x001D" + "\x0002\x0000\x0001\x001D\x0002\x0000\x0002\x001D\x0001\x0000\x0004\x001D\x0001\x0000\x0003\x001D" + "\x0001\x0000\x000F\x001D\x0001\x0000\x0002\x001D\x0001\x0000\x0011\x001D\x0001\x0000\x0002\x001D" + "\x0001\x0000\x0021\x001D\x0001\x0000\x0001\x001D\x0001\x0000\x0002\x001D\x0002\x0000\x0001\x001D" + "\x0001\x0000\x0001\x001D\x0001\x0000\x0001\x001D\x0001\x0000\x0003\x001D\x001E\x0000\x0001\x001D" + "\x000F\x0000\x0001\x001D\x0013\x0000\x0001\x001D\x001A\x0000\x0001\x001D\x0021\x0000\x0001\x001D" + "\x0007\x0000\x0001\x001D\x0018\x0000\x0001\x001D\x0001\x0000\x0002\x001D\x0003\x0000\x0004\x001D" + "\x0001\x0000\x0001\x001D\x0001\x0000\x0001\x001D\x0001\x0000\x0002\x001D\x0001\x0000\x0003\x001D" + "\x0001\x0000\x0002\x001D\x0001\x0000\x0004\x001D\x0001\x0000\x0003\x001D\x0001\x0000\x0008\x001D" + "\x0001\x0000\x0006\x001D\x0001\x0000\x0002\x001D\x0001\x0000\x0011\x001D\x0001\x0000\x0002\x001D" + "\x0001\x0000\x0021\x001D\x0001\x0000\x0001\x001D\x0001\x0000\x0002\x001D\x0002\x0000\x0001\x001D" + "\x0001\x0000\x0001\x001D\x0001\x0000\x0001\x001D\x0001\x0000\x0003\x001D\x0075\x0000\x0001\x0021" + "\x0015\x0000\x0001\x001E\x0002\x0021\x0011\x0000\x0001\x0022\x0001\x0000\x0001\x0023\x0002\x0000" + "\x0001\x0024\x0001\x0000\x0001\x0025\x0004\x0000\x0001\x0026\x0001\x0000\x0001\x0027\x0001\x0000" + "\x0001\x0028\x0002\x0000\x0001\x0029\x0003\x0000\x0001\x002A\x0002\x0000\x0001\x002B\x0004\x0000" + "\x0001\x002C\x0003\x0000\x0001\x002D\x000F\x0000\x0001\x002E\x0002\x0000\x0001\x002F\x0011\x0000" + "\x0001\x0030\x0002\x0000\x0001\x0031\x0031\x0000\x0002\x0018\x0001\x0032\x0001\x0000\x0001\x0033" + "\x0001\x0000\x0001\x0033\x0001\x0034\x0001\x0000\x0001\x0018\x0002\x0000\x0001\x0033\x0001\x0000" + "\x0001\x001F\x0001\x0018\x0001\x0000\x0001\x0022\x0001\x0000\x0001\x0023\x0002\x0000\x0001\x0035" + "\x0001\x0000\x0001\x0036\x0004\x0000\x0001\x0026\x0001\x0000\x0001\x0027\x0001\x0000\x0001\x0028" + "\x0002\x0000\x0001\x0029\x0003\x0000\x0001\x0037\x0002\x0000\x0001\x0038\x0004\x0000\x0001\x0039" + "\x0003\x0000\x0001\x003A\x000F\x0000\x0001\x002E\x0002\x0000\x0001\x003B\x0011\x0000\x0001\x003C" + "\x0002\x0000\x0001\x003D\x0031\x0000\x0001\x0018\x0002\x0019\x0002\x0000\x0002\x003E\x0001\x003F" + "\x0001\x0000\x0001\x0019\x0002\x0000\x0001\x003E\x0001\x0000\x0001\x001F\x0001\x0018\x0006\x0000" + "\x0001\x0040\x0011\x0000\x0001\x0041\x0002\x0000\x0001\x0042\x0008\x0000\x0001\x0043\x0012\x0000" + "\x0001\x0044\x0011\x0000\x0001\x0045\x0002\x0000\x0001\x0046\x0021\x0000\x0001\x0047\x0010\x0000" + "\x0001\x001A\x0001\x0000\x0001\x001A\x0003\x0000\x0001\x0034\x0001\x0000\x0001\x001A\x0007\x0000" + "\x0001\x0022\x0001\x0000\x0001\x0023\x0002\x0000\x0001\x0048\x0001\x0000\x0001\x0036\x0004\x0000" + "\x0001\x0026\x0001\x0000\x0001\x0027\x0001\x0000\x0001\x0028\x0002\x0000\x0001\x0029\x0003\x0000" + "\x0001\x0049\x0002\x0000\x0001\x004A\x0004\x0000\x0001\x0039\x0003\x0000\x0001\x004B\x000F\x0000" + "\x0001\x002E\x0002\x0000\x0001\x004C\x0011\x0000\x0001\x004D\x0002\x0000\x0001\x004E\x0021\x0000" + "\x0001\x004F\x000F\x0000\x0001\x0018\x0001\x0050\x0001\x0019\x0001\x0051\x0003\x0000\x0001\x0050" + "\x0001\x0000\x0001\x0050\x0004\x0000\x0001\x001F\x0001\x0018\x0086\x0000\x0002\x001C\x000C\x0000" + "\x0001\x0052\x0011\x0000\x0001\x0053\x0002\x0000\x0001\x0054\x0008\x0000\x0001\x0055\x0012\x0000" + "\x0001\x0056\x0011\x0000\x0001\x0057\x0002\x0000\x0001\x0058\x0032\x0000\x0001\x001D\x0007\x0000" + "\x0001\x001D\x000C\x0000\x0001\x0059\x0011\x0000\x0001\x005A\x0002\x0000\x0001\x005B\x0008\x0000" + "\x0001\x005C\x0012\x0000\x0001\x005D\x0011\x0000\x0001\x005E\x0002\x0000\x0001\x005F\x0032\x0000" + "\x0001\x001E\x0007\x0000\x0001\x001E\x0007\x0000\x0001\x0022\x0001\x0000\x0001\x0023\x0002\x0000" + "\x0001\x0060\x0001\x0000\x0001\x0025\x0004\x0000\x0001\x0026\x0001\x0000\x0001\x0027\x0001\x0000" + "\x0001\x0028\x0002\x0000\x0001\x0029\x0003\x0000\x0001\x0061\x0002\x0000\x0001\x0062\x0004\x0000" + "\x0001\x002C\x0003\x0000\x0001\x0063\x000F\x0000\x0001\x002E\x0002\x0000\x0001\x0064\x0011\x0000" + "\x0001\x0065\x0002\x0000\x0001\x0066\x0031\x0000\x0001\x0018\x0001\x001F\x0001\x0032\x0001\x0000" + "\x0001\x0033\x0001\x0000\x0001\x0033\x0001\x0034\x0001\x0000\x0001\x001F\x0002\x0000\x0001\x0067" + "\x0001\x0068\x0001\x001F\x0001\x0018\x0001\x0000\x0001\x0022\x0001\x0000\x0001\x0023\x0002\x0000" + "\x0001\x0069\x0001\x0000\x0001\x0025\x0004\x0000\x0001\x0026\x0001\x0000\x0001\x0027\x0001\x0000" + "\x0001\x0028\x0002\x0000\x0001\x0029\x0003\x0000\x0001\x006A\x0002\x0000\x0001\x006B\x0004\x0000" + "\x0001\x002C\x0003\x0000\x0001\x006C\x000F\x0000\x0001\x002E\x0002\x0000\x0001\x006D\x0011\x0000" + "\x0001\x006E\x0002\x0000\x0001\x006F\x0031\x0000\x0001\x0018\x0001\x0020\x0001\x0032\x0001\x0000" + "\x0001\x0033\x0001\x0000\x0001\x0033\x0001\x0034\x0001\x0000\x0001\x0020\x0002\x0000\x0001\x0033" + "\x0001\x0000\x0001\x001F\x0001\x0020\x0006\x0000\x0001\x0070\x0011\x0000\x0001\x0071\x0002\x0000" + "\x0001\x0072\x0008\x0000\x0001\x0073\x0012\x0000\x0001\x0074\x0011\x0000\x0001\x0075\x0002\x0000" + "\x0001\x0076\x002D\x0000\x0001\x0077\x0004\x0000\x0001\x0021\x0007\x0000\x0001\x0021\x000D\x0000" + "\x0001\x0018\x0004\x0000\x0001\x0018\x0009\x0000\x0001\x0018\x0012\x0000\x0001\x0018\x0003\x0000" + "\x0001\x0018\x000B\x0000\x0001\x0018\x0002\x0000\x0001\x0018\x0008\x0000\x0001\x0018\x0012\x0000" + "\x0004\x0018\x001D\x0000\x0001\x0018\x0019\x0000\x0001\x0018\x0003\x0000\x0004\x0018\x0001\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0032\x0002\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000" + "\x0002\x0018\x0002\x0000\x0003\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0002\x0000" + "\x0004\x0018\x0001\x0000\x0003\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0003\x0018\x0001\x0000" + "\x0002\x0018\x0001\x0000\x0004\x0018\x0001\x0000\x0002\x0018\x0002\x0000\x0008\x0018\x0001\x0000" + "\x0002\x0018\x0001\x0000\x0008\x0018\x0001\x0032\x0001\x0000\x0007\x0018\x0001\x0000\x0008\x0018" + "\x0001\x0000\x0006\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0018\x0003\x0000\x0003\x0018\x0012\x0000\x0001\x0018\x0016\x0000\x0002\x0018" + "\x0013\x0000\x0001\x0032\x0001\x0018\x0020\x0000\x0001\x0032\x000B\x0000\x0001\x0018\x0035\x0000" + "\x0001\x0032\x0009\x0000\x0001\x0018\x000D\x0000\x0004\x0018\x0002\x0000\x0002\x0018\x000C\x0000" + "\x0004\x0018\x0001\x0000\x0002\x0018\x0009\x0000\x0003\x0018\x0003\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x0004\x0000\x0003\x0018\x0001\x0000\x0004\x0032\x0001\x0000\x0002\x0018\x0005\x0000" + "\x0004\x0018\x0002\x0000\x0002\x0018\x000A\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0024\x0000" + "\x0001\x0018\x0003\x0000\x0002\x0018\x000A\x0000\x0002\x0018\x0001\x0000\x0003\x0018\x0007\x0000" + "\x0001\x0018\x0006\x0000\x0002\x0018\x0001\x0000\x0002\x0018\x0006\x0000\x0001\x0018\x0004\x0000" + "\x0002\x0018\x0002\x0000\x0002\x0018\x0005\x0000\x0003\x0018\x0002\x0000\x0001\x0018\x0003\x0000" + "\x0002\x0032\x0008\x0000\x0001\x0018\x000E\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0018\x0000" + "\x0001\x0018\x0004\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0006\x0000" + "\x0001\x0018\x0005\x0000\x0001\x0018\x0002\x0000\x0002\x0018\x0001\x0000\x000F\x0018\x0002\x0000" + "\x0001\x0018\x000B\x0000\x0007\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000" + "\x0002\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0003\x0018\x0002\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0001\x0000" + "\x0002\x0018\x0006\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x001B\x0000" + "\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0007\x0000" + "\x0001\x0018\x0019\x0000\x0010\x0018\x0005\x0000\x0003\x0018\x0004\x0000\x0001\x0018\x0006\x0000" + "\x0001\x0018\x0003\x0000\x0002\x0018\x0002\x0000\x0002\x0018\x0004\x0000\x0005\x0018\x0001\x0000" + "\x0001\x0018\x0002\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x005C\x0000\x0002\x0018\x0015\x0000\x0004\x0018\x002D\x0000\x0001\x0018\x000D\x0000" + "\x0002\x0018\x0008\x0000\x0002\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0009\x0000" + "\x0001\x0018\x0009\x0000\x0002\x0018\x0006\x0000\x0001\x0018\x0002\x0000\x0004\x0018\x0003\x0000" + "\x0001\x0018\x0002\x0000\x0002\x0018\x0001\x0000\x0003\x0018\x0001\x0000\x0002\x0018\x0001\x0000" + "\x0001\x0018\x0008\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000\x0002\x0018\x0001\x0000" + "\x0004\x0018\x0013\x0000\x0001\x0018\x0011\x0000\x0001\x0022\x0001\x0000\x0001\x0023\x0002\x0000" + "\x0001\x0078\x0001\x0000\x0001\x0025\x0004\x0000\x0001\x0026\x0001\x0000\x0001\x0027\x0001\x0000" + "\x0001\x0028\x0002\x0000\x0001\x0029\x0003\x0000\x0001\x0079\x0002\x0000\x0001\x007A\x0004\x0000" + "\x0001\x002C\x0003\x0000\x0001\x007B\x000F\x0000\x0001\x002E\x0002\x0000\x0001\x007C\x0011\x0000" + "\x0001\x007D\x0002\x0000\x0001\x007E\x0031\x0000\x0001\x0018\x0002\x0032\x0002\x0000\x0002\x007F" + "\x0001\x0034\x0001\x0000\x0001\x0032\x0002\x0000\x0001\x007F\x0001\x0000\x0001\x001F\x0001\x0018" + "\x0001\x0000\x0001\x0022\x0001\x0000\x0001\x0023\x0002\x0000\x0001\x0080\x0001\x0000\x0001\x0081" + "\x0004\x0000\x0001\x0026\x0001\x0000\x0001\x0027\x0001\x0000\x0001\x0028\x0002\x0000\x0001\x0029" + "\x0003\x0000\x0001\x0082\x0002\x0000\x0001\x0083\x0004\x0000\x0001\x0084\x0003\x0000\x0001\x0085" + "\x000F\x0000\x0001\x002E\x0002\x0000\x0001\x0086\x0011\x0000\x0001\x0087\x0002\x0000\x0001\x0088" + "\x0031\x0000\x0001\x0018\x0001\x0033\x0007\x0000\x0001\x0033\x0004\x0000\x0002\x0018\x0001\x0000" + "\x0001\x0022\x0001\x0000\x0001\x0023\x0002\x0000\x0001\x0089\x0001\x0000\x0001\x0025\x0004\x0000" + "\x0001\x0026\x0001\x0000\x0001\x0027\x0001\x0000\x0001\x0028\x0002\x0000\x0001\x0029\x0003\x0000" + "\x0001\x008A\x0002\x0000\x0001\x008B\x0004\x0000\x0001\x002C\x0003\x0000\x0001\x008C\x000F\x0000" + "\x0001\x002E\x0002\x0000\x0001\x008D\x0011\x0000\x0001\x008E\x0002\x0000\x0001\x008F\x0021\x0000" + "\x0001\x004F\x000F\x0000\x0001\x0018\x0001\x0034\x0001\x0032\x0001\x0051\x0003\x0000\x0001\x0034" + "\x0001\x0000\x0001\x0034\x0004\x0000\x0001\x001F\x0001\x0018\x0007\x0000\x0001\x0018\x0004\x0000" + "\x0001\x0018\x0009\x0000\x0001\x0018\x0012\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x000B\x0000" + "\x0001\x0019\x0002\x0000\x0001\x0019\x0008\x0000\x0001\x0018\x0012\x0000\x0004\x0019\x001D\x0000" + "\x0001\x0018\x0016\x0000\x0001\x0018\x0016\x0000\x0002\x0018\x0013\x0000\x0001\x0019\x0001\x0018" + "\x0020\x0000\x0001\x0019\x000B\x0000\x0001\x0019\x0035\x0000\x0001\x0019\x0009\x0000\x0001\x0019" + "\x000D\x0000\x0004\x0018\x0002\x0000\x0002\x0018\x000C\x0000\x0003\x0018\x0001\x0019\x0001\x0000" + "\x0002\x0019\x0009\x0000\x0003\x0018\x0003\x0000\x0001\x0018\x0001\x0000\x0001\x0019\x0004\x0000" + "\x0001\x0019\x0002\x0018\x0001\x0000\x0004\x0019\x0001\x0000\x0002\x0018\x0005\x0000\x0004\x0019" + "\x0002\x0000\x0001\x0018\x0001\x0019\x000A\x0000\x0001\x0019\x0007\x0000\x0001\x0018\x0018\x0000" + "\x0001\x0018\x0004\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0006\x0000" + "\x0001\x0018\x0005\x0000\x0001\x0018\x0002\x0000\x0002\x0018\x0001\x0000\x000F\x0018\x0002\x0000" + "\x0001\x0018\x000B\x0000\x0007\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000" + "\x0002\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0003\x0018\x0002\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0004\x0000\x0001\x0019\x0001\x0000" + "\x0002\x0018\x0006\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x001B\x0000" + "\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0007\x0000" + "\x0001\x0018\x0019\x0000\x0010\x0018\x0005\x0000\x0003\x0018\x0004\x0000\x0001\x0018\x0006\x0000" + "\x0001\x0018\x0003\x0000\x0002\x0018\x0002\x0000\x0002\x0018\x0004\x0000\x0001\x0018\x0004\x0019" + "\x0001\x0000\x0001\x0018\x0002\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0001\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0018\x005C\x0000\x0002\x0019\x0015\x0000\x0004\x0019\x002D\x0000\x0001\x0019" + "\x000D\x0000\x0002\x0019\x0008\x0000\x0002\x0019\x0001\x0000\x0001\x0019\x0001\x0000\x0001\x0019" + "\x0009\x0000\x0001\x0019\x0009\x0000\x0002\x0019\x0006\x0000\x0001\x0019\x0002\x0000\x0004\x0019" + "\x0003\x0000\x0001\x0019\x0002\x0000\x0002\x0019\x0001\x0000\x0003\x0019\x0001\x0000\x0002\x0019" + "\x0001\x0000\x0001\x0019\x0008\x0000\x0001\x0019\x0001\x0000\x0002\x0019\x0002\x0000\x0002\x0019" + "\x0001\x0000\x0004\x0019\x0013\x0000\x0001\x0019\x0016\x0000\x0001\x0090\x0001\x0000\x0001\x0091" + "\x000F\x0000\x0001\x0092\x0002\x0000\x0001\x0093\x0004\x0000\x0001\x0094\x0003\x0000\x0001\x0095" + "\x0012\x0000\x0001\x0096\x0011\x0000\x0001\x0097\x0002\x0000\x0001\x0098\x0032\x0000\x0001\x003E" + "\x0001\x0019\x0006\x0000\x0001\x003E\x0007\x0000\x0001\x0022\x0001\x0000\x0001\x0023\x0002\x0000" + "\x0001\x0099\x0001\x0000\x0001\x0036\x0004\x0000\x0001\x0026\x0001\x0000\x0001\x0027\x0001\x0000" + "\x0001\x0028\x0002\x0000\x0001\x0029\x0003\x0000\x0001\x009A\x0002\x0000\x0001\x009B\x0004\x0000" + "\x0001\x0039\x0003\x0000\x0001\x009C\x000F\x0000\x0001\x002E\x0002\x0000\x0001\x009D\x0011\x0000" + "\x0001\x009E\x0002\x0000\x0001\x009F\x0021\x0000\x0001\x004F\x000F\x0000\x0001\x0018\x0001\x003F" + "\x0001\x0019\x0001\x0051\x0003\x0000\x0001\x003F\x0001\x0000\x0001\x003F\x0004\x0000\x0001\x001F" + "\x0001\x0018\x0039\x0000\x0001\x001A\x0002\x0000\x0001\x001A\x001B\x0000\x0004\x001A\x008E\x0000" + "\x0001\x001A\x003F\x0000\x0001\x001A\x0024\x0000\x0001\x001A\x0001\x0000\x0002\x001A\x0011\x0000" + "\x0001\x001A\x0004\x0000\x0001\x001A\x000F\x0000\x0004\x001A\x0003\x0000\x0001\x001A\x000A\x0000" + "\x0001\x001A\x0083\x0000\x0001\x001A\x0092\x0000\x0004\x001A\x006A\x0000\x0002\x001A\x0015\x0000" + "\x0004\x001A\x002D\x0000\x0001\x001A\x000D\x0000\x0002\x001A\x0008\x0000\x0002\x001A\x0001\x0000" + "\x0001\x001A\x0001\x0000\x0001\x001A\x0009\x0000\x0001\x001A\x0009\x0000\x0002\x001A\x0006\x0000" + "\x0001\x001A\x0002\x0000\x0004\x001A\x0003\x0000\x0001\x001A\x0002\x0000\x0002\x001A\x0001\x0000" + "\x0003\x001A\x0001\x0000\x0002\x001A\x0001\x0000\x0001\x001A\x0008\x0000\x0001\x001A\x0001\x0000" + "\x0002\x001A\x0002\x0000\x0002\x001A\x0001\x0000\x0004\x001A\x0013\x0000\x0001\x001A\x007F\x0000" + "\x0001\x001A\x0025\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0009\x0000\x0001\x0018\x0012\x0000" + "\x0001\x0018\x0003\x0000\x0001\x0018\x000B\x0000\x0001\x0050\x0002\x0000\x0001\x0050\x0008\x0000" + "\x0001\x0018\x0012\x0000\x0004\x0050\x001D\x0000\x0001\x0018\x0016\x0000\x0001\x0018\x0016\x0000" + "\x0002\x0018\x0013\x0000\x0001\x0019\x0001\x0018\x0020\x0000\x0001\x0019\x000B\x0000\x0001\x0050" + "\x0035\x0000\x0001\x0019\x0009\x0000\x0001\x0050\x000D\x0000\x0004\x0018\x0002\x0000\x0002\x0018" + "\x000C\x0000\x0003\x0018\x0001\x0050\x0001\x0000\x0002\x0050\x0009\x0000\x0003\x0018\x0003\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0050\x0004\x0000\x0001\x0050\x0002\x0018\x0001\x0000\x0004\x0019" + "\x0001\x0000\x0002\x0018\x0005\x0000\x0004\x0050\x0002\x0000\x0001\x0018\x0001\x0050\x000A\x0000" + "\x0001\x0050\x0007\x0000\x0001\x0018\x0018\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0006\x0000" + "\x0001\x0018\x0003\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0005\x0000\x0001\x0018\x0002\x0000" + "\x0002\x0018\x0001\x0000\x000F\x0018\x0002\x0000\x0001\x0018\x000B\x0000\x0007\x0018\x0002\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000\x0001\x0018\x0001\x0000" + "\x0003\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x0004\x0000\x0001\x0050\x0001\x0000\x0002\x0018\x0006\x0000\x0001\x0018\x0007\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0018\x001B\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000" + "\x0001\x0018\x0003\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0019\x0000\x0010\x0018\x0005\x0000" + "\x0003\x0018\x0004\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0002\x0018\x0002\x0000" + "\x0002\x0018\x0004\x0000\x0001\x0018\x0004\x0050\x0001\x0000\x0001\x0018\x0002\x0000\x0001\x0018" + "\x0004\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x005C\x0000\x0002\x0050" + "\x0015\x0000\x0004\x0050\x002D\x0000\x0001\x0050\x000D\x0000\x0002\x0050\x0008\x0000\x0002\x0050" + "\x0001\x0000\x0001\x0050\x0001\x0000\x0001\x0050\x0009\x0000\x0001\x0050\x0009\x0000\x0002\x0050" + "\x0006\x0000\x0001\x0050\x0002\x0000\x0004\x0050\x0003\x0000\x0001\x0050\x0002\x0000\x0002\x0050" + "\x0001\x0000\x0003\x0050\x0001\x0000\x0002\x0050\x0001\x0000\x0001\x0050\x0008\x0000\x0001\x0050" + "\x0001\x0000\x0002\x0050\x0002\x0000\x0002\x0050\x0001\x0000\x0004\x0050\x0013\x0000\x0001\x0050" + "\x007F\x0000\x0001\x0051\x0024\x0000\x0001\x00A0\x0011\x0000\x0001\x00A1\x0002\x0000\x0001\x00A2" + "\x0008\x0000\x0001\x00A3\x0012\x0000\x0001\x00A4\x0011\x0000\x0001\x00A5\x0002\x0000\x0001\x00A6" + "\x0021\x0000\x0001\x004F\x0010\x0000\x0001\x0051\x0001\x0000\x0001\x0051\x0003\x0000\x0001\x0034" + "\x0001\x0000\x0001\x0051\x003F\x0000\x0001\x001D\x0002\x0000\x0001\x001D\x001B\x0000\x0004\x001D" + "\x008E\x0000\x0001\x001D\x003F\x0000\x0001\x001D\x0024\x0000\x0001\x001D\x0001\x0000\x0002\x001D" + "\x0011\x0000\x0001\x001D\x0004\x0000\x0001\x001D\x000F\x0000\x0004\x001D\x0003\x0000\x0001\x001D" + "\x000A\x0000\x0001\x001D\x0083\x0000\x0001\x001D\x0092\x0000\x0004\x001D\x006A\x0000\x0002\x001D" + "\x0015\x0000\x0004\x001D\x002D\x0000\x0001\x001D\x000D\x0000\x0002\x001D\x0008\x0000\x0002\x001D" + "\x0001\x0000\x0001\x001D\x0001\x0000\x0001\x001D\x0009\x0000\x0001\x001D\x0009\x0000\x0002\x001D" + "\x0006\x0000\x0001\x001D\x0002\x0000\x0004\x001D\x0003\x0000\x0001\x001D\x0002\x0000\x0002\x001D" + "\x0001\x0000\x0003\x001D\x0001\x0000\x0002\x001D\x0001\x0000\x0001\x001D\x0008\x0000\x0001\x001D" + "\x0001\x0000\x0002\x001D\x0002\x0000\x0002\x001D\x0001\x0000\x0004\x001D\x0013\x0000\x0001\x001D" + "\x0049\x0000\x0001\x001E\x0002\x0000\x0001\x001E\x001B\x0000\x0004\x001E\x008E\x0000\x0001\x001E" + "\x003F\x0000\x0001\x001E\x0024\x0000\x0001\x001E\x0001\x0000\x0002\x001E\x0011\x0000\x0001\x001E" + "\x0004\x0000\x0001\x001E\x000F\x0000\x0004\x001E\x0003\x0000\x0001\x001E\x000A\x0000\x0001\x001E" + "\x0083\x0000\x0001\x001E\x0092\x0000\x0004\x001E\x006A\x0000\x0002\x001E\x0015\x0000\x0004\x001E" + "\x002D\x0000\x0001\x001E\x000D\x0000\x0002\x001E\x0008\x0000\x0002\x001E\x0001\x0000\x0001\x001E" + "\x0001\x0000\x0001\x001E\x0009\x0000\x0001\x001E\x0009\x0000\x0002\x001E\x0006\x0000\x0001\x001E" + "\x0002\x0000\x0004\x001E\x0003\x0000\x0001\x001E\x0002\x0000\x0002\x001E\x0001\x0000\x0003\x001E" + "\x0001\x0000\x0002\x001E\x0001\x0000\x0001\x001E\x0008\x0000\x0001\x001E\x0001\x0000\x0002\x001E" + "\x0002\x0000\x0002\x001E\x0001\x0000\x0004\x001E\x0013\x0000\x0001\x001E\x0017\x0000\x0001\x0018" + "\x0004\x0000\x0001\x0018\x0009\x0000\x0001\x0018\x0012\x0000\x0001\x0018\x0003\x0000\x0001\x0018" + "\x000B\x0000\x0001\x001F\x0002\x0000\x0001\x001F\x0008\x0000\x0001\x0018\x0012\x0000\x0004\x001F" + "\x001D\x0000\x0001\x0018\x0016\x0000\x0001\x0018\x0016\x0000\x0002\x0018\x0013\x0000\x0001\x0032" + "\x0001\x0018\x0020\x0000\x0001\x0032\x000B\x0000\x0001\x001F\x0035\x0000\x0001\x0032\x0009\x0000" + "\x0001\x001F\x000D\x0000\x0004\x0018\x0002\x0000\x0002\x0018\x000C\x0000\x0003\x0018\x0001\x001F" + "\x0001\x0000\x0002\x001F\x0009\x0000\x0003\x0018\x0003\x0000\x0001\x0018\x0001\x0000\x0001\x001F" + "\x0004\x0000\x0001\x001F\x0002\x0018\x0001\x0000\x0004\x0032\x0001\x0000\x0002\x0018\x0005\x0000" + "\x0004\x001F\x0002\x0000\x0001\x0018\x0001\x001F\x000A\x0000\x0001\x001F\x0007\x0000\x0001\x0018" + "\x0018\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018" + "\x0006\x0000\x0001\x0018\x0005\x0000\x0001\x0018\x0002\x0000\x0002\x0018\x0001\x0000\x000F\x0018" + "\x0002\x0000\x0001\x0018\x000B\x0000\x0007\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0001\x0018" + "\x0001\x0000\x0002\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0003\x0018\x0002\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0004\x0000\x0001\x001F" + "\x0001\x0000\x0002\x0018\x0006\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0001\x0000\x0001\x0018" + "\x001B\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0003\x0000\x0001\x0018" + "\x0007\x0000\x0001\x0018\x0019\x0000\x0010\x0018\x0005\x0000\x0003\x0018\x0004\x0000\x0001\x0018" + "\x0006\x0000\x0001\x0018\x0003\x0000\x0002\x0018\x0002\x0000\x0002\x0018\x0004\x0000\x0001\x0018" + "\x0004\x001F\x0001\x0000\x0001\x0018\x0002\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0018\x005C\x0000\x0002\x001F\x0015\x0000\x0004\x001F\x002D\x0000" + "\x0001\x001F\x000D\x0000\x0002\x001F\x0008\x0000\x0002\x001F\x0001\x0000\x0001\x001F\x0001\x0000" + "\x0001\x001F\x0009\x0000\x0001\x001F\x0009\x0000\x0002\x001F\x0006\x0000\x0001\x001F\x0002\x0000" + "\x0004\x001F\x0003\x0000\x0001\x001F\x0002\x0000\x0002\x001F\x0001\x0000\x0003\x001F\x0001\x0000" + "\x0002\x001F\x0001\x0000\x0001\x001F\x0008\x0000\x0001\x001F\x0001\x0000\x0002\x001F\x0002\x0000" + "\x0002\x001F\x0001\x0000\x0004\x001F\x0013\x0000\x0001\x001F\x0011\x0000\x0001\x0022\x0001\x0000" + "\x0001\x0023\x0002\x0000\x0001\x00A7\x0001\x0000\x0001\x0025\x0004\x0000\x0001\x0026\x0001\x0000" + "\x0001\x0027\x0001\x0000\x0001\x0028\x0002\x0000\x0001\x0029\x0003\x0000\x0001\x00A8\x0002\x0000" + "\x0001\x00A9\x0004\x0000\x0001\x002C\x0003\x0000\x0001\x00AA\x000F\x0000\x0001\x002E\x0002\x0000" + "\x0001\x00AB\x0011\x0000\x0001\x00AC\x0002\x0000\x0001\x00AD\x0031\x0000\x0001\x0018\x0001\x0067" + "\x0001\x0032\x0004\x0000\x0001\x0034\x0001\x0000\x0001\x0067\x0004\x0000\x0001\x001F\x0001\x0018" + "\x0006\x0000\x0001\x00AE\x0011\x0000\x0001\x00AF\x0002\x0000\x0001\x00B0\x0008\x0000\x0001\x00B1" + "\x0012\x0000\x0001\x00B2\x0011\x0000\x0001\x00B3\x0002\x0000\x0001\x00B4\x0032\x0000\x0001\x0068" + "\x0007\x0000\x0001\x0068\x0004\x0000\x0001\x0067\x0008\x0000\x0001\x0018\x0004\x0000\x0001\x0018" + "\x0009\x0000\x0001\x0018\x0012\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x000B\x0000\x0001\x0020" + "\x0002\x0000\x0001\x0020\x0008\x0000\x0001\x0018\x0012\x0000\x0004\x0020\x001D\x0000\x0001\x0018" + "\x0016\x0000\x0001\x0018\x0016\x0000\x0002\x0018\x0013\x0000\x0001\x0032\x0001\x0018\x0020\x0000" + "\x0001\x0032\x000B\x0000\x0001\x0020\x0035\x0000\x0001\x0032\x0009\x0000\x0001\x0020\x000D\x0000" + "\x0004\x0018\x0002\x0000\x0002\x0018\x000C\x0000\x0003\x0018\x0001\x0020\x0001\x0000\x0002\x0020" + "\x0009\x0000\x0003\x0018\x0003\x0000\x0001\x0018\x0001\x0000\x0001\x0020\x0004\x0000\x0001\x0020" + "\x0002\x0018\x0001\x0000\x0004\x0032\x0001\x0000\x0002\x0018\x0005\x0000\x0004\x0020\x0002\x0000" + "\x0001\x0018\x0001\x0020\x000A\x0000\x0001\x0020\x0007\x0000\x0001\x0018\x0018\x0000\x0001\x0018" + "\x0004\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0006\x0000\x0001\x0018" + "\x0005\x0000\x0001\x0018\x0002\x0000\x0002\x0018\x0001\x0000\x000F\x0018\x0002\x0000\x0001\x0018" + "\x000B\x0000\x0007\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0002\x0018" + "\x0002\x0000\x0001\x0018\x0001\x0000\x0003\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0004\x0000\x0001\x0020\x0001\x0000\x0002\x0018" + "\x0006\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x001B\x0000\x0001\x0018" + "\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0007\x0000\x0001\x0018" + "\x0019\x0000\x0010\x0018\x0005\x0000\x0003\x0018\x0004\x0000\x0001\x0018\x0006\x0000\x0001\x0018" + "\x0003\x0000\x0002\x0018\x0002\x0000\x0002\x0018\x0004\x0000\x0001\x0018\x0004\x0020\x0001\x0000" + "\x0001\x0018\x0002\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x005C\x0000\x0002\x0020\x0015\x0000\x0004\x0020\x002D\x0000\x0001\x0020\x000D\x0000" + "\x0002\x0020\x0008\x0000\x0002\x0020\x0001\x0000\x0001\x0020\x0001\x0000\x0001\x0020\x0009\x0000" + "\x0001\x0020\x0009\x0000\x0002\x0020\x0006\x0000\x0001\x0020\x0002\x0000\x0004\x0020\x0003\x0000" + "\x0001\x0020\x0002\x0000\x0002\x0020\x0001\x0000\x0003\x0020\x0001\x0000\x0002\x0020\x0001\x0000" + "\x0001\x0020\x0008\x0000\x0001\x0020\x0001\x0000\x0002\x0020\x0002\x0000\x0002\x0020\x0001\x0000" + "\x0004\x0020\x0013\x0000\x0001\x0020\x0049\x0000\x0001\x0021\x0002\x0000\x0001\x0021\x001B\x0000" + "\x0004\x0021\x008E\x0000\x0001\x0021\x003F\x0000\x0001\x0021\x0024\x0000\x0001\x0021\x0001\x0000" + "\x0002\x0021\x0011\x0000\x0001\x0021\x0004\x0000\x0001\x0021\x000F\x0000\x0004\x0021\x0003\x0000" + "\x0001\x0021\x000A\x0000\x0001\x0021\x0083\x0000\x0001\x0021\x0092\x0000\x0004\x0021\x006A\x0000" + "\x0002\x0021\x0015\x0000\x0004\x0021\x002D\x0000\x0001\x0021\x000D\x0000\x0002\x0021\x0008\x0000" + "\x0002\x0021\x0001\x0000\x0001\x0021\x0001\x0000\x0001\x0021\x0009\x0000\x0001\x0021\x0009\x0000" + "\x0002\x0021\x0006\x0000\x0001\x0021\x0002\x0000\x0004\x0021\x0003\x0000\x0001\x0021\x0002\x0000" + "\x0002\x0021\x0001\x0000\x0003\x0021\x0001\x0000\x0002\x0021\x0001\x0000\x0001\x0021\x0008\x0000" + "\x0001\x0021\x0001\x0000\x0002\x0021\x0002\x0000\x0002\x0021\x0001\x0000\x0004\x0021\x0013\x0000" + "\x0001\x0021\x0075\x0000\x0001\x00B5\x0016\x0000\x0002\x00B5\x0017\x0000\x0001\x0018\x0004\x0000" + "\x0001\x0018\x0009\x0000\x0001\x0018\x0012\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x000B\x0000" + "\x0001\x0032\x0002\x0000\x0001\x0032\x0008\x0000\x0001\x0018\x0012\x0000\x0004\x0032\x001D\x0000" + "\x0001\x0018\x0016\x0000\x0001\x0018\x0016\x0000\x0002\x0018\x0013\x0000\x0001\x0032\x0001\x0018" + "\x0020\x0000\x0001\x0032\x000B\x0000\x0001\x0032\x0035\x0000\x0001\x0032\x0009\x0000\x0001\x0032" + "\x000D\x0000\x0004\x0018\x0002\x0000\x0002\x0018\x000C\x0000\x0003\x0018\x0001\x0032\x0001\x0000" + "\x0002\x0032\x0009\x0000\x0003\x0018\x0003\x0000\x0001\x0018\x0001\x0000\x0001\x0032\x0004\x0000" + "\x0001\x0032\x0002\x0018\x0001\x0000\x0004\x0032\x0001\x0000\x0002\x0018\x0005\x0000\x0004\x0032" + "\x0002\x0000\x0001\x0018\x0001\x0032\x000A\x0000\x0001\x0032\x0007\x0000\x0001\x0018\x0018\x0000" + "\x0001\x0018\x0004\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0006\x0000" + "\x0001\x0018\x0005\x0000\x0001\x0018\x0002\x0000\x0002\x0018\x0001\x0000\x000F\x0018\x0002\x0000" + "\x0001\x0018\x000B\x0000\x0007\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000" + "\x0002\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0003\x0018\x0002\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0004\x0000\x0001\x0032\x0001\x0000" + "\x0002\x0018\x0006\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x001B\x0000" + "\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0007\x0000" + "\x0001\x0018\x0019\x0000\x0010\x0018\x0005\x0000\x0003\x0018\x0004\x0000\x0001\x0018\x0006\x0000" + "\x0001\x0018\x0003\x0000\x0002\x0018\x0002\x0000\x0002\x0018\x0004\x0000\x0001\x0018\x0004\x0032" + "\x0001\x0000\x0001\x0018\x0002\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0001\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0018\x005C\x0000\x0002\x0032\x0015\x0000\x0004\x0032\x002D\x0000\x0001\x0032" + "\x000D\x0000\x0002\x0032\x0008\x0000\x0002\x0032\x0001\x0000\x0001\x0032\x0001\x0000\x0001\x0032" + "\x0009\x0000\x0001\x0032\x0009\x0000\x0002\x0032\x0006\x0000\x0001\x0032\x0002\x0000\x0004\x0032" + "\x0003\x0000\x0001\x0032\x0002\x0000\x0002\x0032\x0001\x0000\x0003\x0032\x0001\x0000\x0002\x0032" + "\x0001\x0000\x0001\x0032\x0008\x0000\x0001\x0032\x0001\x0000\x0002\x0032\x0002\x0000\x0002\x0032" + "\x0001\x0000\x0004\x0032\x0013\x0000\x0001\x0032\x0016\x0000\x0001\x00B6\x0001\x0000\x0001\x00B7" + "\x000F\x0000\x0001\x00B8\x0002\x0000\x0001\x00B9\x0004\x0000\x0001\x00BA\x0003\x0000\x0001\x00BB" + "\x0012\x0000\x0001\x00BC\x0011\x0000\x0001\x00BD\x0002\x0000\x0001\x00BE\x0032\x0000\x0001\x007F" + "\x0001\x0032\x0006\x0000\x0001\x007F\x000D\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0009\x0000" + "\x0001\x0018\x0012\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x000B\x0000\x0001\x0033\x0002\x0000" + "\x0001\x0033\x0008\x0000\x0001\x0018\x0012\x0000\x0004\x0033\x001D\x0000\x0001\x0018\x0019\x0000" + "\x0001\x0018\x0003\x0000\x0004\x0018\x0001\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0001\x0000" + "\x0002\x0018\x0002\x0000\x0002\x0018\x0002\x0000\x0003\x0018\x0001\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x0002\x0000\x0004\x0018\x0001\x0000\x0003\x0018\x0001\x0000\x0001\x0018\x0001\x0000" + "\x0003\x0018\x0001\x0000\x0002\x0018\x0001\x0000\x0004\x0018\x0001\x0000\x0002\x0018\x0002\x0000" + "\x0008\x0018\x0001\x0000\x0002\x0018\x0001\x0000\x0008\x0018\x0002\x0000\x0007\x0018\x0001\x0000" + "\x0008\x0018\x0001\x0000\x0006\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0018\x0003\x0000\x0003\x0018\x0012\x0000\x0001\x0018\x0016\x0000" + "\x0002\x0018\x0014\x0000\x0001\x0018\x002C\x0000\x0001\x0033\x003F\x0000\x0001\x0033\x000D\x0000" + "\x0004\x0018\x0002\x0000\x0002\x0018\x000C\x0000\x0003\x0018\x0001\x0033\x0001\x0000\x0002\x0033" + "\x0009\x0000\x0003\x0018\x0003\x0000\x0001\x0018\x0001\x0000\x0001\x0033\x0004\x0000\x0001\x0033" + "\x0002\x0018\x0006\x0000\x0002\x0018\x0005\x0000\x0004\x0033\x0002\x0000\x0001\x0018\x0001\x0033" + "\x000A\x0000\x0001\x0033\x0007\x0000\x0001\x0018\x0024\x0000\x0001\x0018\x0003\x0000\x0002\x0018" + "\x000A\x0000\x0002\x0018\x0001\x0000\x0003\x0018\x0007\x0000\x0001\x0018\x0006\x0000\x0002\x0018" + "\x0001\x0000\x0002\x0018\x0006\x0000\x0001\x0018\x0004\x0000\x0002\x0018\x0002\x0000\x0002\x0018" + "\x0005\x0000\x0003\x0018\x0002\x0000\x0001\x0018\x000D\x0000\x0001\x0018\x000E\x0000\x0001\x0018" + "\x0007\x0000\x0001\x0018\x0018\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0006\x0000\x0001\x0018" + "\x0003\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0005\x0000\x0001\x0018\x0002\x0000\x0002\x0018" + "\x0001\x0000\x000F\x0018\x0002\x0000\x0001\x0018\x000B\x0000\x0007\x0018\x0002\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0003\x0018" + "\x0002\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018" + "\x0004\x0000\x0001\x0033\x0001\x0000\x0002\x0018\x0006\x0000\x0001\x0018\x0007\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0018\x001B\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018" + "\x0003\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0019\x0000\x0010\x0018\x0005\x0000\x0003\x0018" + "\x0004\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0002\x0018\x0002\x0000\x0002\x0018" + "\x0004\x0000\x0001\x0018\x0004\x0033\x0001\x0000\x0001\x0018\x0002\x0000\x0001\x0018\x0004\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x005C\x0000\x0002\x0033\x0015\x0000" + "\x0004\x0033\x002D\x0000\x0001\x0033\x000D\x0000\x0002\x0033\x0008\x0000\x0002\x0033\x0001\x0000" + "\x0001\x0033\x0001\x0000\x0001\x0033\x0009\x0000\x0001\x0033\x0009\x0000\x0002\x0033\x0006\x0000" + "\x0001\x0033\x0002\x0000\x0004\x0033\x0003\x0000\x0001\x0033\x0002\x0000\x0002\x0033\x0001\x0000" + "\x0003\x0033\x0001\x0000\x0002\x0033\x0001\x0000\x0001\x0033\x0008\x0000\x0001\x0033\x0001\x0000" + "\x0002\x0033\x0002\x0000\x0002\x0033\x0001\x0000\x0004\x0033\x0013\x0000\x0001\x0033\x0017\x0000" + "\x0001\x0018\x0004\x0000\x0001\x0018\x0009\x0000\x0001\x0018\x0012\x0000\x0001\x0018\x0003\x0000" + "\x0001\x0018\x000B\x0000\x0001\x0034\x0002\x0000\x0001\x0034\x0008\x0000\x0001\x0018\x0012\x0000" + "\x0004\x0034\x001D\x0000\x0001\x0018\x0016\x0000\x0001\x0018\x0016\x0000\x0002\x0018\x0013\x0000" + "\x0001\x0032\x0001\x0018\x0020\x0000\x0001\x0032\x000B\x0000\x0001\x0034\x0035\x0000\x0001\x0032" + "\x0009\x0000\x0001\x0034\x000D\x0000\x0004\x0018\x0002\x0000\x0002\x0018\x000C\x0000\x0003\x0018" + "\x0001\x0034\x0001\x0000\x0002\x0034\x0009\x0000\x0003\x0018\x0003\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0034\x0004\x0000\x0001\x0034\x0002\x0018\x0001\x0000\x0004\x0032\x0001\x0000\x0002\x0018" + "\x0005\x0000\x0004\x0034\x0002\x0000\x0001\x0018\x0001\x0034\x000A\x0000\x0001\x0034\x0007\x0000" + "\x0001\x0018\x0018\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000" + "\x0001\x0018\x0006\x0000\x0001\x0018\x0005\x0000\x0001\x0018\x0002\x0000\x0002\x0018\x0001\x0000" + "\x000F\x0018\x0002\x0000\x0001\x0018\x000B\x0000\x0007\x0018\x0002\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0003\x0018\x0002\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0004\x0000" + "\x0001\x0034\x0001\x0000\x0002\x0018\x0006\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x001B\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0003\x0000" + "\x0001\x0018\x0007\x0000\x0001\x0018\x0019\x0000\x0010\x0018\x0005\x0000\x0003\x0018\x0004\x0000" + "\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0002\x0018\x0002\x0000\x0002\x0018\x0004\x0000" + "\x0001\x0018\x0004\x0034\x0001\x0000\x0001\x0018\x0002\x0000\x0001\x0018\x0004\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x005C\x0000\x0002\x0034\x0015\x0000\x0004\x0034" + "\x002D\x0000\x0001\x0034\x000D\x0000\x0002\x0034\x0008\x0000\x0002\x0034\x0001\x0000\x0001\x0034" + "\x0001\x0000\x0001\x0034\x0009\x0000\x0001\x0034\x0009\x0000\x0002\x0034\x0006\x0000\x0001\x0034" + "\x0002\x0000\x0004\x0034\x0003\x0000\x0001\x0034\x0002\x0000\x0002\x0034\x0001\x0000\x0003\x0034" + "\x0001\x0000\x0002\x0034\x0001\x0000\x0001\x0034\x0008\x0000\x0001\x0034\x0001\x0000\x0002\x0034" + "\x0002\x0000\x0002\x0034\x0001\x0000\x0004\x0034\x0013\x0000\x0001\x0034\x0049\x0000\x0001\x003E" + "\x0002\x0000\x0001\x003E\x001B\x0000\x0004\x003E\x0042\x0000\x0001\x0019\x0044\x0000\x0001\x0019" + "\x0066\x0000\x0001\x0019\x0021\x0000\x0001\x0019\x000B\x0000\x0001\x003E\x0035\x0000\x0001\x0019" + "\x0009\x0000\x0001\x003E\x0024\x0000\x0001\x003E\x0001\x0000\x0002\x003E\x0011\x0000\x0001\x003E" + "\x0004\x0000\x0001\x003E\x0003\x0000\x0004\x0019\x0008\x0000\x0004\x003E\x0003\x0000\x0001\x003E" + "\x000A\x0000\x0001\x003E\x0074\x0000\x0002\x0019\x009B\x0000\x0001\x003E\x0092\x0000\x0004\x003E" + "\x006A\x0000\x0002\x003E\x0015\x0000\x0004\x003E\x002D\x0000\x0001\x003E\x000D\x0000\x0002\x003E" + "\x0008\x0000\x0002\x003E\x0001\x0000\x0001\x003E\x0001\x0000\x0001\x003E\x0009\x0000\x0001\x003E" + "\x0009\x0000\x0002\x003E\x0006\x0000\x0001\x003E\x0002\x0000\x0004\x003E\x0003\x0000\x0001\x003E" + "\x0002\x0000\x0002\x003E\x0001\x0000\x0003\x003E\x0001\x0000\x0002\x003E\x0001\x0000\x0001\x003E" + "\x0008\x0000\x0001\x003E\x0001\x0000\x0002\x003E\x0002\x0000\x0002\x003E\x0001\x0000\x0004\x003E" + "\x0013\x0000\x0001\x003E\x0017\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0009\x0000\x0001\x0018" + "\x0012\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x000B\x0000\x0001\x003F\x0002\x0000\x0001\x003F" + "\x0008\x0000\x0001\x0018\x0012\x0000\x0004\x003F\x001D\x0000\x0001\x0018\x0016\x0000\x0001\x0018" + "\x0016\x0000\x0002\x0018\x0013\x0000\x0001\x0019\x0001\x0018\x0020\x0000\x0001\x0019\x000B\x0000" + "\x0001\x003F\x0035\x0000\x0001\x0019\x0009\x0000\x0001\x003F\x000D\x0000\x0004\x0018\x0002\x0000" + "\x0002\x0018\x000C\x0000\x0003\x0018\x0001\x003F\x0001\x0000\x0002\x003F\x0009\x0000\x0003\x0018" + "\x0003\x0000\x0001\x0018\x0001\x0000\x0001\x003F\x0004\x0000\x0001\x003F\x0002\x0018\x0001\x0000" + "\x0004\x0019\x0001\x0000\x0002\x0018\x0005\x0000\x0004\x003F\x0002\x0000\x0001\x0018\x0001\x003F" + "\x000A\x0000\x0001\x003F\x0007\x0000\x0001\x0018\x0018\x0000\x0001\x0018\x0004\x0000\x0001\x0018" + "\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0005\x0000\x0001\x0018" + "\x0002\x0000\x0002\x0018\x0001\x0000\x000F\x0018\x0002\x0000\x0001\x0018\x000B\x0000\x0007\x0018" + "\x0002\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000\x0001\x0018" + "\x0001\x0000\x0003\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0018\x0004\x0000\x0001\x003F\x0001\x0000\x0002\x0018\x0006\x0000\x0001\x0018" + "\x0007\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x001B\x0000\x0001\x0018\x0006\x0000\x0001\x0018" + "\x0003\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0019\x0000\x0010\x0018" + "\x0005\x0000\x0003\x0018\x0004\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0002\x0018" + "\x0002\x0000\x0002\x0018\x0004\x0000\x0001\x0018\x0004\x003F\x0001\x0000\x0001\x0018\x0002\x0000" + "\x0001\x0018\x0004\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x005C\x0000" + "\x0002\x003F\x0015\x0000\x0004\x003F\x002D\x0000\x0001\x003F\x000D\x0000\x0002\x003F\x0008\x0000" + "\x0002\x003F\x0001\x0000\x0001\x003F\x0001\x0000\x0001\x003F\x0009\x0000\x0001\x003F\x0009\x0000" + "\x0002\x003F\x0006\x0000\x0001\x003F\x0002\x0000\x0004\x003F\x0003\x0000\x0001\x003F\x0002\x0000" + "\x0002\x003F\x0001\x0000\x0003\x003F\x0001\x0000\x0002\x003F\x0001\x0000\x0001\x003F\x0008\x0000" + "\x0001\x003F\x0001\x0000\x0002\x003F\x0002\x0000\x0002\x003F\x0001\x0000\x0004\x003F\x0013\x0000" + "\x0001\x003F\x0049\x0000\x0001\x0051\x0002\x0000\x0001\x0051\x001B\x0000\x0004\x0051\x008E\x0000" + "\x0001\x0051\x003F\x0000\x0001\x0051\x0024\x0000\x0001\x0051\x0001\x0000\x0002\x0051\x0011\x0000" + "\x0001\x0051\x0004\x0000\x0001\x0051\x000F\x0000\x0004\x0051\x0003\x0000\x0001\x0051\x000A\x0000" + "\x0001\x0051\x0083\x0000\x0001\x0051\x0092\x0000\x0004\x0051\x006A\x0000\x0002\x0051\x0015\x0000" + "\x0004\x0051\x002D\x0000\x0001\x0051\x000D\x0000\x0002\x0051\x0008\x0000\x0002\x0051\x0001\x0000" + "\x0001\x0051\x0001\x0000\x0001\x0051\x0009\x0000\x0001\x0051\x0009\x0000\x0002\x0051\x0006\x0000" + "\x0001\x0051\x0002\x0000\x0004\x0051\x0003\x0000\x0001\x0051\x0002\x0000\x0002\x0051\x0001\x0000" + "\x0003\x0051\x0001\x0000\x0002\x0051\x0001\x0000\x0001\x0051\x0008\x0000\x0001\x0051\x0001\x0000" + "\x0002\x0051\x0002\x0000\x0002\x0051\x0001\x0000\x0004\x0051\x0013\x0000\x0001\x0051\x0017\x0000" + "\x0001\x0018\x0004\x0000\x0001\x0018\x0009\x0000\x0001\x0018\x0012\x0000\x0001\x0018\x0003\x0000" + "\x0001\x0018\x000B\x0000\x0001\x0067\x0002\x0000\x0001\x0067\x0008\x0000\x0001\x0018\x0012\x0000" + "\x0004\x0067\x001D\x0000\x0001\x0018\x0016\x0000\x0001\x0018\x0016\x0000\x0002\x0018\x0013\x0000" + "\x0001\x0032\x0001\x0018\x0020\x0000\x0001\x0032\x000B\x0000\x0001\x0067\x0035\x0000\x0001\x0032" + "\x0009\x0000\x0001\x0067\x000D\x0000\x0004\x0018\x0002\x0000\x0002\x0018\x000C\x0000\x0003\x0018" + "\x0001\x0067\x0001\x0000\x0002\x0067\x0009\x0000\x0003\x0018\x0003\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0067\x0004\x0000\x0001\x0067\x0002\x0018\x0001\x0000\x0004\x0032\x0001\x0000\x0002\x0018" + "\x0005\x0000\x0004\x0067\x0002\x0000\x0001\x0018\x0001\x0067\x000A\x0000\x0001\x0067\x0007\x0000" + "\x0001\x0018\x0018\x0000\x0001\x0018\x0004\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000" + "\x0001\x0018\x0006\x0000\x0001\x0018\x0005\x0000\x0001\x0018\x0002\x0000\x0002\x0018\x0001\x0000" + "\x000F\x0018\x0002\x0000\x0001\x0018\x000B\x0000\x0007\x0018\x0002\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x0001\x0000\x0002\x0018\x0002\x0000\x0001\x0018\x0001\x0000\x0003\x0018\x0002\x0000" + "\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x0004\x0000" + "\x0001\x0067\x0001\x0000\x0002\x0018\x0006\x0000\x0001\x0018\x0007\x0000\x0001\x0018\x0001\x0000" + "\x0001\x0018\x001B\x0000\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0001\x0018\x0003\x0000" + "\x0001\x0018\x0007\x0000\x0001\x0018\x0019\x0000\x0010\x0018\x0005\x0000\x0003\x0018\x0004\x0000" + "\x0001\x0018\x0006\x0000\x0001\x0018\x0003\x0000\x0002\x0018\x0002\x0000\x0002\x0018\x0004\x0000" + "\x0001\x0018\x0004\x0067\x0001\x0000\x0001\x0018\x0002\x0000\x0001\x0018\x0004\x0000\x0001\x0018" + "\x0001\x0000\x0001\x0018\x0001\x0000\x0001\x0018\x005C\x0000\x0002\x0067\x0015\x0000\x0004\x0067" + "\x002D\x0000\x0001\x0067\x000D\x0000\x0002\x0067\x0008\x0000\x0002\x0067\x0001\x0000\x0001\x0067" + "\x0001\x0000\x0001\x0067\x0009\x0000\x0001\x0067\x0009\x0000\x0002\x0067\x0006\x0000\x0001\x0067" + "\x0002\x0000\x0004\x0067\x0003\x0000\x0001\x0067\x0002\x0000\x0002\x0067\x0001\x0000\x0003\x0067" + "\x0001\x0000\x0002\x0067\x0001\x0000\x0001\x0067\x0008\x0000\x0001\x0067\x0001\x0000\x0002\x0067" + "\x0002\x0000\x0002\x0067\x0001\x0000\x0004\x0067\x0013\x0000\x0001\x0067\x0049\x0000\x0001\x0068" + "\x0002\x0000\x0001\x0068\x001B\x0000\x0004\x0068\x008E\x0000\x0001\x0068\x003F\x0000\x0001\x0068" + "\x0024\x0000\x0001\x0068\x0001\x0000\x0002\x0068\x0011\x0000\x0001\x0068\x0004\x0000\x0001\x0068" + "\x000F\x0000\x0004\x0068\x0003\x0000\x0001\x0068\x000A\x0000\x0001\x0068\x0083\x0000\x0001\x0068" + "\x0092\x0000\x0004\x0068\x006A\x0000\x0002\x0068\x0015\x0000\x0004\x0068\x002D\x0000\x0001\x0068" + "\x000D\x0000\x0002\x0068\x0008\x0000\x0002\x0068\x0001\x0000\x0001\x0068\x0001\x0000\x0001\x0068" + "\x0009\x0000\x0001\x0068\x0009\x0000\x0002\x0068\x0006\x0000\x0001\x0068\x0002\x0000\x0004\x0068" + "\x0003\x0000\x0001\x0068\x0002\x0000\x0002\x0068\x0001\x0000\x0003\x0068\x0001\x0000\x0002\x0068" + "\x0001\x0000\x0001\x0068\x0008\x0000\x0001\x0068\x0001\x0000\x0002\x0068\x0002\x0000\x0002\x0068" + "\x0001\x0000\x0004\x0068\x0013\x0000\x0001\x0068\x0016\x0000\x0001\x00BF\x0011\x0000\x0001\x00C0" + "\x0002\x0000\x0001\x00C1\x0008\x0000\x0001\x00C2\x0012\x0000\x0001\x00C3\x0011\x0000\x0001\x00C4" + "\x0002\x0000\x0001\x00C5\x002D\x0000\x0001\x0077\x0004\x0000\x0001\x00B5\x0007\x0000\x0001\x00B5" + "\x003F\x0000\x0001\x007F\x0002\x0000\x0001\x007F\x001B\x0000\x0004\x007F\x0042\x0000\x0001\x0032" + "\x0044\x0000\x0001\x0032\x0066\x0000\x0001\x0032\x0021\x0000\x0001\x0032\x000B\x0000\x0001\x007F" + "\x0035\x0000\x0001\x0032\x0009\x0000\x0001\x007F\x0024\x0000\x0001\x007F\x0001\x0000\x0002\x007F" + "\x0011\x0000\x0001\x007F\x0004\x0000\x0001\x007F\x0003\x0000\x0004\x0032\x0008\x0000\x0004\x007F" + "\x0003\x0000\x0001\x007F\x000A\x0000\x0001\x007F\x0074\x0000\x0002\x0032\x009B\x0000\x0001\x007F" + "\x0092\x0000\x0004\x007F\x006A\x0000\x0002\x007F\x0015\x0000\x0004\x007F\x002D\x0000\x0001\x007F" + "\x000D\x0000\x0002\x007F\x0008\x0000\x0002\x007F\x0001\x0000\x0001\x007F\x0001\x0000\x0001\x007F" + "\x0009\x0000\x0001\x007F\x0009\x0000\x0002\x007F\x0006\x0000\x0001\x007F\x0002\x0000\x0004\x007F" + "\x0003\x0000\x0001\x007F\x0002\x0000\x0002\x007F\x0001\x0000\x0003\x007F\x0001\x0000\x0002\x007F" + "\x0001\x0000\x0001\x007F\x0008\x0000\x0001\x007F\x0001\x0000\x0002\x007F\x0002\x0000\x0002\x007F" + "\x0001\x0000\x0004\x007F\x0013\x0000\x0001\x007F\x0049\x0000\x0001\x00B5\x0002\x0000\x0001\x00B5" + "\x001B\x0000\x0004\x00B5\x008E\x0000\x0001\x00B5\x003F\x0000\x0001\x00B5\x0024\x0000\x0001\x00B5" + "\x0001\x0000\x0002\x00B5\x0011\x0000\x0001\x00B5\x0004\x0000\x0001\x00B5\x000F\x0000\x0004\x00B5" + "\x0003\x0000\x0001\x00B5\x000A\x0000\x0001\x00B5\x0083\x0000\x0001\x00B5\x0092\x0000\x0004\x00B5" + "\x006A\x0000\x0002\x00B5\x0015\x0000\x0004\x00B5\x002D\x0000\x0001\x00B5\x000D\x0000\x0002\x00B5" + "\x0008\x0000\x0002\x00B5\x0001\x0000\x0001\x00B5\x0001\x0000\x0001\x00B5\x0009\x0000\x0001\x00B5" + "\x0009\x0000\x0002\x00B5\x0006\x0000\x0001\x00B5\x0002\x0000\x0004\x00B5\x0003\x0000\x0001\x00B5" + "\x0002\x0000\x0002\x00B5\x0001\x0000\x0003\x00B5\x0001\x0000\x0002\x00B5\x0001\x0000\x0001\x00B5" + "\x0008\x0000\x0001\x00B5\x0001\x0000\x0002\x00B5\x0002\x0000\x0002\x00B5\x0001\x0000\x0004\x00B5" + "\x0013\x0000\x0001\x00B5\x0010\x0000"; private static int[] ZzUnpackTrans() { int[] result = new int[26554]; int offset = 0; offset = ZzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; } private static int ZzUnpackTrans(string packed, int offset, int[] result) { int i = 0; // index in packed string int j = offset; // index in unpacked array int l = packed.Length; while (i < l) { int count = packed[i++]; int value = packed[i++]; value--; do { result[j++] = value; } while (--count > 0); } return j; } /* error codes */ private const int ZZ_UNKNOWN_ERROR = 0; private const int ZZ_NO_MATCH = 1; private const int ZZ_PUSHBACK_2BIG = 2; /* error messages for the codes above */ private static readonly string[] ZZ_ERROR_MSG = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; /// <summary> /// ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code> /// </summary> private static readonly int[] ZZ_ATTRIBUTE = ZzUnpackAttribute(); private const string ZZ_ATTRIBUTE_PACKED_0 = "\x0001\x0000\x0001\x0009\x001E\x0001\x0011\x0000\x0001\x0001\x0001\x0000\x0001\x0001\x000A\x0000" + "\x0001\x0001\x0011\x0000\x0001\x0001\x0015\x0000\x0001\x0001\x004D\x0000\x0001\x0001\x0010\x0000"; private static int[] ZzUnpackAttribute() { int[] result = new int[197]; int offset = 0; offset = ZzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; } private static int ZzUnpackAttribute(string packed, int offset, int[] result) { int i = 0; // index in packed string int j = offset; // index in unpacked array int l = packed.Length; while (i < l) { int count = packed[i++]; int value = packed[i++]; do { result[j++] = value; } while (--count > 0); } return j; } /// <summary> /// the input device </summary> private TextReader zzReader; /// <summary> /// the current state of the DFA </summary> private int zzState; /// <summary> /// the current lexical state </summary> private int zzLexicalState = YYINITIAL; /// <summary> /// this buffer contains the current text to be matched and is /// the source of the YyText() string /// </summary> private char[] zzBuffer = new char[ZZ_BUFFERSIZE]; /// <summary> /// the textposition at the last accepting state </summary> private int zzMarkedPos; /// <summary> /// the current text position in the buffer </summary> private int zzCurrentPos; /// <summary> /// startRead marks the beginning of the YyText() string in the buffer </summary> private int zzStartRead; /// <summary> /// endRead marks the last character in the buffer, that has been read /// from input /// </summary> private int zzEndRead; /// <summary> /// number of newlines encountered up to the start of the matched text </summary> private int yyline; /// <summary> /// the number of characters up to the start of the matched text </summary> private int yyChar; #pragma warning disable 169, 414 /// <summary> /// the number of characters from the last newline up to the start of the /// matched text /// </summary> private int yycolumn; /// <summary> /// zzAtBOL == true &lt;=&gt; the scanner is currently at the beginning of a line /// </summary> private bool zzAtBOL = true; /// <summary> /// zzAtEOF == true &lt;=&gt; the scanner is at the EOF </summary> private bool zzAtEOF; /// <summary> /// denotes if the user-EOF-code has already been executed </summary> private bool zzEOFDone; #pragma warning restore 169, 414 /* user code: */ /// <summary> /// Alphanumeric sequences </summary> public static readonly int WORD_TYPE = StandardTokenizer.ALPHANUM; /// <summary> /// Numbers </summary> public static readonly int NUMERIC_TYPE = StandardTokenizer.NUM; /// <summary> /// Chars in class \p{Line_Break = Complex_Context} are from South East Asian /// scripts (Thai, Lao, Myanmar, Khmer, etc.). Sequences of these are kept /// together as as a single token rather than broken up, because the logic /// required to break them at word boundaries is too complex for UAX#29. /// <para> /// See Unicode Line Breaking Algorithm: http://www.unicode.org/reports/tr14/#SA /// </para> /// </summary> public static readonly int SOUTH_EAST_ASIAN_TYPE = StandardTokenizer.SOUTHEAST_ASIAN; public static readonly int IDEOGRAPHIC_TYPE = StandardTokenizer.IDEOGRAPHIC; public static readonly int HIRAGANA_TYPE = StandardTokenizer.HIRAGANA; public static readonly int KATAKANA_TYPE = StandardTokenizer.KATAKANA; public static readonly int HANGUL_TYPE = StandardTokenizer.HANGUL; public int YyChar { get { return yyChar; } } /// <summary> /// Fills CharTermAttribute with the current token text. /// </summary> public void GetText(ICharTermAttribute t) { t.CopyBuffer(zzBuffer, zzStartRead, zzMarkedPos - zzStartRead); } /// <summary> /// Creates a new scanner /// </summary> /// <param name="in"> the TextReader to read input from. </param> public StandardTokenizerImpl(TextReader @in) { this.zzReader = @in; } /// <summary> /// Unpacks the compressed character translation table. /// </summary> /// <param name="packed"> the packed character translation table </param> /// <returns> the unpacked character translation table </returns> private static char[] ZzUnpackCMap(string packed) { char[] map = new char[0x10000]; int i = 0; // index in packed string int j = 0; // index in unpacked array while (i < 2860) { int count = packed[i++]; char value = packed[i++]; do { map[j++] = value; } while (--count > 0); } return map; } /// <summary> /// Refills the input buffer. /// </summary> /// <returns> <code>false</code>, iff there was new input. /// </returns> /// <exception cref="IOException"> if any I/O-Error occurs </exception> private bool ZzRefill() { /* first: make room (if you can) */ if (zzStartRead > 0) { Array.Copy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead - zzStartRead); /* translate stored positions */ zzEndRead -= zzStartRead; zzCurrentPos -= zzStartRead; zzMarkedPos -= zzStartRead; zzStartRead = 0; } /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.Length) { /* if not: blow it up */ char[] newBuffer = new char[zzCurrentPos * 2]; Array.Copy(zzBuffer, 0, newBuffer, 0, zzBuffer.Length); zzBuffer = newBuffer; } /* finally: fill the buffer with new input */ int numRead = zzReader.Read(zzBuffer, zzEndRead, zzBuffer.Length - zzEndRead); if (numRead > 0) { zzEndRead += numRead; return false; } // unlikely but not impossible: read 0 characters, but not at end of stream if (numRead == 0) { int c = zzReader.Read(); if (c <= 0) { return true; } else { zzBuffer[zzEndRead++] = (char)c; return false; } } // numRead < 0 return true; } /// <summary> /// Disposes the input stream. /// </summary> public void YyClose() { zzAtEOF = true; // indicate end of file zzEndRead = zzStartRead; // invalidate buffer if (zzReader != null) { zzReader.Dispose(); } } /// <summary> /// Resets the scanner to read from a new input stream. /// Does not close the old reader. /// /// All internal variables are reset, the old input stream /// <b>cannot</b> be reused (internal buffer is discarded and lost). /// Lexical state is set to <see cref="YYINITIAL"/>. /// /// Internal scan buffer is resized down to its initial length, if it has grown. /// </summary> /// <param name="reader"> the new input stream </param> public void YyReset(TextReader reader) { zzReader = reader; zzAtBOL = true; zzAtEOF = false; zzEOFDone = false; zzEndRead = zzStartRead = 0; zzCurrentPos = zzMarkedPos = 0; yyline = yyChar = yycolumn = 0; zzLexicalState = YYINITIAL; if (zzBuffer.Length > ZZ_BUFFERSIZE) { zzBuffer = new char[ZZ_BUFFERSIZE]; } } /// <summary> /// Returns the current lexical state. /// </summary> public int YyState { get { return zzLexicalState; } } /// <summary> /// Enters a new lexical state /// </summary> /// <param name="newState"> the new lexical state </param> public void YyBegin(int newState) { zzLexicalState = newState; } /// <summary> /// Returns the text matched by the current regular expression. /// </summary> public string YyText { get { return new string(zzBuffer, zzStartRead, zzMarkedPos - zzStartRead); } } /// <summary> /// Returns the character at position <paramref name="pos"/> from the /// matched text. /// /// It is equivalent to YyText[pos], but faster /// </summary> /// <param name="pos"> the position of the character to fetch. /// A value from 0 to YyLength-1. /// </param> /// <returns> the character at position pos </returns> public char YyCharAt(int pos) { return zzBuffer[zzStartRead + pos]; } /// <summary> /// Returns the length of the matched text region. /// </summary> public int YyLength { get { return zzMarkedPos - zzStartRead; } } /// <summary> /// Reports an error that occured while scanning. /// <para/> /// In a wellformed scanner (no or only correct usage of /// YyPushBack(int) and a match-all fallback rule) this method /// will only be called with things that "Can't Possibly Happen". /// If this method is called, something is seriously wrong /// (e.g. a JFlex bug producing a faulty scanner etc.). /// <para/> /// Usual syntax/scanner level error handling should be done /// in error fallback rules. /// </summary> /// <param name="errorCode"> the code of the errormessage to display </param> private void ZzScanError(int errorCode) { string message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (System.IndexOutOfRangeException) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Exception(message); } /// <summary> /// Pushes the specified amount of characters back into the input stream. /// /// They will be read again by then next call of the scanning method /// </summary> /// <param name="number"> the number of characters to be read again. /// This number must not be greater than YyLength! </param> public void YyPushBack(int number) { if (number > YyLength) { ZzScanError(ZZ_PUSHBACK_2BIG); } zzMarkedPos -= number; } /// <summary> /// Resumes scanning until the next regular expression is matched, /// the end of input is encountered or an I/O-Error occurs. /// </summary> /// <returns> the next token </returns> /// <exception cref="IOException"> if any I/O-Error occurs </exception> public int GetNextToken() { int zzInput; int zzAction; // cached fields: int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; char[] zzBufferL = zzBuffer; char[] zzCMapL = ZZ_CMAP; int[] zzTransL = ZZ_TRANS; int[] zzRowMapL = ZZ_ROWMAP; int[] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; yyChar += zzMarkedPosL - zzStartRead; zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = ZZ_LEXSTATE[zzLexicalState]; // set up zzAction for empty match case: int zzAttributes = zzAttrL[zzState]; if ((zzAttributes & 1) == 1) { zzAction = zzState; } { while (true) { if (zzCurrentPosL < zzEndReadL) { zzInput = zzBufferL[zzCurrentPosL++]; } else if (zzAtEOF) { zzInput = StandardTokenizerInterface.YYEOF; goto zzForActionBreak; } else { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; bool eof = ZzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = StandardTokenizerInterface.YYEOF; goto zzForActionBreak; } else { zzInput = zzBufferL[zzCurrentPosL++]; } } int zzNext = zzTransL[zzRowMapL[zzState] + zzCMapL[zzInput]]; if (zzNext == -1) { goto zzForActionBreak; } zzState = zzNext; zzAttributes = zzAttrL[zzState]; if ((zzAttributes & 1) == 1) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ((zzAttributes & 8) == 8) { goto zzForActionBreak; } } } } zzForActionBreak: // store back cached position zzMarkedPos = zzMarkedPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 1: { // Break so we don't hit fall-through warning: break; // Not numeric, word, ideographic, hiragana, or SE Asian -- ignore it. } // goto case 9; // unreachable case 9: break; case 2: { return WORD_TYPE; } case 10: break; case 3: { return NUMERIC_TYPE; } case 11: break; case 4: { return KATAKANA_TYPE; } case 12: break; case 5: { return SOUTH_EAST_ASIAN_TYPE; } case 13: break; case 6: { return IDEOGRAPHIC_TYPE; } case 14: break; case 7: { return HIRAGANA_TYPE; } case 15: break; case 8: { return HANGUL_TYPE; } case 16: break; default: if (zzInput == StandardTokenizerInterface.YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; { return StandardTokenizerInterface.YYEOF; } } else { ZzScanError(ZZ_NO_MATCH); } break; } } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Moq; using Newtonsoft.Json; using NUnit.Framework; using QuantConnect.Brokerages; using QuantConnect.Brokerages.GDAX; using QuantConnect.Interfaces; using QuantConnect.Orders; using RestSharp; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; namespace QuantConnect.Tests.Brokerages.GDAX { [TestFixture] public class GDAXBrokerageTests { #region Declarations GDAXBrokerage _unit; Mock<IWebSocket> _wss = new Mock<IWebSocket>(); Mock<IRestClient> _rest = new Mock<IRestClient>(); Mock<IAlgorithm> _algo = new Mock<IAlgorithm>(); string _orderData; string _orderByIdData; string _openOrderData; string _matchData; string _accountsData; string _holdingData; string _tickerData; Symbol _symbol; const string _brokerId = "d0c5340b-6d6c-49d9-b567-48c4bfca13d2"; const string _matchBrokerId = "132fb6ae-456b-4654-b4e0-d681ac05cea1"; AccountType _accountType = AccountType.Margin; #endregion [SetUp] public void Setup() { var priceProvider = new Mock<IPriceProvider>(); priceProvider.Setup(x => x.GetLastPrice(It.IsAny<Symbol>())).Returns(1.234m); _unit = new GDAXBrokerage("wss://localhost", _wss.Object, _rest.Object, "abc", "MTIz", "pass", _algo.Object, priceProvider.Object); _orderData = File.ReadAllText("TestData//gdax_order.txt"); _matchData = File.ReadAllText("TestData//gdax_match.txt"); _openOrderData = File.ReadAllText("TestData//gdax_openOrders.txt"); _accountsData = File.ReadAllText("TestData//gdax_accounts.txt"); _holdingData = File.ReadAllText("TestData//gdax_holding.txt"); _orderByIdData = File.ReadAllText("TestData//gdax_orderById.txt"); _tickerData = File.ReadAllText("TestData//gdax_ticker.txt"); _symbol = Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => r.Resource.StartsWith("/products/")))).Returns(new RestSharp.RestResponse { Content = File.ReadAllText("TestData//gdax_tick.txt"), StatusCode = HttpStatusCode.OK }); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => r.Resource.StartsWith("/orders/" + _brokerId) || r.Resource.StartsWith("/orders/" + _matchBrokerId)))) .Returns(new RestSharp.RestResponse { Content = File.ReadAllText("TestData//gdax_orderById.txt"), StatusCode = HttpStatusCode.OK }); _algo.Setup(a => a.BrokerageModel.AccountType).Returns(_accountType); _algo.Setup(a => a.AccountCurrency).Returns(Currencies.USD); } private void SetupResponse(string body, HttpStatusCode httpStatus = HttpStatusCode.OK) { _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => !r.Resource.StartsWith("/products/") && !r.Resource.StartsWith("/orders/" + _brokerId)))) .Returns(new RestSharp.RestResponse { Content = body, StatusCode = httpStatus }); } [Test] public void IsConnectedTest() { _wss.Setup(w => w.IsOpen).Returns(true); Assert.IsTrue(_unit.IsConnected); _wss.Setup(w => w.IsOpen).Returns(false); Assert.IsFalse(_unit.IsConnected); } [Test] public void ConnectTest() { _wss.Setup(m => m.Connect()).Callback(() => { _wss.Setup(m => m.IsOpen).Returns(true); }).Verifiable(); _wss.Setup(m => m.IsOpen).Returns(false); _unit.Connect(); _wss.Verify(); } [Test] public void DisconnectTest() { _wss.Setup(m => m.Close()).Verifiable(); _wss.Setup(m => m.IsOpen).Returns(true); _unit.Disconnect(); _wss.Verify(); } [TestCase(5.23512)] [TestCase(99)] public void OnMessageFillTest(decimal expectedQuantity) { string json = _matchData; string id = "132fb6ae-456b-4654-b4e0-d681ac05cea1"; //not our order if (expectedQuantity == 99) { json = json.Replace(id, Guid.NewGuid().ToString()); } decimal orderQuantity = 6.1m; GDAXTestsHelpers.AddOrder(_unit, 1, id, orderQuantity); ManualResetEvent raised = new ManualResetEvent(false); decimal actualFee = 0; decimal actualQuantity = 0; _unit.OrderStatusChanged += (s, e) => { Assert.AreEqual("BTCUSD", e.Symbol.Value); actualFee += e.OrderFee.Value.Amount; Assert.AreEqual(Currencies.USD, e.OrderFee.Value.Currency); actualQuantity += e.AbsoluteFillQuantity; Assert.IsTrue(actualQuantity != orderQuantity); Assert.AreEqual(OrderStatus.Filled, e.Status); Assert.AreEqual(expectedQuantity, e.FillQuantity); // fill quantity = 5.23512 // fill price = 400.23 // partial order fee = (400.23 * 5.23512 * 0.003) = 6.2857562328 Assert.AreEqual(6.2857562328m, actualFee); raised.Set(); }; _unit.OnMessage(_unit, GDAXTestsHelpers.GetArgs(json)); // not our order, market order is completed even if not totally filled json = json.Replace(id, Guid.NewGuid().ToString()); _unit.OnMessage(_unit, GDAXTestsHelpers.GetArgs(json)); //if not our order should get no event Assert.AreEqual(raised.WaitOne(1000), expectedQuantity != 99); } [Test] public void GetAuthenticationTokenTest() { var actual = _unit.GetAuthenticationToken("", "POST", "http://localhost"); Assert.IsFalse(string.IsNullOrEmpty(actual.Signature)); Assert.IsFalse(string.IsNullOrEmpty(actual.Timestamp)); Assert.AreEqual("pass", actual.Passphrase); Assert.AreEqual("abc", actual.Key); } [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, 1.23, 0, OrderType.Market)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, -1.23, 0, OrderType.Market)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, 1.23, 1234.56, OrderType.Limit)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, -1.23, 1234.56, OrderType.Limit)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, 1.23, 1234.56, OrderType.StopMarket)] [TestCase("1", HttpStatusCode.OK, Orders.OrderStatus.Submitted, -1.23, 1234.56, OrderType.StopMarket)] [TestCase(null, HttpStatusCode.BadRequest, Orders.OrderStatus.Invalid, 1.23, 1234.56, OrderType.Market)] [TestCase(null, HttpStatusCode.BadRequest, Orders.OrderStatus.Invalid, 1.23, 1234.56, OrderType.Limit)] [TestCase(null, HttpStatusCode.BadRequest, Orders.OrderStatus.Invalid, 1.23, 1234.56, OrderType.StopMarket)] public void PlaceOrderTest(string orderId, HttpStatusCode httpStatus, Orders.OrderStatus status, decimal quantity, decimal price, OrderType orderType) { var response = new { id = _brokerId, fill_fees = "0.11" }; SetupResponse(JsonConvert.SerializeObject(response), httpStatus); _unit.OrderStatusChanged += (s, e) => { Assert.AreEqual(status, e.Status); if (orderId != null) { Assert.AreEqual("BTCUSD", e.Symbol.Value); Assert.That((quantity > 0 && e.Direction == Orders.OrderDirection.Buy) || (quantity < 0 && e.Direction == Orders.OrderDirection.Sell)); Assert.IsTrue(orderId == null || _unit.CachedOrderIDs.SelectMany(c => c.Value.BrokerId.Where(b => b == _brokerId)).Any()); } }; Order order = null; if (orderType == OrderType.Limit) { order = new Orders.LimitOrder(_symbol, quantity, price, DateTime.UtcNow); } else if (orderType == OrderType.Market) { order = new Orders.MarketOrder(_symbol, quantity, DateTime.UtcNow); } else { order = new Orders.StopMarketOrder(_symbol, quantity, price, DateTime.UtcNow); } bool actual = _unit.PlaceOrder(order); Assert.IsTrue(actual || (orderId == null && !actual)); } [Test] public void GetOpenOrdersTest() { SetupResponse(_openOrderData); _unit.CachedOrderIDs.TryAdd(1, new Orders.MarketOrder { BrokerId = new List<string> { "1" }, Price = 123 }); var actual = _unit.GetOpenOrders(); Assert.AreEqual(2, actual.Count()); Assert.AreEqual(0.01, actual.First().Quantity); Assert.AreEqual(OrderDirection.Buy, actual.First().Direction); Assert.AreEqual(0.1, actual.First().Price); Assert.AreEqual(-1, actual.Last().Quantity); Assert.AreEqual(OrderDirection.Sell, actual.Last().Direction); Assert.AreEqual(1, actual.Last().Price); } [Test] public void GetTickTest() { var actual = _unit.GetTick(_symbol); Assert.AreEqual(333.98m, actual.BidPrice); Assert.AreEqual(333.99m, actual.AskPrice); Assert.AreEqual(5957.11914015, actual.Quantity); } [Test] public void GetCashBalanceTest() { SetupResponse(_accountsData); var actual = _unit.GetCashBalance(); Assert.AreEqual(2, actual.Count()); var usd = actual.Single(a => a.Currency == Currencies.USD); var btc = actual.Single(a => a.Currency == "BTC"); Assert.AreEqual(80.2301373066930000m, usd.Amount); Assert.AreEqual(1.1, btc.Amount); } [Test, Ignore("Holdings are now set to 0 swaps at the start of each launch. Not meaningful.")] public void GetAccountHoldingsTest() { SetupResponse(_holdingData); _unit.CachedOrderIDs.TryAdd(1, new Orders.MarketOrder { BrokerId = new List<string> { "1" }, Price = 123 }); var actual = _unit.GetAccountHoldings(); Assert.AreEqual(0, actual.Count()); } [TestCase(HttpStatusCode.OK, HttpStatusCode.NotFound, false)] [TestCase(HttpStatusCode.OK, HttpStatusCode.OK, true)] public void CancelOrderTest(HttpStatusCode code, HttpStatusCode code2, bool expected) { _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => !r.Resource.EndsWith("1")))).Returns(new RestSharp.RestResponse { StatusCode = code }); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => !r.Resource.EndsWith("2")))).Returns(new RestSharp.RestResponse { StatusCode = code2 }); var actual = _unit.CancelOrder(new Orders.LimitOrder { BrokerId = new List<string> { "1", "2" } }); Assert.AreEqual(expected, actual); } [Test] public void UpdateOrderTest() { Assert.Throws<NotSupportedException>(() => _unit.UpdateOrder(new LimitOrder())); } [Test] public void SubscribeTest() { string actual = null; string expected = "[\"BTC-USD\",\"BTC-ETH\"]"; _wss.Setup(w => w.Send(It.IsAny<string>())).Callback<string>(c => actual = c); _unit.Ticks.Clear(); _unit.Subscribe(new[] { Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX), Symbol.Create("GBPUSD", SecurityType.Crypto, Market.GDAX), Symbol.Create("BTCETH", SecurityType.Crypto, Market.GDAX)}); StringAssert.Contains(expected, actual); // spin for a few seconds, waiting for the GBPUSD tick var start = DateTime.UtcNow; var timeout = start.AddSeconds(5); while (_unit.Ticks.Count == 0 && DateTime.UtcNow < timeout) { Thread.Sleep(1); } // only rate conversion ticks are received during subscribe Assert.AreEqual(1, _unit.Ticks.Count); Assert.AreEqual("GBPUSD", _unit.Ticks[0].Symbol.Value); } [Test] public void UnsubscribeTest() { string actual = null; _wss.Setup(w => w.IsOpen).Returns(true); _wss.Setup(w => w.Send(It.IsAny<string>())).Callback<string>(c => actual = c); _unit.Unsubscribe(new List<Symbol> { Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX) }); StringAssert.Contains("user", actual); StringAssert.Contains("heartbeat", actual); StringAssert.Contains("matches", actual); } [Test, Ignore("This test is obsolete, the 'ticker' channel is no longer used.")] public void OnMessageTickerTest() { string json = _tickerData; _unit.OnMessage(_unit, GDAXTestsHelpers.GetArgs(json)); var actual = _unit.Ticks.First(); Assert.AreEqual("BTCUSD", actual.Symbol.Value); Assert.AreEqual(4388.005m, actual.Price); Assert.AreEqual(4388m, actual.BidPrice); Assert.AreEqual(4388.01m, actual.AskPrice); actual = _unit.Ticks.Last(); Assert.AreEqual("BTCUSD", actual.Symbol.Value); Assert.AreEqual(4388.01m, actual.Price); Assert.AreEqual(0.03m, actual.Quantity); } [Test] public void PollTickTest() { _unit.PollTick(Symbol.Create("GBPUSD", SecurityType.Forex, Market.FXCM)); Thread.Sleep(1000); // conversion rate is the price returned by the QC pricing API Assert.AreEqual(1.234m, _unit.Ticks.First().Price); } [Test] public void ErrorTest() { string actual = null; // subscribe to invalid symbol const string expected = "[\"BTC-LTC\"]"; _wss.Setup(w => w.Send(It.IsAny<string>())).Callback<string>(c => actual = c); _unit.Subscribe(new[] { Symbol.Create("BTCLTC", SecurityType.Crypto, Market.GDAX)}); StringAssert.Contains(expected, actual); BrokerageMessageType messageType = 0; _unit.Message += (sender, e) => { messageType = e.Type; }; const string json = "{\"type\":\"error\",\"message\":\"Failed to subscribe\",\"reason\":\"Invalid product ID provided\"}"; _unit.OnMessage(_unit, GDAXTestsHelpers.GetArgs(json)); Assert.AreEqual(BrokerageMessageType.Warning, messageType); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; #if !NETFX_CORE using NUnit.Framework; #else using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #endif using Newtonsoft.Json.Linq; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Tests.Linq { [TestFixture] public class JPathTests : TestFixtureBase { [Test] public void SingleProperty() { JPath path = new JPath("Blah"); Assert.AreEqual(1, path.Parts.Count); Assert.AreEqual("Blah", path.Parts[0]); } [Test] public void TwoProperties() { JPath path = new JPath("Blah.Two"); Assert.AreEqual(2, path.Parts.Count); Assert.AreEqual("Blah", path.Parts[0]); Assert.AreEqual("Two", path.Parts[1]); } [Test] public void SinglePropertyAndIndexer() { JPath path = new JPath("Blah[0]"); Assert.AreEqual(2, path.Parts.Count); Assert.AreEqual("Blah", path.Parts[0]); Assert.AreEqual(0, path.Parts[1]); } [Test] public void MultiplePropertiesAndIndexers() { JPath path = new JPath("Blah[0].Two.Three[1].Four"); Assert.AreEqual(6, path.Parts.Count); Assert.AreEqual("Blah", path.Parts[0]); Assert.AreEqual(0, path.Parts[1]); Assert.AreEqual("Two", path.Parts[2]); Assert.AreEqual("Three", path.Parts[3]); Assert.AreEqual(1, path.Parts[4]); Assert.AreEqual("Four", path.Parts[5]); } [Test] public void BadCharactersInIndexer() { ExceptionAssert.Throws<JsonException>( @"Unexpected character while parsing path indexer: [", () => { new JPath("Blah[[0]].Two.Three[1].Four"); }); } [Test] public void UnclosedIndexer() { ExceptionAssert.Throws<JsonException>( @"Path ended with open indexer. Expected ]", () => { new JPath("Blah[0"); }); } [Test] public void AdditionalDots() { JPath path = new JPath(".Blah..[0]..Two.Three....[1].Four."); Assert.AreEqual(6, path.Parts.Count); Assert.AreEqual("Blah", path.Parts[0]); Assert.AreEqual(0, path.Parts[1]); Assert.AreEqual("Two", path.Parts[2]); Assert.AreEqual("Three", path.Parts[3]); Assert.AreEqual(1, path.Parts[4]); Assert.AreEqual("Four", path.Parts[5]); } [Test] public void IndexerOnly() { JPath path = new JPath("[111119990]"); Assert.AreEqual(1, path.Parts.Count); Assert.AreEqual(111119990, path.Parts[0]); } [Test] public void EmptyIndexer() { ExceptionAssert.Throws<JsonException>( "Empty path indexer.", () => { new JPath("[]"); }); } [Test] public void IndexerCloseInProperty() { ExceptionAssert.Throws<JsonException>( "Unexpected character while parsing path: ]", () => { new JPath("]"); }); } [Test] public void AdjacentIndexers() { JPath path = new JPath("[1][0][0][" + int.MaxValue + "]"); Assert.AreEqual(4, path.Parts.Count); Assert.AreEqual(1, path.Parts[0]); Assert.AreEqual(0, path.Parts[1]); Assert.AreEqual(0, path.Parts[2]); Assert.AreEqual(int.MaxValue, path.Parts[3]); } [Test] public void MissingDotAfterIndexer() { ExceptionAssert.Throws<JsonException>( "Unexpected character following indexer: B", () => { new JPath("[1]Blah"); }); } [Test] public void EvaluateSingleProperty() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken("Blah"); Assert.IsNotNull(t); Assert.AreEqual(JTokenType.Integer, t.Type); Assert.AreEqual(1, (int)t); } [Test] public void EvaluateMissingProperty() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken("Missing[1]"); Assert.IsNull(t); } [Test] public void EvaluateIndexerOnObject() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken("[1]"); Assert.IsNull(t); } [Test] public void EvaluateIndexerOnObjectWithError() { JObject o = new JObject( new JProperty("Blah", 1)); ExceptionAssert.Throws<JsonException>( @"Index 1 not valid on JObject.", () => { o.SelectToken("[1]", true); }); } [Test] public void EvaluatePropertyOnArray() { JArray a = new JArray(1, 2, 3, 4, 5); JToken t = a.SelectToken("BlahBlah"); Assert.IsNull(t); } [Test] public void EvaluatePropertyOnArrayWithError() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>( @"Property 'BlahBlah' not valid on JArray.", () => { a.SelectToken("BlahBlah", true); }); } [Test] public void EvaluateConstructorOutOfBoundsIndxerWithError() { JConstructor c = new JConstructor("Blah"); ExceptionAssert.Throws<JsonException>( @"Index 1 outside the bounds of JConstructor.", () => { c.SelectToken("[1]", true); }); } [Test] public void EvaluateMissingPropertyWithError() { JObject o = new JObject( new JProperty("Blah", 1)); ExceptionAssert.Throws<JsonException>( "Property 'Missing' does not exist on JObject.", () => { o.SelectToken("Missing", true); }); } [Test] public void EvaluateOutOfBoundsIndxer() { JArray a = new JArray(1, 2, 3, 4, 5); JToken t = a.SelectToken("[1000].Ha"); Assert.IsNull(t); } [Test] public void EvaluateArrayOutOfBoundsIndxerWithError() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>( "Index 1000 outside the bounds of JArray.", () => { a.SelectToken("[1000].Ha", true); }); } [Test] public void EvaluateArray() { JArray a = new JArray(1, 2, 3, 4); JToken t = a.SelectToken("[1]"); Assert.IsNotNull(t); Assert.AreEqual(JTokenType.Integer, t.Type); Assert.AreEqual(2, (int)t); } [Test] public void EvaluateSinglePropertyReturningArray() { JObject o = new JObject( new JProperty("Blah", new [] { 1, 2, 3 })); JToken t = o.SelectToken("Blah"); Assert.IsNotNull(t); Assert.AreEqual(JTokenType.Array, t.Type); t = o.SelectToken("Blah[2]"); Assert.AreEqual(JTokenType.Integer, t.Type); Assert.AreEqual(3, (int)t); } [Test] public void EvaluateLastSingleCharacterProperty() { JObject o2 = JObject.Parse("{'People':[{'N':'Jeff'}]}"); string a2 = (string)o2.SelectToken("People[0].N"); Assert.AreEqual("Jeff", a2); } [Test] public void PathWithConstructor() { JArray a = JArray.Parse(@"[ { ""Property1"": [ 1, [ [ [] ] ] ] }, { ""Property2"": new Constructor1( null, [ 1 ] ) } ]"); JValue v = (JValue)a.SelectToken("[1].Property2[1][0]"); Assert.AreEqual(1L, v.Value); } [Test] public void Example() { JObject o = JObject.Parse(@"{ ""Stores"": [ ""Lambton Quay"", ""Willis Street"" ], ""Manufacturers"": [ { ""Name"": ""Acme Co"", ""Products"": [ { ""Name"": ""Anvil"", ""Price"": 50 } ] }, { ""Name"": ""Contoso"", ""Products"": [ { ""Name"": ""Elbow Grease"", ""Price"": 99.95 }, { ""Name"": ""Headlight Fluid"", ""Price"": 4 } ] } ] }"); string name = (string)o.SelectToken("Manufacturers[0].Name"); // Acme Co decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price"); // 50 string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name"); // Elbow Grease Assert.AreEqual("Acme Co", name); Assert.AreEqual(50m, productPrice); Assert.AreEqual("Elbow Grease", productName); IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList(); // Lambton Quay // Willis Street IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList(); // null // Headlight Fluid decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price")); // 149.95 Assert.AreEqual(2, storeNames.Count); Assert.AreEqual("Lambton Quay", storeNames[0]); Assert.AreEqual("Willis Street", storeNames[1]); Assert.AreEqual(2, firstProductNames.Count); Assert.AreEqual(null, firstProductNames[0]); Assert.AreEqual("Headlight Fluid", firstProductNames[1]); Assert.AreEqual(149.95m, totalPrice); } } }
namespace Nancy.Tests.Unit { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using FakeItEasy; using Nancy.Helpers; using Nancy.IO; using Xunit; using Xunit.Extensions; public class RequestFixture { [Fact] public void Should_dispose_request_stream_when_being_disposed() { // Given var stream = A.Fake<RequestStream>(x => { x.Implements(typeof(IDisposable)); x.WithArgumentsForConstructor(() => new RequestStream(0, false)); }); var url = new Url() { Scheme = "http", Path = "localhost" }; var request = new Request("GET", url, stream); // When request.Dispose(); // Then A.CallTo(() => ((IDisposable)stream).Dispose()).MustHaveHappened(); } [Fact] public void Should_be_disposable() { // Given, When, Then typeof(Request).ShouldImplementInterface<IDisposable>(); } [Fact] public void Should_override_request_method_on_post() { // Given const string bodyContent = "_method=GET"; var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers); // Then request.Method.ShouldEqual("GET"); } [Theory] [InlineData("GET")] [InlineData("PUT")] [InlineData("DELETE")] [InlineData("HEAD")] public void Should_only_override_method_on_post(string method) { // Given const string bodyContent = "_method=TEST"; var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } }; // When var request = new Request(method, new Url { Path = "/", Scheme = "http" }, memory, headers); // Then request.Method.ShouldEqual(method); } [Fact] public void Should_throw_argumentoutofrangeexception_when_initialized_with_null_method() { // Given, When var exception = Record.Exception(() => new Request(null, "/", "http")); // Then exception.ShouldBeOfType<ArgumentOutOfRangeException>(); } [Fact] public void Should_throw_argumentoutofrangeexception_when_initialized_with_empty_method() { // Given, When var exception = Record.Exception(() => new Request(string.Empty, "/", "http")); // Then exception.ShouldBeOfType<ArgumentOutOfRangeException>(); } [Fact] public void Should_throw_null_exception_when_initialized_with_null_uri() { // Given, When var exception = Record.Exception(() => new Request("GET", null, "http")); // Then exception.ShouldBeOfType<ArgumentNullException>(); } [Fact] public void Should_set_method_parameter_value_to_method_property_when_initialized() { // Given const string method = "GET"; // When var request = new Request(method, "/", "http"); // Then request.Method.ShouldEqual(method); } [Fact] public void Should_set_uri_parameter_value_to_uri_property_when_initialized() { // Given const string path = "/"; // When var request = new Request("GET", path, "http"); // Then request.Path.ShouldEqual(path); } [Fact] public void Should_set_header_parameter_value_to_header_property_when_initialized() { // Given var headers = new Dictionary<string, IEnumerable<string>>() { { "content-type", new[] {"foo"} } }; // When var request = new Request("GET", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(), headers); // Then request.Headers.ContentType.ShouldNotBeEmpty(); } [Fact] public void Should_set_body_parameter_value_to_body_property_when_initialized() { // Given var body = CreateRequestStream(); // When var request = new Request("GET", new Url { Path = "/", Scheme = "http" }, body, new Dictionary<string, IEnumerable<string>>()); // Then request.Body.ShouldBeSameAs(body); } [Fact] public void Should_set_extract_form_data_from_body_when_content_type_is_x_www_form_urlencoded() { // Given const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D"; var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers); // Then ((string)request.Form.name).ShouldEqual("John Doe"); } [Fact] public void Should_set_extract_form_data_from_body_when_content_type_is_x_www_form_urlencoded_with_character_set() { // Given const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D"; var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded; charset=UTF-8" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers); // Then ((string)request.Form.name).ShouldEqual("John Doe"); } [Fact] public void Should_set_extracted_form_data_from_body_when_content_type_is_multipart_form_data() { // Given var memory = new MemoryStream(BuildMultipartFormValues(new Dictionary<string, string> { { "name", "John Doe"}, { "age", "42"} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers); // Then ((string)request.Form.name).ShouldEqual("John Doe"); ((string)request.Form.age).ShouldEqual("42"); } [Fact] public void Should_respect_case_insensitivity_when_extracting_form_data_from_body_when_content_type_is_x_www_form_urlencoded() { // Given StaticConfiguration.CaseSensitive = false; const string bodyContent = "key=value&key=value&KEY=VALUE"; var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers); // Then ((string)request.Form.key).ShouldEqual("value,value,VALUE"); ((string)request.Form.KEY).ShouldEqual("value,value,VALUE"); } [Fact] public void Should_respect_case_sensitivity_when_extracting_form_data_from_body_when_content_type_is_x_www_form_urlencoded() { // Given StaticConfiguration.CaseSensitive = true; const string bodyContent = "key=value&key=value&KEY=VALUE"; var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers); // Then ((string)request.Form.key).ShouldEqual("value,value"); ((string)request.Form.KEY).ShouldEqual("VALUE"); } [Fact] public void Should_respect_case_insensitivity_when_extracting_form_data_from_body_when_content_type_is_multipart_form_data() { // Given StaticConfiguration.CaseSensitive = false; var memory = new MemoryStream(BuildMultipartFormValues(new Dictionary<string, string>(StringComparer.Ordinal) { { "key", "value" }, { "KEY", "VALUE" } })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers); // Then ((string)request.Form.key).ShouldEqual("value,VALUE"); ((string)request.Form.KEY).ShouldEqual("value,VALUE"); } [Fact] public void Should_respect_case_sensitivity_when_extracting_form_data_from_body_when_content_type_is_multipart_form_data() { // Given StaticConfiguration.CaseSensitive = true; var memory = new MemoryStream(BuildMultipartFormValues(new Dictionary<string, string>(StringComparer.Ordinal) { { "key", "value" }, { "KEY", "VALUE" } })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers); // Then ((string)request.Form.key).ShouldEqual("value"); ((string)request.Form.KEY).ShouldEqual("VALUE"); } [Fact] public void Should_set_extracted_files_to_files_collection_when_body_content_type_is_multipart_form_data() { // Given var memory = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>> { { "test", new Tuple<string, string, string>("content/type", "some test content", "whatever")} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers); // Then request.Files.ShouldHaveCount(1); } [Fact] public void Should_set_content_type_on_file_extracted_from_multipart_form_data_body() { // Given var memory = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>> { { "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers); // Then request.Files.First().ContentType.ShouldEqual("content/type"); } [Fact] public void Should_set_name_on_file_extracted_from_multipart_form_data_body() { // Given var memory = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>> { { "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers); // Then request.Files.First().Name.ShouldEqual("sample.txt"); } [Fact] public void Should_value_on_file_extracted_from_multipart_form_data_body() { // Given var memory = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>> { { "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers); // Then GetStringValue(request.Files.First().Value).ShouldEqual("some test content"); } [Fact] public void Should_set_key_on_file_extracted_from_multipart_data_body() { // Given var memory = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>> { { "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "fieldname")} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers); // Then request.Files.First().Key.ShouldEqual("fieldname"); } private static string GetStringValue(Stream stream) { var reader = new StreamReader(stream); return reader.ReadToEnd(); } [Fact] public void Should_be_able_to_invoke_form_repeatedly() { const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D"; var memory = new MemoryStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers); // Then ((string)request.Form.name).ShouldEqual("John Doe"); } [Fact] public void Should_throw_argumentoutofrangeexception_when_initialized_with_null_protocol() { // Given, When var exception = Record.Exception(() => new Request("GET", "/", null)); // Then exception.ShouldBeOfType<ArgumentOutOfRangeException>(); } [Fact] public void Should_throw_argumentoutofrangeexception_when_initialized_with_an_empty_protocol() { // Given, When var exception = Record.Exception(() => new Request("GET", "/", string.Empty)); // Then exception.ShouldBeOfType<ArgumentOutOfRangeException>(); } [Fact] public void Should_set_protocol_parameter_value_to_protocol_property_when_initialized() { // Given const string protocol = "http"; // When var request = new Request("GET", "/", protocol); // Then request.Url.Scheme.ShouldEqual(protocol); } [Fact] public void Should_split_cookie_in_two_parts_only() { // Given, when var cookieName = "_nc"; var cookieData = "Y+M3rcC/7ssXvHTx9pwCbwQVV4g=sp0hUZVApYgGbKZIU4bvXbBCVl9fhSEssEXSGdrt4jVag6PO1oed8lSd+EJD1nzWx4OTTCTZKjYRWeHE97QVND4jJIl+DuKRgJnSl3hWI5gdgGjcxqCSTvMOMGmW3NHLVyKpajGD8tq1DXhXMyXHjTzrCAYl8TGzwyJJGx/gd7VMJeRbAy9JdHOxEUlCKUnPneWN6q+/ITFryAa5hAdfcjXmh4Fgym75whKOMkWO+yM2icdsciX0ShcvnEQ/bXcTHTya6d7dJVfZl7qQ8AgIQv8ucQHxD3NxIvHNPBwms2ClaPds0HG5N+7pu7eMSFZjUHpDrrCnFvYN+JDiG3GMpf98LuCCvxemvipJo2MUkY4J1LvaDFoWA5tIxAfItZJkSIW2d8JPDwFk8OHJy8zhyn8AjD2JFqWaUZr4y9KZOtgI0V0Qlq0mS3mDSlLn29xapgoPHBvykwQjR6TwF2pBLpStsfZa/tXbEv2mc3VO3CnErIA1lEfKNqn9C/Dw6hqW"; var headers = new Dictionary<string, IEnumerable<string>>(); var cookies = new List<string>(); cookies.Add(string.Format("{0}={1}", cookieName, HttpUtility.UrlEncode(cookieData))); headers.Add("cookie", cookies); var newUrl = new Url { Path = "/" }; var request = new Request("GET", newUrl, null, headers); // Then request.Cookies[cookieName].ShouldEqual(cookieData); } [Fact] public void Should_split_cookie_in_two_parts_with_secure_attribute() { // Given, when const string cookieName = "path"; const string cookieData = "/"; var headers = new Dictionary<string, IEnumerable<string>>(); var cookies = new List<string> { string.Format("{0}={1}; Secure", cookieName, cookieData)} ; headers.Add("cookie", cookies); var newUrl = new Url { Path = "/" }; var request = new Request("GET", newUrl, null, headers); // Then request.Cookies[cookieName].ShouldEqual(cookieData); } [Fact] public void Should_split_cookie_in_two_parts_with_httponly_and_secure_attribute() { // Given, when const string cookieName = "path"; const string cookieData = "/"; var headers = new Dictionary<string, IEnumerable<string>>(); var cookies = new List<string> { string.Format("{0}={1}; HttpOnly; Secure", cookieName, cookieData) }; headers.Add("cookie", cookies); var newUrl = new Url { Path = "/" }; var request = new Request("GET", newUrl, null, headers); // Then request.Cookies[cookieName].ShouldEqual(cookieData); } [Fact] public void Should_split_cookie_in_two_parts_with_httponly_and_secure_attribute_ignoring_case() { // Given, when const string cookieName = "path"; const string cookieData = "/"; var headers = new Dictionary<string, IEnumerable<string>>(); var cookies = new List<string> { string.Format("{0}={1}; httponly; secure", cookieName, cookieData) }; headers.Add("cookie", cookies); var newUrl = new Url { Path = "/" }; var request = new Request("GET", newUrl, null, headers); // Then request.Cookies[cookieName].ShouldEqual(cookieData); } [Fact] public void Should_split_cookie_in_two_parts_with_httponly_attribute() { // Given, when const string cookieName = "path"; const string cookieData = "/"; var headers = new Dictionary<string, IEnumerable<string>>(); var cookies = new List<string> { string.Format("{0}={1}; HttpOnly", cookieName, cookieData) }; headers.Add("cookie", cookies); var newUrl = new Url { Path = "/" }; var request = new Request("GET", newUrl, null, headers); // Then request.Cookies[cookieName].ShouldEqual(cookieData); } [Fact] public void Should_add_attribute_in_cookie_as_empty_value() { // Given, when const string cookieName = "path"; const string cookieData = "/"; const string cookieAttribute = "SomeAttribute"; var headers = new Dictionary<string, IEnumerable<string>>(); var cookies = new List<string> { string.Format("{0}={1}; {2}", cookieName, cookieData, cookieAttribute) }; headers.Add("cookie", cookies); var newUrl = new Url { Path = "/" }; var request = new Request("GET", newUrl, null, headers); // Then request.Cookies[cookieName].ShouldEqual(cookieData); request.Cookies[cookieAttribute].ShouldEqual(string.Empty); } [Fact] public void Should_move_request_body_position_to_zero_after_parsing_url_encoded_data() { // Given const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D"; var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded; charset=UTF-8" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers); // Then memory.Position.ShouldEqual(0L); } [Fact] public void Should_move_request_body_position_to_zero_after_parsing_multipart_encoded_data() { // Given var memory = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>> { { "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers); // Then memory.Position.ShouldEqual(0L); } [Fact] public void Should_preserve_all_values_when_multiple_are_posted_using_same_name_after_parsing_multipart_encoded_data() { // Given var memory = new MemoryStream(BuildMultipartFormValues( new KeyValuePair<string, string>("age", "32"), new KeyValuePair<string, string>("age", "42"), new KeyValuePair<string, string>("age", "52") )); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers); // Then ((string)request.Form.age).ShouldEqual("32,42,52"); } [Fact] public void Should_limit_the_amount_of_form_fields_parsed() { // Given var sb = new StringBuilder(); for (int i = 0; i < StaticConfiguration.RequestQueryFormMultipartLimit + 10; i++) { if (i > 0) { sb.Append('&'); } sb.AppendFormat("Field{0}=Value{0}", i); } var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(sb.ToString()); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } }; // When var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers); // Then ((IEnumerable<string>)request.Form.GetDynamicMemberNames()).Count().ShouldEqual(StaticConfiguration.RequestQueryFormMultipartLimit); } [Fact] public void Should_limit_the_amount_of_querystring_fields_parsed() { // Given var sb = new StringBuilder(); for (int i = 0; i < StaticConfiguration.RequestQueryFormMultipartLimit + 10; i++) { if (i > 0) { sb.Append('&'); } sb.AppendFormat("Field{0}=Value{0}", i); } var memory = CreateRequestStream(); // When var request = new Request("GET", new Url { Path = "/", Scheme = "http", Query = sb.ToString() }, memory, new Dictionary<string, IEnumerable<string>>()); // Then ((IEnumerable<string>)request.Query.GetDynamicMemberNames()).Count().ShouldEqual(StaticConfiguration.RequestQueryFormMultipartLimit); } [Fact] public void Should_change_empty_path_to_root() { var request = new Request("GET", "", "http"); request.Path.ShouldEqual("/"); } [Fact] public void Should_replace_value_of_query_key_without_value_with_true() { // Given var memory = CreateRequestStream(); // When var request = new Request("GET", new Url { Path = "/", Scheme = "http", Query = "key1" }, memory); // Then ((bool)request.Query.key1).ShouldBeTrue(); ((string)request.Query.key1).ShouldEqual("key1"); } [Fact] public void Should_not_replace_equal_key_value_query_with_bool() { // Given var memory = CreateRequestStream(); // When var request = new Request("GET", new Url { Path = "/", Scheme = "http", Query = "key1=key1" }, memory); // Then ShouldAssertExtensions.ShouldBeOfType<string>(request.Query["key1"].Value); } private static RequestStream CreateRequestStream() { return CreateRequestStream(new MemoryStream()); } private static RequestStream CreateRequestStream(Stream stream) { return RequestStream.FromStream(stream); } private static byte[] BuildMultipartFormValues(params KeyValuePair<string, string>[] values) { var boundaryBuilder = new StringBuilder(); foreach (var pair in values) { boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append("--"); boundaryBuilder.Append("----NancyFormBoundary"); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"", pair.Key); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append(pair.Value); } boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append("------NancyFormBoundary--"); var bytes = Encoding.ASCII.GetBytes(boundaryBuilder.ToString()); return bytes; } private static byte[] BuildMultipartFormValues(Dictionary<string, string> formValues) { var pairs = formValues.Keys.Select(key => new KeyValuePair<string, string>(key, formValues[key])); return BuildMultipartFormValues(pairs.ToArray()); } private static byte[] BuildMultipartFileValues(Dictionary<string, Tuple<string, string, string>> formValues) { var boundaryBuilder = new StringBuilder(); foreach (var key in formValues.Keys) { boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append("--"); boundaryBuilder.Append("----NancyFormBoundary"); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.AppendFormat("Content-Disposition: form-data; name=\"{1}\"; filename=\"{0}\"", key, formValues[key].Item3); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.AppendFormat("Content-Type: {0}", formValues[key].Item1); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append(formValues[key].Item2); } boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append("------NancyFormBoundary--"); var bytes = Encoding.ASCII.GetBytes(boundaryBuilder.ToString()); return bytes; } } }
// 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.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { internal sealed class WinHttpRequestStream : Stream { private static readonly byte[] s_crLfTerminator = new byte[] { 0x0d, 0x0a }; // "\r\n" private static readonly byte[] s_endChunk = new byte[] { 0x30, 0x0d, 0x0a, 0x0d, 0x0a }; // "0\r\n\r\n" private volatile bool _disposed; private readonly WinHttpRequestState _state; private readonly bool _chunkedMode; // TODO (Issue 2505): temporary pinned buffer caches of 1 item. Will be replaced by PinnableBufferCache. private GCHandle _cachedSendPinnedBuffer; internal WinHttpRequestStream(WinHttpRequestState state, bool chunkedMode) { _state = state; _chunkedMode = chunkedMode; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return !_disposed; } } public override long Length { get { CheckDisposed(); throw new NotSupportedException(); } } public override long Position { get { CheckDisposed(); throw new NotSupportedException(); } set { CheckDisposed(); throw new NotSupportedException(); } } public override void Flush() { // Nothing to do. } public override Task FlushAsync(CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - offset) { throw new ArgumentException(SR.net_http_buffer_insufficient_length, nameof(buffer)); } if (token.IsCancellationRequested) { var tcs = new TaskCompletionSource<int>(); tcs.TrySetCanceled(token); return tcs.Task; } CheckDisposed(); if (_state.TcsInternalWriteDataToRequestStream != null && !_state.TcsInternalWriteDataToRequestStream.Task.IsCompleted) { throw new InvalidOperationException(SR.net_http_no_concurrent_io_allowed); } return InternalWriteAsync(buffer, offset, count, token); } public override void Write(byte[] buffer, int offset, int count) { WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public override long Seek(long offset, SeekOrigin origin) { CheckDisposed(); throw new NotSupportedException(); } public override void SetLength(long value) { CheckDisposed(); throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { CheckDisposed(); throw new NotSupportedException(); } internal async Task EndUploadAsync(CancellationToken token) { if (_chunkedMode) { await InternalWriteDataAsync(s_endChunk, 0, s_endChunk.Length, token).ConfigureAwait(false); } } protected override void Dispose(bool disposing) { if (!_disposed) { _disposed = true; // TODO (Issue 2508): Pinned buffers must be released in the callback, when it is guaranteed no further // operations will be made to the send/receive buffers. if (_cachedSendPinnedBuffer.IsAllocated) { _cachedSendPinnedBuffer.Free(); } } base.Dispose(disposing); } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().FullName); } } private Task InternalWriteAsync(byte[] buffer, int offset, int count, CancellationToken token) { if (count == 0) { return Task.CompletedTask; } return _chunkedMode ? InternalWriteChunkedModeAsync(buffer, offset, count, token) : InternalWriteDataAsync(buffer, offset, count, token); } private async Task InternalWriteChunkedModeAsync(byte[] buffer, int offset, int count, CancellationToken token) { // WinHTTP does not fully support chunked uploads. It simply allows one to omit the 'Content-Length' header // and instead use the 'Transfer-Encoding: chunked' header. The caller is still required to encode the // request body according to chunking rules. Debug.Assert(_chunkedMode); Debug.Assert(count > 0); string chunkSizeString = string.Format("{0:x}\r\n", count); byte[] chunkSize = Encoding.UTF8.GetBytes(chunkSizeString); await InternalWriteDataAsync(chunkSize, 0, chunkSize.Length, token).ConfigureAwait(false); await InternalWriteDataAsync(buffer, offset, count, token).ConfigureAwait(false); await InternalWriteDataAsync(s_crLfTerminator, 0, s_crLfTerminator.Length, token).ConfigureAwait(false); } private Task<bool> InternalWriteDataAsync(byte[] buffer, int offset, int count, CancellationToken token) { Debug.Assert(count > 0); // TODO (Issue 2505): replace with PinnableBufferCache. if (!_cachedSendPinnedBuffer.IsAllocated || _cachedSendPinnedBuffer.Target != buffer) { if (_cachedSendPinnedBuffer.IsAllocated) { _cachedSendPinnedBuffer.Free(); } _cachedSendPinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); } _state.TcsInternalWriteDataToRequestStream = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); lock (_state.Lock) { if (!Interop.WinHttp.WinHttpWriteData( _state.RequestHandle, Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset), (uint)count, IntPtr.Zero)) { _state.TcsInternalWriteDataToRequestStream.TrySetException( new IOException(SR.net_http_io_write, WinHttpException.CreateExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpWriteData)))); } } // TODO: Issue #2165. Register callback on cancellation token to cancel WinHTTP operation. return _state.TcsInternalWriteDataToRequestStream.Task; } } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERLevel; namespace SelfLoad.Business.ERLevel { /// <summary> /// C07_Country_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="C07_Country_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="C06_Country"/> collection. /// </remarks> [Serializable] public partial class C07_Country_ReChild : BusinessBase<C07_Country_ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Country_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Regions Child Name"); /// <summary> /// Gets or sets the Regions Child Name. /// </summary> /// <value>The Regions Child Name.</value> public string Country_Child_Name { get { return GetProperty(Country_Child_NameProperty); } set { SetProperty(Country_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C07_Country_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="C07_Country_ReChild"/> object.</returns> internal static C07_Country_ReChild NewC07_Country_ReChild() { return DataPortal.CreateChild<C07_Country_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="C07_Country_ReChild"/> object, based on given parameters. /// </summary> /// <param name="country_ID2">The Country_ID2 parameter of the C07_Country_ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="C07_Country_ReChild"/> object.</returns> internal static C07_Country_ReChild GetC07_Country_ReChild(int country_ID2) { return DataPortal.FetchChild<C07_Country_ReChild>(country_ID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C07_Country_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public C07_Country_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="C07_Country_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="C07_Country_ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="country_ID2">The Country ID2.</param> protected void Child_Fetch(int country_ID2) { var args = new DataPortalHookArgs(country_ID2); OnFetchPre(args); using (var dalManager = DalFactorySelfLoad.GetManager()) { var dal = dalManager.GetProvider<IC07_Country_ReChildDal>(); var data = dal.Fetch(country_ID2); Fetch(data); } OnFetchPost(args); // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="C07_Country_ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Country_Child_NameProperty, dr.GetString("Country_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="C07_Country_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(C06_Country parent) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IC07_Country_ReChildDal>(); using (BypassPropertyChecks) { dal.Insert( parent.Country_ID, Country_Child_Name ); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="C07_Country_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(C06_Country parent) { if (!IsDirty) return; using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IC07_Country_ReChildDal>(); using (BypassPropertyChecks) { dal.Update( parent.Country_ID, Country_Child_Name ); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="C07_Country_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(C06_Country parent) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IC07_Country_ReChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Country_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall; using FlatRedBall.Gui; using FlatRedBall.Collections; using FlatRedBall.IO; using FlatRedBall.ManagedSpriteGroups; namespace SpriteEditor.Gui { public class SpriteRigSaveOptions : Window { #region Fields private ComboBox bodyAvailableTextures; private TextBox bodyNameToInclude; public SpriteList bodySprites; private ComboBox bodySpriteSelectionMethod; private Button cancelButton; private ComboBox jointAvailableTextures; private TextBox jointNameToInclude; public SpriteList joints; private ComboBox jointSpriteSelectionMethod; public ToggleButton jointsVisible; private GuiMessages messages; private Button okButton; public List<PoseChain> poseChains; public Sprite root; private ComboBox rootSpriteComboBox; public ToggleButton rootVisible; private ComboBox sceneOrGroup; #endregion #region Delegates private void jointSpriteSelectionMethodClicked(Window callingWindow) { if (((ComboBox)callingWindow).Text == "Name Includes") { this.jointAvailableTextures.Visible = false; this.jointNameToInclude.Visible = true; } else if (((ComboBox)callingWindow).Text == "By Texture") { this.jointAvailableTextures.Visible = true; this.jointNameToInclude.Visible = false; this.fillAvailableTextures(this.jointAvailableTextures); } else { this.jointAvailableTextures.Visible = false; this.jointNameToInclude.Visible = false; } } private void bodySpriteSelectionMethodClicked(Window callingWindow) { if (((ComboBox)callingWindow).Text == "Name Includes") { this.bodyAvailableTextures.Visible = false; this.bodyNameToInclude.Visible = true; } else if (((ComboBox)callingWindow).Text == "By Texture") { this.bodyAvailableTextures.Visible = true; this.bodyNameToInclude.Visible = false; this.fillAvailableTextures(this.bodyAvailableTextures); } else { this.bodyAvailableTextures.Visible = false; this.bodyNameToInclude.Visible = false; } } private void saveButtonClick(Window callingWindow) { // If a user thinks he's funny and selects AllNotJoint for BodySprites // and AllNotBodySprites for Joints, let the user know he has to // specify some criteria. if (this.bodySpriteSelectionMethod.Text == "All Not Joint" && this.jointSpriteSelectionMethod.Text == "All Not Body") { GuiManager.ShowMessageBox( "Cannot select All Not Body for Joint Selection when " + "All Not Joint is selected for Body Sprite Selection. " + "Change one of the criteria and try to save again.", "Selection Error"); return; } double error = 0; SpriteList possibleSprites = new SpriteList(); if (this.sceneOrGroup.Text == "Entire Scene") { possibleSprites = GameData.Scene.Sprites; } else if (GameData.EditorLogic.CurrentSprites.Count != 0) { ((Sprite)GameData.EditorLogic.CurrentSprites[0].TopParent).GetAllDescendantsOneWay(possibleSprites); } #region Get rid of the Axes from the possibleSprites if (possibleSprites.Contains(GameData.EditorLogic.EditAxes.xAxis)) { possibleSprites.Remove(GameData.EditorLogic.EditAxes.xAxis); } if (possibleSprites.Contains(GameData.EditorLogic.EditAxes.yAxis)) { possibleSprites.Remove(GameData.EditorLogic.EditAxes.yAxis); } if (possibleSprites.Contains(GameData.EditorLogic.EditAxes.zAxis)) { possibleSprites.Remove(GameData.EditorLogic.EditAxes.zAxis); } if (possibleSprites.Contains(GameData.EditorLogic.EditAxes.xRot)) { possibleSprites.Remove(GameData.EditorLogic.EditAxes.xRot); } if (possibleSprites.Contains(GameData.EditorLogic.EditAxes.yRot)) { possibleSprites.Remove(GameData.EditorLogic.EditAxes.yRot); } if (possibleSprites.Contains(GameData.EditorLogic.EditAxes.xScale)) { possibleSprites.Remove(GameData.EditorLogic.EditAxes.xScale); } if (possibleSprites.Contains(GameData.EditorLogic.EditAxes.yScale)) { possibleSprites.Remove(GameData.EditorLogic.EditAxes.yScale); } if (possibleSprites.Contains(GameData.EditorLogic.EditAxes.origin)) { possibleSprites.Remove(GameData.EditorLogic.EditAxes.origin); } #endregion if (this.bodySpriteSelectionMethod.Text == "Name Includes") { this.bodySprites = possibleSprites.FindSpritesWithNameContaining(this.bodyNameToInclude.Text); } else if (this.bodySpriteSelectionMethod.Text == "By Texture") { this.bodySprites = possibleSprites.FindSpritesWithTexture( FlatRedBallServices.Load<Texture2D>(this.bodyAvailableTextures.Text, GameData.SceneContentManager)); } else if (this.bodySpriteSelectionMethod.Text == "All") { this.bodySprites = possibleSprites; } if (this.jointSpriteSelectionMethod.Text == "Name Includes") { this.joints = possibleSprites.FindSpritesWithNameContaining(this.jointNameToInclude.Text); } else if (this.jointSpriteSelectionMethod.Text == "By Texture") { this.joints = possibleSprites.FindSpritesWithTexture( FlatRedBallServices.Load<Texture2D>(this.jointAvailableTextures.Text, GameData.SceneContentManager)); } else if (this.jointSpriteSelectionMethod.Text == "All") { this.joints = possibleSprites; } try { if (bodySpriteSelectionMethod == null) System.Windows.Forms.MessageBox.Show("a"); if (this.bodySpriteSelectionMethod.Text == "All Not Joint") { this.bodySprites = new SpriteList(); if (possibleSprites == null) System.Windows.Forms.MessageBox.Show("b"); foreach (Sprite s in possibleSprites) { if (this == null) System.Windows.Forms.MessageBox.Show("c"); if (this.joints == null) System.Windows.Forms.MessageBox.Show("d"); if (this.bodySprites == null) System.Windows.Forms.MessageBox.Show("e"); if (!this.joints.Contains(s)) { this.bodySprites.Add(s); } } } } catch { error = 3.3; } if (this.jointSpriteSelectionMethod.Text == "All Not Body") { this.joints = new SpriteList(); foreach (Sprite s in possibleSprites) { if (!this.bodySprites.Contains(s)) { this.joints.Add(s); } } } if (this.rootSpriteComboBox.Text != "<No Root>") { this.root = possibleSprites.FindByName(this.rootSpriteComboBox.Text); } else { this.root = null; } FileButtonWindow.spriteRigOptionsOK(this); this.Visible = false; } #endregion // Methods public SpriteRigSaveOptions(GuiMessages messages, Cursor cursor) : base(cursor) { this.messages = messages; GuiManager.AddWindow(this); this.ScaleX = 13f; this.ScaleY = 17f; base.HasMoveBar = true; base.mName = "SpriteRig Options"; base.HasCloseButton = true; TextDisplay tempTextDisplay = new TextDisplay(mCursor); AddWindow(tempTextDisplay); tempTextDisplay.Text = "Include:"; tempTextDisplay.SetPositionTL(0.2f, 1.5f); this.sceneOrGroup = new ComboBox(mCursor); AddWindow(sceneOrGroup); this.sceneOrGroup.ScaleX = 8f; this.sceneOrGroup.SetPositionTL(10f, 3.5f); this.sceneOrGroup.Text = "Entire Scene"; this.sceneOrGroup.AddItem("Current Group"); this.sceneOrGroup.AddItem("Entire Scene"); tempTextDisplay = new TextDisplay(mCursor); AddWindow(tempTextDisplay); tempTextDisplay.Text = "Body Sprite Selection Includes:"; tempTextDisplay.SetPositionTL(0.2f, 6f); this.bodySpriteSelectionMethod = new ComboBox(mCursor); AddWindow(bodySpriteSelectionMethod); this.bodySpriteSelectionMethod.ScaleX = 8f; this.bodySpriteSelectionMethod.SetPositionTL(10f, 8.5f); this.bodySpriteSelectionMethod.Text = "Name Includes"; this.bodySpriteSelectionMethod.AddItem("Name Includes"); this.bodySpriteSelectionMethod.AddItem("By Texture"); this.bodySpriteSelectionMethod.AddItem("All Not Joint"); this.bodySpriteSelectionMethod.AddItem("All"); this.bodySpriteSelectionMethod.ItemClick += new GuiMessage(this.bodySpriteSelectionMethodClicked); this.bodyAvailableTextures = new ComboBox(mCursor); AddWindow(bodyAvailableTextures); this.bodyAvailableTextures.ScaleX = 8f; this.bodyAvailableTextures.SetPositionTL(10f, 10.5f); this.bodyAvailableTextures.Visible = false; this.bodyNameToInclude = new TextBox(mCursor); AddWindow(bodyNameToInclude); this.bodyNameToInclude.ScaleX = 8f; this.bodyNameToInclude.SetPositionTL(10f, 10.5f); tempTextDisplay = new TextDisplay(mCursor); AddWindow(tempTextDisplay); tempTextDisplay.Text = "Joint Sprite Selection Includes:"; tempTextDisplay.SetPositionTL(0.2f, 13f); this.jointSpriteSelectionMethod = new ComboBox(mCursor); AddWindow(jointSpriteSelectionMethod); this.jointSpriteSelectionMethod.ScaleX = 8f; this.jointSpriteSelectionMethod.SetPositionTL(10f, 15.5f); this.jointSpriteSelectionMethod.Text = "Name Includes"; this.jointSpriteSelectionMethod.AddItem("Name Includes"); this.jointSpriteSelectionMethod.AddItem("By Texture"); this.jointSpriteSelectionMethod.AddItem("All Not Body"); this.jointSpriteSelectionMethod.AddItem("All"); this.jointSpriteSelectionMethod.ItemClick += new GuiMessage(this.jointSpriteSelectionMethodClicked); this.jointAvailableTextures = new ComboBox(mCursor); AddWindow(jointAvailableTextures); this.jointAvailableTextures.ScaleX = 8f; this.jointAvailableTextures.SetPositionTL(10f, 18f); this.jointAvailableTextures.Visible = false; this.jointNameToInclude = new TextBox(mCursor); AddWindow(jointNameToInclude); this.jointNameToInclude.ScaleX = 8f; this.jointNameToInclude.SetPositionTL(10f, 18f); tempTextDisplay = new TextDisplay(mCursor); AddWindow(tempTextDisplay); tempTextDisplay.Text = "Root Sprite:"; tempTextDisplay.SetPositionTL(0.2f, 20); this.rootSpriteComboBox = new ComboBox(mCursor); AddWindow(rootSpriteComboBox); this.rootSpriteComboBox.ScaleX = 8f; this.rootSpriteComboBox.SetPositionTL(10f, 22.5f); this.rootSpriteComboBox.Text = "<No Root>"; tempTextDisplay = new TextDisplay(mCursor); AddWindow(tempTextDisplay); tempTextDisplay.Text = "Sprite Visibility:"; tempTextDisplay.SetPositionTL(0.2f, 25f); this.jointsVisible = new ToggleButton(mCursor); AddWindow(jointsVisible); this.jointsVisible.SetPositionTL(11f, 27f); this.jointsVisible.SetText("Joints Not Visible", "Joints Visible"); this.jointsVisible.ScaleX = 7.5f; this.rootVisible = new ToggleButton(mCursor); AddWindow(rootVisible); this.rootVisible.SetPositionTL(11f, 29f); this.rootVisible.SetText("Root Not Visible", "Root Visible"); this.rootVisible.ScaleX = 7.5f; this.okButton = new Button(mCursor); AddWindow(okButton); this.okButton.Text = "Save"; this.okButton.ScaleX = 4.5f; this.okButton.ScaleY = 1.3f; this.okButton.SetPositionTL(5f, 32f); this.okButton.Click += new GuiMessage(this.saveButtonClick); this.cancelButton = new Button(mCursor); AddWindow(cancelButton); this.cancelButton.Text = "Cancel"; this.cancelButton.ScaleX = 4.5f; this.cancelButton.ScaleY = 1.3f; this.cancelButton.SetPositionTL(16f, 32f); this.cancelButton.Click += new GuiMessage(this.cancelButtonClick); this.Visible = false; } private void cancelButtonClick(Window callingWindow) { this.Visible = false; } private void fillAvailableSprites(ComboBox comboBox) { comboBox.Clear(); SpriteList possibleSprites = new SpriteList(); if (this.sceneOrGroup.Text == "Entire Scene") { possibleSprites = GameData.Scene.Sprites; } else if (GameData.EditorLogic.CurrentSprites.Count != 0) { ((Sprite)GameData.EditorLogic.CurrentSprites[0].TopParent).GetAllDescendantsOneWay(possibleSprites); } comboBox.AddItem("<No Root>"); foreach (Sprite s in possibleSprites) { comboBox.AddItem(s.Name); } } private void fillAvailableTextures(ComboBox comboBox) { comboBox.Clear(); SpriteList possibleSprites = new SpriteList(); if (this.sceneOrGroup.Text == "Entire Scene") { possibleSprites = GameData.Scene.Sprites; } else if (GameData.EditorLogic.CurrentSprites.Count != 0) { ((Sprite)GameData.EditorLogic.CurrentSprites[0].TopParent).GetAllDescendantsOneWay(possibleSprites); } List<Texture2D> ta = new List<Texture2D>(); foreach (Sprite s in possibleSprites) { if (!ta.Contains(s.Texture)) { ta.Add(s.Texture); } } foreach (Texture2D t in ta) { comboBox.AddItem(FileManager.MakeRelative(t.Name, FileManager.RelativeDirectory)); } } public void FillComboBoxes() { SpriteList possibleSprites = new SpriteList(); if (this.sceneOrGroup.Text == "Entire Scene") { possibleSprites = GameData.Scene.Sprites; } else if (GameData.EditorLogic.CurrentSprites.Count != 0) { ((Sprite)GameData.EditorLogic.CurrentSprites[0].TopParent).GetAllDescendantsOneWay(possibleSprites); } this.rootSpriteComboBox.AddItem("<No Root>"); foreach (Sprite s in possibleSprites) { this.rootSpriteComboBox.AddItem(s.Name); } Sprite defaultRoot = possibleSprites.FindByName("root1"); if (defaultRoot == null) { defaultRoot = possibleSprites.FindByName("root"); } if (defaultRoot == null) { defaultRoot = possibleSprites.FindByName("Root"); } if (defaultRoot == null) { defaultRoot = possibleSprites.FindByName("Root1"); } if (defaultRoot == null) { defaultRoot = possibleSprites.FindWithNameContaining("root"); } if (defaultRoot == null) { defaultRoot = possibleSprites.FindWithNameContaining("Root"); } if (defaultRoot != null) { this.rootSpriteComboBox.Text = defaultRoot.Name; } else { this.rootSpriteComboBox.Text = "<No Root>"; } } } }
// InflaterInputStream.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // HISTORY // 11-08-2009 GeoffHart T9121 Added Multi-member gzip support #if ZIPLIB using System; using System.IO; #if !NETCF_1_0 using System.Security.Cryptography; #endif namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { /// <summary> /// An input buffer customised for use by <see cref="InflaterInputStream"/> /// </summary> /// <remarks> /// The buffer supports decryption of incoming data. /// </remarks> internal class InflaterInputBuffer { #region Constructors /// <summary> /// Initialise a new instance of <see cref="InflaterInputBuffer"/> with a default buffer size /// </summary> /// <param name="stream">The stream to buffer.</param> public InflaterInputBuffer(Stream stream) : this(stream , 4096) { } /// <summary> /// Initialise a new instance of <see cref="InflaterInputBuffer"/> /// </summary> /// <param name="stream">The stream to buffer.</param> /// <param name="bufferSize">The size to use for the buffer</param> /// <remarks>A minimum buffer size of 1KB is permitted. Lower sizes are treated as 1KB.</remarks> public InflaterInputBuffer(Stream stream, int bufferSize) { inputStream = stream; if ( bufferSize < 1024 ) { bufferSize = 1024; } rawData = new byte[bufferSize]; clearText = rawData; } #endregion /// <summary> /// Get the length of bytes bytes in the <see cref="RawData"/> /// </summary> public int RawLength { get { return rawLength; } } /// <summary> /// Get the contents of the raw data buffer. /// </summary> /// <remarks>This may contain encrypted data.</remarks> public byte[] RawData { get { return rawData; } } /// <summary> /// Get the number of useable bytes in <see cref="ClearText"/> /// </summary> public int ClearTextLength { get { return clearTextLength; } } /// <summary> /// Get the contents of the clear text buffer. /// </summary> public byte[] ClearText { get { return clearText; } } /// <summary> /// Get/set the number of bytes available /// </summary> public int Available { get { return available; } set { available = value; } } /// <summary> /// Call <see cref="Inflater.SetInput(byte[], int, int)"/> passing the current clear text buffer contents. /// </summary> /// <param name="inflater">The inflater to set input for.</param> public void SetInflaterInput(Inflater inflater) { if ( available > 0 ) { inflater.SetInput(clearText, clearTextLength - available, available); available = 0; } } /// <summary> /// Fill the buffer from the underlying input stream. /// </summary> public void Fill() { rawLength = 0; int toRead = rawData.Length; while (toRead > 0) { int count = inputStream.Read(rawData, rawLength, toRead); if ( count <= 0 ) { break; } rawLength += count; toRead -= count; } #if !NETCF_1_0 if ( cryptoTransform != null ) { clearTextLength = cryptoTransform.TransformBlock(rawData, 0, rawLength, clearText, 0); } else #endif { clearTextLength = rawLength; } available = clearTextLength; } /// <summary> /// Read a buffer directly from the input stream /// </summary> /// <param name="buffer">The buffer to fill</param> /// <returns>Returns the number of bytes read.</returns> public int ReadRawBuffer(byte[] buffer) { return ReadRawBuffer(buffer, 0, buffer.Length); } /// <summary> /// Read a buffer directly from the input stream /// </summary> /// <param name="outBuffer">The buffer to read into</param> /// <param name="offset">The offset to start reading data into.</param> /// <param name="length">The number of bytes to read.</param> /// <returns>Returns the number of bytes read.</returns> public int ReadRawBuffer(byte[] outBuffer, int offset, int length) { if ( length < 0 ) { throw new ArgumentOutOfRangeException("length"); } int currentOffset = offset; int currentLength = length; while ( currentLength > 0 ) { if ( available <= 0 ) { Fill(); if (available <= 0) { return 0; } } int toCopy = Math.Min(currentLength, available); System.Array.Copy(rawData, rawLength - (int)available, outBuffer, currentOffset, toCopy); currentOffset += toCopy; currentLength -= toCopy; available -= toCopy; } return length; } /// <summary> /// Read clear text data from the input stream. /// </summary> /// <param name="outBuffer">The buffer to add data to.</param> /// <param name="offset">The offset to start adding data at.</param> /// <param name="length">The number of bytes to read.</param> /// <returns>Returns the number of bytes actually read.</returns> public int ReadClearTextBuffer(byte[] outBuffer, int offset, int length) { if ( length < 0 ) { throw new ArgumentOutOfRangeException("length"); } int currentOffset = offset; int currentLength = length; while ( currentLength > 0 ) { if ( available <= 0 ) { Fill(); if (available <= 0) { return 0; } } int toCopy = Math.Min(currentLength, available); Array.Copy(clearText, clearTextLength - (int)available, outBuffer, currentOffset, toCopy); currentOffset += toCopy; currentLength -= toCopy; available -= toCopy; } return length; } /// <summary> /// Read a <see cref="byte"/> from the input stream. /// </summary> /// <returns>Returns the byte read.</returns> public int ReadLeByte() { if (available <= 0) { Fill(); if (available <= 0) { throw new ZipException("EOF in header"); } } byte result = rawData[rawLength - available]; available -= 1; return result; } /// <summary> /// Read an <see cref="short"/> in little endian byte order. /// </summary> /// <returns>The short value read case to an int.</returns> public int ReadLeShort() { return ReadLeByte() | (ReadLeByte() << 8); } /// <summary> /// Read an <see cref="int"/> in little endian byte order. /// </summary> /// <returns>The int value read.</returns> public int ReadLeInt() { return ReadLeShort() | (ReadLeShort() << 16); } /// <summary> /// Read a <see cref="long"/> in little endian byte order. /// </summary> /// <returns>The long value read.</returns> public long ReadLeLong() { return (uint)ReadLeInt() | ((long)ReadLeInt() << 32); } #if !NETCF_1_0 /// <summary> /// Get/set the <see cref="ICryptoTransform"/> to apply to any data. /// </summary> /// <remarks>Set this value to null to have no transform applied.</remarks> public ICryptoTransform CryptoTransform { set { cryptoTransform = value; if ( cryptoTransform != null ) { if ( rawData == clearText ) { if ( internalClearText == null ) { internalClearText = new byte[rawData.Length]; } clearText = internalClearText; } clearTextLength = rawLength; if ( available > 0 ) { cryptoTransform.TransformBlock(rawData, rawLength - available, available, clearText, rawLength - available); } } else { clearText = rawData; clearTextLength = rawLength; } } } #endif #region Instance Fields int rawLength; byte[] rawData; int clearTextLength; byte[] clearText; #if !NETCF_1_0 byte[] internalClearText; #endif int available; #if !NETCF_1_0 ICryptoTransform cryptoTransform; #endif Stream inputStream; #endregion } /// <summary> /// This filter stream is used to decompress data compressed using the "deflate" /// format. The "deflate" format is described in RFC 1951. /// /// This stream may form the basis for other decompression filters, such /// as the <see cref="ICSharpCode.SharpZipLib.GZip.GZipInputStream">GZipInputStream</see>. /// /// Author of the original java version : John Leuner. /// </summary> internal class InflaterInputStream : Stream { #region Constructors /// <summary> /// Create an InflaterInputStream with the default decompressor /// and a default buffer size of 4KB. /// </summary> /// <param name = "baseInputStream"> /// The InputStream to read bytes from /// </param> public InflaterInputStream(Stream baseInputStream) : this(baseInputStream, new Inflater(), 4096) { } /// <summary> /// Create an InflaterInputStream with the specified decompressor /// and a default buffer size of 4KB. /// </summary> /// <param name = "baseInputStream"> /// The source of input data /// </param> /// <param name = "inf"> /// The decompressor used to decompress data read from baseInputStream /// </param> public InflaterInputStream(Stream baseInputStream, Inflater inf) : this(baseInputStream, inf, 4096) { } /// <summary> /// Create an InflaterInputStream with the specified decompressor /// and the specified buffer size. /// </summary> /// <param name = "baseInputStream"> /// The InputStream to read bytes from /// </param> /// <param name = "inflater"> /// The decompressor to use /// </param> /// <param name = "bufferSize"> /// Size of the buffer to use /// </param> public InflaterInputStream(Stream baseInputStream, Inflater inflater, int bufferSize) { if (baseInputStream == null) { throw new ArgumentNullException("baseInputStream"); } if (inflater == null) { throw new ArgumentNullException("inflater"); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException("bufferSize"); } this.baseInputStream = baseInputStream; this.inf = inflater; inputBuffer = new InflaterInputBuffer(baseInputStream, bufferSize); } #endregion /// <summary> /// Get/set flag indicating ownership of underlying stream. /// When the flag is true <see cref="Close"/> will close the underlying stream also. /// </summary> /// <remarks> /// The default value is true. /// </remarks> public bool IsStreamOwner { get { return isStreamOwner; } set { isStreamOwner = value; } } /// <summary> /// Skip specified number of bytes of uncompressed data /// </summary> /// <param name ="count"> /// Number of bytes to skip /// </param> /// <returns> /// The number of bytes skipped, zero if the end of /// stream has been reached /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count">The number of bytes</paramref> to skip is less than or equal to zero. /// </exception> public long Skip(long count) { if (count <= 0) { throw new ArgumentOutOfRangeException("count"); } // v0.80 Skip by seeking if underlying stream supports it... if (baseInputStream.CanSeek) { baseInputStream.Seek(count, SeekOrigin.Current); return count; } else { int length = 2048; if (count < length) { length = (int) count; } byte[] tmp = new byte[length]; int readCount = 1; long toSkip = count; while ((toSkip > 0) && (readCount > 0) ) { if (toSkip < length) { length = (int)toSkip; } readCount = baseInputStream.Read(tmp, 0, length); toSkip -= readCount; } return count - toSkip; } } /// <summary> /// Clear any cryptographic state. /// </summary> protected void StopDecrypting() { #if !NETCF_1_0 inputBuffer.CryptoTransform = null; #endif } /// <summary> /// Returns 0 once the end of the stream (EOF) has been reached. /// Otherwise returns 1. /// </summary> public virtual int Available { get { return inf.IsFinished ? 0 : 1; } } /// <summary> /// Fills the buffer with more data to decompress. /// </summary> /// <exception cref="SharpZipBaseException"> /// Stream ends early /// </exception> protected void Fill() { // Protect against redundant calls if (inputBuffer.Available <= 0) { inputBuffer.Fill(); if (inputBuffer.Available <= 0) { throw new SharpZipBaseException("Unexpected EOF"); } } inputBuffer.SetInflaterInput(inf); } #region Stream Overrides /// <summary> /// Gets a value indicating whether the current stream supports reading /// </summary> public override bool CanRead { get { return baseInputStream.CanRead; } } /// <summary> /// Gets a value of false indicating seeking is not supported for this stream. /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Gets a value of false indicating that this stream is not writeable. /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// A value representing the length of the stream in bytes. /// </summary> public override long Length { get { return inputBuffer.RawLength; } } /// <summary> /// The current position within the stream. /// Throws a NotSupportedException when attempting to set the position /// </summary> /// <exception cref="NotSupportedException">Attempting to set the position</exception> public override long Position { get { return baseInputStream.Position; } set { throw new NotSupportedException("InflaterInputStream Position not supported"); } } /// <summary> /// Flushes the baseInputStream /// </summary> public override void Flush() { baseInputStream.Flush(); } /// <summary> /// Sets the position within the current stream /// Always throws a NotSupportedException /// </summary> /// <param name="offset">The relative offset to seek to.</param> /// <param name="origin">The <see cref="SeekOrigin"/> defining where to seek from.</param> /// <returns>The new position in the stream.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("Seek not supported"); } /// <summary> /// Set the length of the current stream /// Always throws a NotSupportedException /// </summary> /// <param name="value">The new length value for the stream.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void SetLength(long value) { throw new NotSupportedException("InflaterInputStream SetLength not supported"); } /// <summary> /// Writes a sequence of bytes to stream and advances the current position /// This method always throws a NotSupportedException /// </summary> /// <param name="buffer">Thew buffer containing data to write.</param> /// <param name="offset">The offset of the first byte to write.</param> /// <param name="count">The number of bytes to write.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException("InflaterInputStream Write not supported"); } /// <summary> /// Writes one byte to the current stream and advances the current position /// Always throws a NotSupportedException /// </summary> /// <param name="value">The byte to write.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void WriteByte(byte value) { throw new NotSupportedException("InflaterInputStream WriteByte not supported"); } /// <summary> /// Entry point to begin an asynchronous write. Always throws a NotSupportedException. /// </summary> /// <param name="buffer">The buffer to write data from</param> /// <param name="offset">Offset of first byte to write</param> /// <param name="count">The maximum number of bytes to write</param> /// <param name="callback">The method to be called when the asynchronous write operation is completed</param> /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests</param> /// <returns>An <see cref="System.IAsyncResult">IAsyncResult</see> that references the asynchronous write</returns> /// <exception cref="NotSupportedException">Any access</exception> public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException("InflaterInputStream BeginWrite not supported"); } /// <summary> /// Closes the input stream. When <see cref="IsStreamOwner"></see> /// is true the underlying stream is also closed. /// </summary> public override void Close() { if ( !isClosed ) { isClosed = true; if ( isStreamOwner ) { baseInputStream.Close(); } } } /// <summary> /// Reads decompressed data into the provided buffer byte array /// </summary> /// <param name ="buffer"> /// The array to read and decompress data into /// </param> /// <param name ="offset"> /// The offset indicating where the data should be placed /// </param> /// <param name ="count"> /// The number of bytes to decompress /// </param> /// <returns>The number of bytes read. Zero signals the end of stream</returns> /// <exception cref="SharpZipBaseException"> /// Inflater needs a dictionary /// </exception> public override int Read(byte[] buffer, int offset, int count) { if (inf.IsNeedingDictionary) { throw new SharpZipBaseException("Need a dictionary"); } int remainingBytes = count; while (true) { int bytesRead = inf.Inflate(buffer, offset, remainingBytes); offset += bytesRead; remainingBytes -= bytesRead; if (remainingBytes == 0 || inf.IsFinished) { break; } if ( inf.IsNeedingInput ) { Fill(); } else if ( bytesRead == 0 ) { throw new ZipException("Dont know what to do"); } } return count - remainingBytes; } #endregion #region Instance Fields /// <summary> /// Decompressor for this stream /// </summary> protected Inflater inf; /// <summary> /// <see cref="InflaterInputBuffer">Input buffer</see> for this stream. /// </summary> protected InflaterInputBuffer inputBuffer; /// <summary> /// Base stream the inflater reads from. /// </summary> private Stream baseInputStream; /// <summary> /// The compressed size /// </summary> protected long csize; /// <summary> /// Flag indicating wether this instance has been closed or not. /// </summary> bool isClosed; /// <summary> /// Flag indicating wether this instance is designated the stream owner. /// When closing if this flag is true the underlying stream is closed. /// </summary> bool isStreamOwner = true; #endregion } } #endif
//css_dbg /t:exe, /args:{00020813-0000-0000-c000-000000000046} excell; using System; using System.IO; using System.Text; using Microsoft.Win32; using System.Reflection; using System.Windows.Forms; using System.Reflection.Emit; using System.Runtime.InteropServices; using System.Diagnostics; using CSScriptLibrary; using csscript; class Scripting { class Script { static bool activeX = false; [STAThread] static public void Main(string[] args) { //Debug.Assert(false); const string usage = "Usage: cscscript com <<file1> <file2> [/r] [/ax]> | <<file1> /u> | <<name>|<guid> <file2> [/ax]>...\n" + "Converterts type library of the COM Server to assembly.\n" + "<file1> - the name of the COM Server file\n" + "<file2> - the name of the assembly file (.dll is a default extension)\n" + "<name> - VersionIndependentProgID or ProgID of the COM Server\n" + "<guid> - GUID of the COM Server ({XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}).\n" + "/ax - treats the COM library as an ActiveX COM and generate Windows Forms Control assembly\n" + "/r - registers COM dll before importing\n" + "/u - unregisters COM dll\n"; try { //System.Diagnostics.Debug.Assert(false); if (args.Length < 2) { Console.WriteLine(usage); return; } string input = ""; string output = ""; bool register = false, unregister = false; foreach (string arg in args) { if (arg.ToLower() == "/u") unregister = true; else if (arg.ToLower() == "/r") register = true; else if (arg.ToLower() == "/ax") Script.activeX = true; else if (input == "") input = arg; else if (output == "") output = arg; } string ide = Environment.GetEnvironmentVariable("CSScriptDebugging"); if (!File.Exists(input)) { if (File.Exists(Path.Combine(Path.GetDirectoryName(EntryScript), input))) input = Path.Combine(Path.GetDirectoryName(EntryScript), input); } else input = Path.GetFullPath(input); if (unregister) { new DllRegServer(input).UnRegister(); } else { //MessageBox.Show(input);//for testing if (register) { new DllRegServer(input).Register(); ImportTlbFromFile(input, ResolveAsmLocation(output)); } else { if (File.Exists(input) || input.ToLower().EndsWith(".dll")) ImportTlbFromFile(input, ResolveAsmLocation(output)); else if (input.StartsWith("{")) ImportTlbFromGUID(input, ResolveAsmLocation(output)); else ImportTlbFromName(input, ResolveAsmLocation(output)); } } } catch (Exception ex) { Console.WriteLine(ex.Message); throw ex; } } static string EntryScript { get { if (Environment.GetEnvironmentVariable("EntryScript") != null) //standalone execution return Environment.GetEnvironmentVariable("EntryScript"); else if (CSSEnvironment.PrimaryScriptFile != null) //hosted execution return CSSEnvironment.PrimaryScriptFile; else throw new Exception("Error: Cannot obtain the entry script path"); } } static string ResolveAsmLocation(string file) { //System.Diagnostics.Debug.Assert(false); if (CSScript.GlobalSettings.HideAutoGeneratedFiles == Settings.HideOptions.HideAll) return Path.Combine(CSSEnvironment.GetCacheDirectory(EntryScript), Path.GetFileName(file)); else return Path.Combine(Path.GetDirectoryName(EntryScript), file); } static void ImportTlbFromFile(string file, string asmName) { string com = Path.GetFullPath(file); string asm = Path.GetFullPath(asmName.EndsWith(".dll") ? asmName : asmName + ".dll"); //MessageBox.Show(asm); //for testing if (!File.Exists(file)) throw new FileNotFoundException("The file cannot be found", file); FileInfo comInfo = new FileInfo(com); if (File.Exists(asm)) { if (new FileInfo(asm).CreationTimeUtc != comInfo.CreationTimeUtc) File.Delete(asm); else return; } RunApp(GetTlbImpApp(), "\"" + com + "\" \"/out:" + asm + "\""); if (!File.Exists(asm)) throw new Exception("Specified file cannot be imported."); new FileInfo(asm).CreationTimeUtc = comInfo.CreationTimeUtc; } static void ImportTlbFromName(string name, string asmName) { bool versionIndependant = (name.Split(".".ToCharArray()).Length == 2); bool anyVersion = name.EndsWith(".*"); if (anyVersion) name = name.Replace(".*", ""); object progIDValue = null; using (RegistryKey CLSIDKey = Registry.ClassesRoot.OpenSubKey(@"CLSID")) foreach (string guid in CLSIDKey.GetSubKeyNames()) using (RegistryKey progIDKey = CLSIDKey.OpenSubKey(guid + "\\" + (versionIndependant ? "VersionIndependentProgID" : "ProgID"))) if (progIDKey != null && (progIDValue = progIDKey.GetValue("")) != null) if (anyVersion ? progIDKey.GetValue("").ToString().ToUpper().StartsWith(name.ToUpper()) : progIDKey.GetValue("").ToString().ToUpper() == name.ToUpper()) { ImportTlbFromFile(CLSIDKey.OpenSubKey(guid + "\\InprocServer32").GetValue("").ToString(), asmName); return; } if (versionIndependant) ImportTlbFromName(name + ".*", asmName); //if not found as version independent, try to find any version else throw new Exception("Cannot find COM object " + name); } static void ImportTlbFromGUID(string guid, string asmName) { //System.Diagnostics.Debug.Assert(false); using (RegistryKey guidKey = Registry.ClassesRoot.OpenSubKey(@"CLSID\\" + guid)) { if (guidKey != null) { ImportTlbFromFile(guidKey.OpenSubKey("InprocServer32").GetValue("").ToString(), asmName); return; } else { using (RegistryKey typeLibKey = Registry.ClassesRoot.OpenSubKey(@"TypeLib\" + guid)) { if (typeLibKey != null) { string[] maxVer = new string[] { "1", "0" }; foreach (string subKey in typeLibKey.GetSubKeyNames()) { string[] ver = subKey.Split('.'); if (Convert.ToInt32(ver[0]) > Convert.ToInt32(maxVer[0])) { maxVer = ver; } else if (Convert.ToInt32(ver[1]) > Convert.ToInt32(maxVer[1])) { maxVer = ver; } } using (RegistryKey majorVesruionKey = typeLibKey.OpenSubKey(maxVer[0] + "." + maxVer[1])) { int maxMinorVer = 0; int minorVer = 0; foreach (string subKey in majorVesruionKey.GetSubKeyNames()) if (int.TryParse(subKey, out minorVer)) if (maxMinorVer < minorVer) maxMinorVer = minorVer; string majorVesruion = maxVer[0] + "." + maxVer[1]; ImportTlbFromFile(typeLibKey.OpenSubKey(majorVesruion + "\\" + maxMinorVer + "\\win32").GetValue("").ToString(), asmName); return; } } } } } throw new Exception("Cannot find COM object " + guid); } static string GetTlbImpApp() { string appName = Script.activeX ? "AxImp.exe" : "TlbImp.exe"; //In the future it needs to be replaced with the automatic search for the TlbImp.exe string[] version = Environment.Version.ToString().Split(".".ToCharArray()); if (version[0] == "4") return Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib\tools\v4.0\" + appName); if (version[0] == "2") return Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib\tools\v2.0\" + appName); if (version[0] == "1" && version[1] == "1") return Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib\tools\v1.1\" + appName); else return "Location of the " + appName + " is unknown."; } static string RunApp(string app, string args) { Process myProcess = new Process(); myProcess.StartInfo.FileName = app; myProcess.StartInfo.Arguments = args; myProcess.StartInfo.WorkingDirectory = Environment.CurrentDirectory; myProcess.StartInfo.UseShellExecute = false; myProcess.StartInfo.RedirectStandardOutput = true; myProcess.StartInfo.CreateNoWindow = true; myProcess.Start(); StringBuilder sb = new StringBuilder(); string line = null; while (null != (line = myProcess.StandardOutput.ReadLine())) { sb.Append(line); sb.Append("\r\n"); } myProcess.WaitForExit(); return sb.ToString(); } } /// <summary> /// This class was kindly provided by Mattias Sjogren (http://www.msjogren.net/dotnet/eng/samples/dotnet_dynpinvoke.asp) /// </summary> public class DllRegServer { bool IsWin64Process() { return "".GetType().Assembly.Location.IndexOf("Framework64") != -1; } private string m_sDllFile; private static ModuleBuilder s_mb; private Type m_tDllReg; public DllRegServer(string dllFile) { if (IsWin64Process()) { //should run System32\regsvr32.exe or/and SysWOW64/regsvr32.exe as an external process //as COM server dll may by of x32 and cannot be loaded in to current x63 process memory for //invoking DllRegisterServer/DllUnregisterServer MessageBox.Show("COM.cs cannot do COM Servr registrtions on x64."); throw new Exception("COM.cs cannot do COM Servr registrtions on x64."); } m_sDllFile = Path.GetFullPath(dllFile); CreateDllRegType(); } public void Register() { InternalRegServer(false); } public void UnRegister() { InternalRegServer(true); } private void InternalRegServer(bool fUnreg) { string sMemberName = fUnreg ? "DllUnregisterServer" : "DllRegisterServer"; int hr = (int)m_tDllReg.InvokeMember(sMemberName, BindingFlags.InvokeMethod, null, Activator.CreateInstance(m_tDllReg), null); if (hr != 0) Marshal.ThrowExceptionForHR(hr); } private void CreateDllRegType() { if (s_mb == null) { // Create dynamic assembly AssemblyName an = new AssemblyName(); an.Name = "DllRegServerAssembly" + Guid.NewGuid().ToString("N"); AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run); // Add module to assembly s_mb = ab.DefineDynamicModule("DllRegServerModule"); } // Add class to module TypeBuilder tb = s_mb.DefineType("DllRegServerClass" + Guid.NewGuid().ToString("N")); MethodBuilder meb; // Add PInvoke methods to class meb = tb.DefinePInvokeMethod("DllRegisterServer", m_sDllFile, MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl, CallingConventions.Standard, typeof(int), null, CallingConvention.StdCall, CharSet.Auto); // Apply preservesig metadata attribute so we can handle return HRESULT ourselves meb.SetImplementationFlags(MethodImplAttributes.PreserveSig | meb.GetMethodImplementationFlags()); meb = tb.DefinePInvokeMethod("DllUnregisterServer", m_sDllFile, MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl, CallingConventions.Standard, typeof(int), null, CallingConvention.StdCall, CharSet.Auto); // Apply preservesig metadata attribute so we can handle return HRESULT ourselves meb.SetImplementationFlags(MethodImplAttributes.PreserveSig | meb.GetMethodImplementationFlags()); // Create the type m_tDllReg = tb.CreateType(); } } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ namespace NPOI.POIFS.EventFileSystem { using System; using System.Collections; using System.Collections.Generic; using System.IO; using NPOI.POIFS.FileSystem; using NPOI.POIFS.Properties; using NPOI.POIFS.Storage; /// <summary> /// An event-driven Reader for POIFS file systems. Users of this class /// first Create an instance of it, then use the RegisterListener /// methods to Register POIFSReaderListener instances for specific /// documents. Once all the listeners have been Registered, the Read() /// method is called, which results in the listeners being notified as /// their documents are Read. /// @author Marc Johnson (mjohnson at apache dot org) /// </summary> internal class POIFSReader { public event POIFSReaderEventHandler StreamReaded; private POIFSReaderRegistry registry; private bool registryClosed; protected virtual void OnStreamReaded(POIFSReaderEventArgs e) { if (StreamReaded != null) { StreamReaded(this, e); } } /// <summary> /// Initializes a new instance of the <see cref="POIFSReader"/> class. /// </summary> public POIFSReader() { registry = new POIFSReaderRegistry(); registryClosed = false; } /// <summary> /// Read from an InputStream and Process the documents we Get /// </summary> /// <param name="stream">the InputStream from which to Read the data</param> /// <returns>POIFSDocument list</returns> public List<DocumentDescriptor> Read(Stream stream) { registryClosed = true; // Read the header block from the stream HeaderBlock header_block = new HeaderBlock(stream); // Read the rest of the stream into blocks RawDataBlockList data_blocks = new RawDataBlockList(stream, header_block.BigBlockSize); // Set up the block allocation table (necessary for the // data_blocks to be manageable new BlockAllocationTableReader(header_block.BigBlockSize, header_block.BATCount, header_block.BATArray, header_block.XBATCount, header_block.XBATIndex, data_blocks); // Get property table from the document PropertyTable properties = new PropertyTable(header_block, data_blocks); // Process documents return ProcessProperties(SmallBlockTableReader.GetSmallDocumentBlocks (header_block.BigBlockSize, data_blocks, properties.Root, header_block.SBATStart), data_blocks, properties.Root.Children, new POIFSDocumentPath() ); } /** * Register a POIFSReaderListener for all documents * * @param listener the listener to be registered * * @exception NullPointerException if listener is null * @exception IllegalStateException if read() has already been * called */ public void RegisterListener(POIFSReaderListener listener) { if (listener == null) { throw new NullReferenceException(); } if (registryClosed) { throw new InvalidOperationException(); } registry.RegisterListener(listener); } /** * Register a POIFSReaderListener for a document in the root * directory * * @param listener the listener to be registered * @param name the document name * * @exception NullPointerException if listener is null or name is * null or empty * @exception IllegalStateException if read() has already been * called */ public void RegisterListener(POIFSReaderListener listener, String name) { RegisterListener(listener, null, name); } /** * Register a POIFSReaderListener for a document in the specified * directory * * @param listener the listener to be registered * @param path the document path; if null, the root directory is * assumed * @param name the document name * * @exception NullPointerException if listener is null or name is * null or empty * @exception IllegalStateException if read() has already been * called */ public void RegisterListener(POIFSReaderListener listener, POIFSDocumentPath path, String name) { if ((listener == null) || (name == null) || (name.Length == 0)) { throw new NullReferenceException(); } if (registryClosed) { throw new InvalidOperationException(); } registry.RegisterListener(listener, (path == null) ? new POIFSDocumentPath() : path, name); } /// <summary> /// Processes the properties. /// </summary> /// <param name="small_blocks">The small_blocks.</param> /// <param name="big_blocks">The big_blocks.</param> /// <param name="properties">The properties.</param> /// <param name="path">The path.</param> /// <returns></returns> private List<DocumentDescriptor> ProcessProperties(BlockList small_blocks, BlockList big_blocks, IEnumerator properties, POIFSDocumentPath path) { List<DocumentDescriptor> documents = new List<DocumentDescriptor>(); while (properties.MoveNext()) { Property property = (Property)properties.Current; String name = property.Name; if (property.IsDirectory) { POIFSDocumentPath new_path = new POIFSDocumentPath(path, new String[] { name }); ProcessProperties( small_blocks, big_blocks, ((DirectoryProperty)property).Children, new_path); } else { int startBlock = property.StartBlock; IEnumerator listeners = registry.GetListeners(path, name); POIFSDocument document = null; if (listeners.MoveNext()) { int size = property.Size; if (property.ShouldUseSmallBlocks) { document = new POIFSDocument(name, small_blocks .FetchBlocks(startBlock, -1), size); } else { document = new POIFSDocument(name, big_blocks .FetchBlocks(startBlock, -1), size); } POIFSReaderListener listener = (POIFSReaderListener)listeners.Current; listener.ProcessPOIFSReaderEvent( new POIFSReaderEvent( new DocumentInputStream(document), path, name)); while (listeners.MoveNext()) { listener = (POIFSReaderListener)listeners.Current; listener.ProcessPOIFSReaderEvent( new POIFSReaderEvent( new DocumentInputStream(document), path, name)); } } else { // consume the document's data and discard it if (property.ShouldUseSmallBlocks) { small_blocks.FetchBlocks(startBlock, -1); } else { big_blocks.FetchBlocks(startBlock, -1); } documents.Add( new DocumentDescriptor(path, name)); //fire event //OnStreamReaded(new POIFSReaderEventArgs(name, path, document)); } } } return documents; } } }
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Collections.Generic; using System.Globalization; using NodaTime.Calendars; using NodaTime.Globalization; using NodaTime.Test.Text; using NUnit.Framework; namespace NodaTime.Test.Globalization { public class NodaFormatInfoTest { private static readonly CultureInfo enUs = CultureInfo.GetCultureInfo("en-US"); private static readonly CultureInfo enGb = CultureInfo.GetCultureInfo("en-GB"); // Just check we can actually build a NodaFormatInfo for every culture, outside // text-specific tests. [Test] [TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))] public void ConvertCulture(CultureInfo culture) { NodaFormatInfo.GetFormatInfo(culture); } [Test] public void TestCachingWithReadOnly() { var original = new CultureInfo("en-US"); // Use a read-only wrapper so that it gets cached var wrapper = CultureInfo.ReadOnly(original); var nodaWrapper1 = NodaFormatInfo.GetFormatInfo(wrapper); var nodaWrapper2 = NodaFormatInfo.GetFormatInfo(wrapper); Assert.AreSame(nodaWrapper1, nodaWrapper2); } [Test] public void TestCachingWithClonedCulture() { var original = new CultureInfo("en-US"); var clone = (CultureInfo) original.Clone(); Assert.AreEqual(original.Name, clone.Name); var dayNames = clone.DateTimeFormat.DayNames; dayNames[1] = "@@@"; clone.DateTimeFormat.DayNames = dayNames; // Fool Noda Time into believing both are read-only, so it can use a cache... original = CultureInfo.ReadOnly(original); clone = CultureInfo.ReadOnly(clone); var nodaOriginal = NodaFormatInfo.GetFormatInfo(original); var nodaClone = NodaFormatInfo.GetFormatInfo(clone); Assert.AreEqual(original.DateTimeFormat.DayNames[1], nodaOriginal.LongDayNames[1]); Assert.AreEqual(clone.DateTimeFormat.DayNames[1], nodaClone.LongDayNames[1]); // Just check we made a difference... Assert.AreNotEqual(nodaOriginal.LongDayNames[1], nodaClone.LongDayNames[1]); } [Test] public void TestConstructor() { var info = new NodaFormatInfo(enUs); Assert.AreSame(enUs, info.CultureInfo); Assert.NotNull(info.DateTimeFormat); Assert.AreEqual(":", info.TimeSeparator); Assert.AreEqual("/", info.DateSeparator); Assert.IsInstanceOf<string>(info.OffsetPatternLong); Assert.IsInstanceOf<string>(info.OffsetPatternMedium); Assert.IsInstanceOf<string>(info.OffsetPatternShort); Assert.AreEqual("NodaFormatInfo[en-US]", info.ToString()); } [Test] public void TestConstructor_null() { Assert.Throws<ArgumentNullException>(() => new NodaFormatInfo(null!)); } [Test] public void TestDateTimeFormat() { var format = DateTimeFormatInfo.InvariantInfo; var info = new NodaFormatInfo(enUs); Assert.AreNotEqual(format, info.DateTimeFormat); } [Test] public void TestGetFormatInfo() { NodaFormatInfo.ClearCache(); var info1 = NodaFormatInfo.GetFormatInfo(enUs); Assert.NotNull(info1); var info2 = NodaFormatInfo.GetFormatInfo(enUs); Assert.AreSame(info1, info2); var info3 = NodaFormatInfo.GetFormatInfo(enGb); Assert.AreNotSame(info1, info3); } [Test] public void TestGetFormatInfo_null() { NodaFormatInfo.ClearCache(); Assert.Throws<ArgumentNullException>(() => NodaFormatInfo.GetFormatInfo(null!)); } [Test] public void TestGetInstance_CultureInfo() { NodaFormatInfo.ClearCache(); using (CultureSaver.SetCultures(enUs, FailingCultureInfo.Instance)) { var actual = NodaFormatInfo.GetInstance(enGb); Assert.AreSame(enGb, actual.CultureInfo); } } [Test] public void TestGetInstance_UnusableType() { NodaFormatInfo.ClearCache(); Assert.Throws<ArgumentException>(() => NodaFormatInfo.GetInstance(CultureInfo.InvariantCulture.NumberFormat)); } [Test] public void TestGetInstance_DateTimeFormatInfo() { NodaFormatInfo.ClearCache(); using (CultureSaver.SetCultures(enUs, FailingCultureInfo.Instance)) { var info = NodaFormatInfo.GetInstance(enGb.DateTimeFormat); Assert.AreEqual(enGb.DateTimeFormat, info.DateTimeFormat); Assert.AreEqual(CultureInfo.InvariantCulture, info.CultureInfo); } } [Test] public void TestGetInstance_null() { NodaFormatInfo.ClearCache(); using (CultureSaver.SetCultures(enUs, FailingCultureInfo.Instance)) { var info = NodaFormatInfo.GetInstance(null); Assert.AreEqual(CultureInfo.CurrentCulture, info.CultureInfo); } using (CultureSaver.SetCultures(enGb, FailingCultureInfo.Instance)) { var info = NodaFormatInfo.GetInstance(null); Assert.AreEqual(CultureInfo.CurrentCulture, info.CultureInfo); } } [Test] public void TestOffsetPatternLong() { const string pattern = "This is a test"; var info = new NodaFormatInfo(enUs); Assert.AreNotEqual(pattern, info.OffsetPatternLong); } [Test] public void TestOffsetPatternMedium() { const string pattern = "This is a test"; var info = new NodaFormatInfo(enUs); Assert.AreNotEqual(pattern, info.OffsetPatternMedium); } [Test] public void TestOffsetPatternShort() { const string pattern = "This is a test"; var info = new NodaFormatInfo(enUs); Assert.AreNotEqual(pattern, info.OffsetPatternShort); } [Test] public void TestGetEraNames() { var info = NodaFormatInfo.GetFormatInfo(enUs); IReadOnlyList<string> names = info.GetEraNames(Era.BeforeCommon); CollectionAssert.AreEqual(new[] { "B.C.E.", "B.C.", "BCE", "BC" }, names); } [Test] public void TestGetEraNames_NoSuchEra() { var info = NodaFormatInfo.GetFormatInfo(enUs); Assert.AreEqual(0, info.GetEraNames(new Era("Ignored", "NonExistentResource")).Count); } [Test] public void TestEraGetNames_Null() { var info = NodaFormatInfo.GetFormatInfo(enUs); Assert.Throws<ArgumentNullException>(() => info.GetEraNames(null!)); } [Test] public void TestGetEraPrimaryName() { var info = NodaFormatInfo.GetFormatInfo(enUs); Assert.AreEqual("B.C.", info.GetEraPrimaryName(Era.BeforeCommon)); } [Test] public void TestGetEraPrimaryName_NoSuchEra() { var info = NodaFormatInfo.GetFormatInfo(enUs); Assert.AreEqual("", info.GetEraPrimaryName(new Era("Ignored", "NonExistentResource"))); } [Test] public void TestEraGetEraPrimaryName_Null() { var info = NodaFormatInfo.GetFormatInfo(enUs); Assert.Throws<ArgumentNullException>(() => info.GetEraPrimaryName(null!)); } [Test] public void TestIntegerGenitiveMonthNames() { // Emulate behavior of Mono 3.0.6 var culture = (CultureInfo) CultureInfo.InvariantCulture.Clone(); culture.DateTimeFormat.MonthGenitiveNames = new[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }; culture.DateTimeFormat.AbbreviatedMonthGenitiveNames = new[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }; var info = NodaFormatInfo.GetFormatInfo(culture); CollectionAssert.AreEqual(info.LongMonthGenitiveNames, info.LongMonthNames); CollectionAssert.AreEqual(info.ShortMonthGenitiveNames, info.ShortMonthNames); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace SqlKata { public partial class Query : BaseQuery<Query> { private string comment; public bool IsDistinct { get; set; } = false; public string QueryAlias { get; set; } public string Method { get; set; } = "select"; public List<Include> Includes = new List<Include>(); public Dictionary<string, object> Variables = new Dictionary<string, object>(); public Query() : base() { } public Query(string table, string comment = null) : base() { From(table); Comment(comment); } public string GetComment() => comment ?? ""; public bool HasOffset(string engineCode = null) => GetOffset(engineCode) > 0; public bool HasLimit(string engineCode = null) => GetLimit(engineCode) > 0; internal int GetOffset(string engineCode = null) { engineCode = engineCode ?? EngineScope; var offset = this.GetOneComponent<OffsetClause>("offset", engineCode); return offset?.Offset ?? 0; } internal int GetLimit(string engineCode = null) { engineCode = engineCode ?? EngineScope; var limit = this.GetOneComponent<LimitClause>("limit", engineCode); return limit?.Limit ?? 0; } public override Query Clone() { var clone = base.Clone(); clone.Parent = Parent; clone.QueryAlias = QueryAlias; clone.IsDistinct = IsDistinct; clone.Method = Method; clone.Includes = Includes; clone.Variables = Variables; return clone; } public Query As(string alias) { QueryAlias = alias; return this; } /// <summary> /// Sets a comment for the query. /// </summary> /// <param name="comment">The comment.</param> /// <returns></returns> public Query Comment(string comment) { this.comment = comment; return this; } public Query For(string engine, Func<Query, Query> fn) { EngineScope = engine; var result = fn.Invoke(this); // reset the engine EngineScope = null; return result; } public Query With(Query query) { // Clear query alias and add it to the containing clause if (string.IsNullOrWhiteSpace(query.QueryAlias)) { throw new InvalidOperationException("No Alias found for the CTE query"); } query = query.Clone(); var alias = query.QueryAlias.Trim(); // clear the query alias query.QueryAlias = null; return AddComponent("cte", new QueryFromClause { Query = query, Alias = alias, }); } public Query With(Func<Query, Query> fn) { return With(fn.Invoke(new Query())); } public Query With(string alias, Query query) { return With(query.As(alias)); } public Query With(string alias, Func<Query, Query> fn) { return With(alias, fn.Invoke(new Query())); } /// <summary> /// Constructs an ad-hoc table of the given data as a CTE. /// </summary> public Query With(string alias, IEnumerable<string> columns, IEnumerable<IEnumerable<object>> valuesCollection) { var columnsList = columns?.ToList(); var valuesCollectionList = valuesCollection?.ToList(); if ((columnsList?.Count ?? 0) == 0 || (valuesCollectionList?.Count ?? 0) == 0) { throw new InvalidOperationException("Columns and valuesCollection cannot be null or empty"); } var clause = new AdHocTableFromClause() { Alias = alias, Columns = columnsList, Values = new List<object>(), }; foreach (var values in valuesCollectionList) { var valuesList = values.ToList(); if (columnsList.Count != valuesList.Count) { throw new InvalidOperationException("Columns count should be equal to each Values count"); } clause.Values.AddRange(valuesList); } return AddComponent("cte", clause); } public Query WithRaw(string alias, string sql, params object[] bindings) { return AddComponent("cte", new RawFromClause { Alias = alias, Expression = sql, Bindings = bindings, }); } public Query Limit(int value) { var newClause = new LimitClause { Limit = value }; return AddOrReplaceComponent("limit", newClause); } public Query Offset(int value) { var newClause = new OffsetClause { Offset = value }; return AddOrReplaceComponent("offset", newClause); } /// <summary> /// Alias for Limit /// </summary> /// <param name="limit"></param> /// <returns></returns> public Query Take(int limit) { return Limit(limit); } /// <summary> /// Alias for Offset /// </summary> /// <param name="offset"></param> /// <returns></returns> public Query Skip(int offset) { return Offset(offset); } /// <summary> /// Set the limit and offset for a given page. /// </summary> /// <param name="page"></param> /// <param name="perPage"></param> /// <returns></returns> public Query ForPage(int page, int perPage = 15) { return Skip((page - 1) * perPage).Take(perPage); } public Query Distinct() { IsDistinct = true; return this; } /// <summary> /// Apply the callback's query changes if the given "condition" is true. /// </summary> /// <param name="condition"></param> /// <param name="whenTrue">Invoked when the condition is true</param> /// <param name="whenFalse">Optional, invoked when the condition is false</param> /// <returns></returns> public Query When(bool condition, Func<Query, Query> whenTrue, Func<Query, Query> whenFalse = null) { if (condition && whenTrue != null) { return whenTrue.Invoke(this); } if (!condition && whenFalse != null) { return whenFalse.Invoke(this); } return this; } /// <summary> /// Apply the callback's query changes if the given "condition" is false. /// </summary> /// <param name="condition"></param> /// <param name="callback"></param> /// <returns></returns> public Query WhenNot(bool condition, Func<Query, Query> callback) { if (!condition) { return callback.Invoke(this); } return this; } public Query OrderBy(params string[] columns) { foreach (var column in columns) { AddComponent("order", new OrderBy { Column = column, Ascending = true }); } return this; } public Query OrderByDesc(params string[] columns) { foreach (var column in columns) { AddComponent("order", new OrderBy { Column = column, Ascending = false }); } return this; } public Query OrderByRaw(string expression, params object[] bindings) { return AddComponent("order", new RawOrderBy { Expression = expression, Bindings = Helper.Flatten(bindings).ToArray() }); } public Query OrderByRandom(string seed) { return AddComponent("order", new OrderByRandom { }); } public Query GroupBy(params string[] columns) { foreach (var column in columns) { AddComponent("group", new Column { Name = column }); } return this; } public Query GroupByRaw(string expression, params object[] bindings) { AddComponent("group", new RawColumn { Expression = expression, Bindings = bindings, }); return this; } public override Query NewQuery() { return new Query(); } public Query Include(string relationName, Query query, string foreignKey = null, string localKey = "Id", bool isMany = false) { Includes.Add(new Include { Name = relationName, LocalKey = localKey, ForeignKey = foreignKey, Query = query, IsMany = isMany, }); return this; } public Query IncludeMany(string relationName, Query query, string foreignKey = null, string localKey = "Id") { return Include(relationName, query, foreignKey, localKey, isMany: true); } private static readonly ConcurrentDictionary<Type, PropertyInfo[]> CacheDictionaryProperties = new ConcurrentDictionary<Type, PropertyInfo[]>(); /// <summary> /// Define a variable to be used within the query /// </summary> /// <param name="variable"></param> /// <param name="value"></param> /// <returns></returns> public Query Define(string variable, object value) { Variables.Add(variable, value); return this; } public object FindVariable(string variable) { var found = Variables.ContainsKey(variable); if (found) { return Variables[variable]; } if (Parent != null) { return (Parent as Query).FindVariable(variable); } throw new Exception($"Variable '{variable}' not found"); } /// <summary> /// Gather a list of key-values representing the properties of the object and their values. /// </summary> /// <param name="data">The plain C# object</param> /// <param name="considerKeys"> /// When true it will search for properties with the [Key] attribute /// and will add it automatically to the Where clause /// </param> /// <returns></returns> private IEnumerable<KeyValuePair<string, object>> BuildKeyValuePairsFromObject(object data, bool considerKeys = false) { var dictionary = new Dictionary<string, object>(); var props = CacheDictionaryProperties.GetOrAdd(data.GetType(), type => type.GetRuntimeProperties().ToArray()); foreach (var property in props) { if (property.GetCustomAttribute(typeof(IgnoreAttribute)) != null) { continue; } var value = property.GetValue(data); var colAttr = property.GetCustomAttribute(typeof(ColumnAttribute)) as ColumnAttribute; var name = colAttr?.Name ?? property.Name; dictionary.Add(name, value); if (considerKeys && colAttr != null) { if ((colAttr as KeyAttribute) != null) { this.Where(name, value); } } } return dictionary; } } }
// Copyright 2008 Adrian Akison // Distributed under license terms of CPOL http://www.codeproject.com/info/cpol10.aspx using System; using System.Collections.Generic; using System.Text; namespace RaidScheduler.Domain.DomainModels.Combinations { /// <summary> /// Variations defines a meta-collection, typically a list of lists, of all possible /// ordered subsets of a particular size from the set of values. /// This list is enumerable and allows the scanning of all possible Variations using a simple /// foreach() loop even though the variations are not all in memory. /// </summary> /// <remarks> /// The MetaCollectionType parameter of the constructor allows for the creation of /// normal Variations and Variations with Repetition. /// /// When given an input collect {A B C} and lower index of 2, the following sets are generated: /// MetaCollectionType.WithoutRepetition generates 6 sets: => /// {A B}, {A B}, {B A}, {B C}, {C A}, {C B} /// MetaCollectionType.WithRepetition generates 9 sets: /// {A A}, {A B}, {A B}, {B A}, {B B }, {B C}, {C A}, {C B}, {C C} /// /// The equality of multiple inputs is not considered when generating variations. /// </remarks> /// <typeparam name="T">The type of the values within the list.</typeparam> public class Variations<T> : IMetaCollection<T> { #region Constructors /// <summary> /// No default constructor, must provided a list of values and size. /// </summary> protected Variations() { ; } /// <summary> /// Create a variation set from the indicated list of values. /// The upper index is calculated as values.Count, the lower index is specified. /// Collection type defaults to MetaCollectionType.WithoutRepetition /// </summary> /// <param name="values">List of values to select Variations from.</param> /// <param name="lowerIndex">The size of each variation set to return.</param> public Variations(IList<T> values, int lowerIndex) { Initialize(values, lowerIndex, GenerateOption.WithoutRepetition); } /// <summary> /// Create a variation set from the indicated list of values. /// The upper index is calculated as values.Count, the lower index is specified. /// </summary> /// <param name="values">List of values to select variations from.</param> /// <param name="lowerIndex">The size of each vatiation set to return.</param> /// <param name="type">Type indicates whether to use repetition in set generation.</param> public Variations(IList<T> values, int lowerIndex, GenerateOption type) { Initialize(values, lowerIndex, type); } #endregion #region IEnumerable Interface /// <summary> /// Gets an enumerator for the collection of Variations. /// </summary> /// <returns>The enumerator.</returns> public IEnumerator<IList<T>> GetEnumerator() { if(Type == GenerateOption.WithRepetition) { return new EnumeratorWithRepetition(this); } else { return new EnumeratorWithoutRepetition(this); } } /// <summary> /// Gets an enumerator for the collection of Variations. /// </summary> /// <returns>The enumerator.</returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { if(Type == GenerateOption.WithRepetition) { return new EnumeratorWithRepetition(this); } else { return new EnumeratorWithoutRepetition(this); } } #endregion #region Enumerator Inner Class /// <summary> /// An enumerator for Variations when the type is set to WithRepetition. /// </summary> public class EnumeratorWithRepetition : IEnumerator<IList<T>> { #region Constructors /// <summary> /// Construct a enumerator with the parent object. /// </summary> /// <param name="source">The source Variations object.</param> public EnumeratorWithRepetition(Variations<T> source) { myParent = source; Reset(); } #endregion #region IEnumerator interface /// <summary> /// Resets the Variations enumerator to the first variation. /// </summary> public void Reset() { myCurrentList = null; myListIndexes = null; } /// <summary> /// Advances to the next variation. /// </summary> /// <returns>True if successfully moved to next variation, False if no more variations exist.</returns> /// <remarks> /// Increments the internal myListIndexes collection by incrementing the last index /// and overflow/carrying into others just like grade-school arithemtic. If the /// finaly carry flag is set, then we would wrap around and are therefore done. /// </remarks> public bool MoveNext() { int carry = 1; if(myListIndexes == null) { myListIndexes = new List<int>(); for(int i = 0; i < myParent.LowerIndex; ++i) { myListIndexes.Add(0); } carry = 0; } else { for(int i = myListIndexes.Count - 1; i >= 0 && carry > 0; --i) { myListIndexes[i] += carry; carry = 0; if(myListIndexes[i] >= myParent.UpperIndex) { myListIndexes[i] = 0; carry = 1; } } } myCurrentList = null; return carry != 1; } /// <summary> /// The current variation /// </summary> public IList<T> Current { get { ComputeCurrent(); return myCurrentList; } } /// <summary> /// The current variation. /// </summary> object System.Collections.IEnumerator.Current { get { ComputeCurrent(); return myCurrentList; } } /// <summary> /// Cleans up non-managed resources, of which there are none used here. /// </summary> public void Dispose() { ; } #endregion #region Heavy Lifting Members /// <summary> /// Computes the current list based on the internal list index. /// </summary> private void ComputeCurrent() { if(myCurrentList == null) { myCurrentList = new List<T>(); foreach(int index in myListIndexes) { myCurrentList.Add(myParent.myValues[index]); } } } #endregion #region Data /// <summary> /// Parent object this is an enumerator for. /// </summary> private Variations<T> myParent; /// <summary> /// The current list of values, this is lazy evaluated by the Current property. /// </summary> private List<T> myCurrentList; /// <summary> /// An enumertor of the parents list of lexicographic orderings. /// </summary> private List<int> myListIndexes; #endregion } /// <summary> /// An enumerator for Variations when the type is set to WithoutRepetition. /// </summary> public class EnumeratorWithoutRepetition : IEnumerator<IList<T>> { #region Constructors /// <summary> /// Construct a enumerator with the parent object. /// </summary> /// <param name="source">The source Variations object.</param> public EnumeratorWithoutRepetition(Variations<T> source) { myParent = source; myPermutationsEnumerator = (Permutations<int>.Enumerator)myParent.myPermutations.GetEnumerator(); } #endregion #region IEnumerator interface /// <summary> /// Resets the Variations enumerator to the first variation. /// </summary> public void Reset() { myPermutationsEnumerator.Reset(); } /// <summary> /// Advances to the next variation. /// </summary> /// <returns>True if successfully moved to next variation, False if no more variations exist.</returns> public bool MoveNext() { bool ret = myPermutationsEnumerator.MoveNext(); myCurrentList = null; return ret; } /// <summary> /// The current variation. /// </summary> public IList<T> Current { get { ComputeCurrent(); return myCurrentList; } } /// <summary> /// The current variation. /// </summary> object System.Collections.IEnumerator.Current { get { ComputeCurrent(); return myCurrentList; } } /// <summary> /// Cleans up non-managed resources, of which there are none used here. /// </summary> public void Dispose() { ; } #endregion #region Heavy Lifting Members /// <summary> /// Creates a list of original values from the int permutation provided. /// The exception for accessing current (InvalidOperationException) is generated /// by the call to .Current on the underlying enumeration. /// </summary> /// <remarks> /// To compute the current list of values, the element to use is determined by /// a permutation position with a non-MaxValue value. It is placed at the position in the /// output that the index value indicates. /// /// E.g. Variations of 6 choose 3 without repetition /// Input array: {A B C D E F} /// Permutations: {- 1 - - 3 2} (- is Int32.MaxValue) /// Generates set: {B F E} /// </remarks> private void ComputeCurrent() { if(myCurrentList == null) { myCurrentList = new List<T>(); int index = 0; IList<int> currentPermutation = (IList<int>)myPermutationsEnumerator.Current; for(int i = 0; i < myParent.LowerIndex; ++i) { myCurrentList.Add(myParent.myValues[0]); } for(int i = 0; i < currentPermutation.Count; ++i) { int position = currentPermutation[i]; if(position != Int32.MaxValue) { myCurrentList[position] = myParent.myValues[index]; if(myParent.Type == GenerateOption.WithoutRepetition) { ++index; } } else { ++index; } } } } #endregion #region Data /// <summary> /// Parent object this is an enumerator for. /// </summary> private Variations<T> myParent; /// <summary> /// The current list of values, this is lazy evaluated by the Current property. /// </summary> private List<T> myCurrentList; /// <summary> /// An enumertor of the parents list of lexicographic orderings. /// </summary> private Permutations<int>.Enumerator myPermutationsEnumerator; #endregion } #endregion #region IMetaList Interface /// <summary> /// The number of unique variations that are defined in this meta-collection. /// </summary> /// <remarks> /// Variations with repetitions does not behave like other meta-collections and it's /// count is equal to N^P, where N is the upper index and P is the lower index. /// </remarks> public long Count { get { if(Type == GenerateOption.WithoutRepetition) { return myPermutations.Count; } else { return (long)Math.Pow(UpperIndex, LowerIndex); } } } /// <summary> /// The type of Variations set that is generated. /// </summary> public GenerateOption Type { get { return myMetaCollectionType; } } /// <summary> /// The upper index of the meta-collection, equal to the number of items in the initial set. /// </summary> public int UpperIndex { get { return myValues.Count; } } /// <summary> /// The lower index of the meta-collection, equal to the number of items returned each iteration. /// </summary> public int LowerIndex { get { return myLowerIndex; } } #endregion #region Heavy Lifting Members /// <summary> /// Initialize the variations for constructors. /// </summary> /// <param name="values">List of values to select variations from.</param> /// <param name="lowerIndex">The size of each variation set to return.</param> /// <param name="type">The type of variations set to generate.</param> private void Initialize(IList<T> values, int lowerIndex, GenerateOption type) { myMetaCollectionType = type; myLowerIndex = lowerIndex; myValues = new List<T>(); myValues.AddRange(values); if(type == GenerateOption.WithoutRepetition) { List<int> myMap = new List<int>(); int index = 0; for(int i = 0; i < myValues.Count; ++i) { if(i >= myValues.Count - myLowerIndex) { myMap.Add(index++); } else { myMap.Add(Int32.MaxValue); } } myPermutations = new Permutations<int>(myMap); } else { ; // myPermutations isn't used. } } #endregion #region Data /// <summary> /// Copy of values object is intialized with, required for enumerator reset. /// </summary> private List<T> myValues; /// <summary> /// Permutations object that handles permutations on int for variation inclusion and ordering. /// </summary> private Permutations<int> myPermutations; /// <summary> /// The type of the variation collection. /// </summary> private GenerateOption myMetaCollectionType; /// <summary> /// The lower index defined in the constructor. /// </summary> private int myLowerIndex; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Net.Test.Common; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class SelectAndPollTests { const int SelectTimeout = 100; const int SelectSuccessTimeoutMicroseconds = 5*1000*1000; // 5 seconds [Fact] public void SelectNone_Throws() { Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, null, SelectSuccessTimeoutMicroseconds)); } [Fact] public void Select_Read_NotASocket_Throws() { var list = new List<object> { new object() }; Assert.Throws<ArgumentException>(() => Socket.Select(list, null, null, SelectSuccessTimeoutMicroseconds)); } [Fact] public void SelectRead_Single_Success() { using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int receiverPort = receiver.BindToAnonymousPort(IPAddress.Loopback); var receiverEndpoint = new IPEndPoint(IPAddress.Loopback, receiverPort); sender.SendTo(new byte[1], SocketFlags.None, receiverEndpoint); var list = new List<Socket> { receiver }; Socket.Select(list, null, null, SelectSuccessTimeoutMicroseconds); Assert.Equal(1, list.Count); Assert.Equal(receiver, list[0]); } } [Fact] public void SelectRead_Single_Timeout() { using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { receiver.BindToAnonymousPort(IPAddress.Loopback); var list = new List<Socket> { receiver }; Socket.Select(list, null, null, SelectTimeout); Assert.Equal(0, list.Count); } } [Fact] public void SelectRead_Multiple_Success() { using (var firstReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var secondReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int firstReceiverPort = firstReceiver.BindToAnonymousPort(IPAddress.Loopback); var firstReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, firstReceiverPort); int secondReceiverPort = secondReceiver.BindToAnonymousPort(IPAddress.Loopback); var secondReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, secondReceiverPort); sender.SendTo(new byte[1], SocketFlags.None, firstReceiverEndpoint); sender.SendTo(new byte[1], SocketFlags.None, secondReceiverEndpoint); var sw = Stopwatch.StartNew(); Assert.True(SpinWait.SpinUntil(() => { var list = new List<Socket> { firstReceiver, secondReceiver }; Socket.Select(list, null, null, Math.Max((int)(SelectSuccessTimeoutMicroseconds - (sw.Elapsed.TotalSeconds * 1000000)), 0)); Assert.True(list.Count <= 2); if (list.Count == 2) { Assert.Equal(firstReceiver, list[0]); Assert.Equal(secondReceiver, list[1]); return true; } return false; }, SelectSuccessTimeoutMicroseconds / 1000), "Failed to select both items within allotted time"); } } [Fact] public void SelectRead_Multiple_Timeout() { using (var firstReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var secondReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { firstReceiver.BindToAnonymousPort(IPAddress.Loopback); secondReceiver.BindToAnonymousPort(IPAddress.Loopback); var list = new List<Socket> { firstReceiver, secondReceiver }; Socket.Select(list, null, null, SelectTimeout); Assert.Equal(0, list.Count); } } [Fact] public void SelectRead_Multiple_Mixed() { using (var firstReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var secondReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { firstReceiver.BindToAnonymousPort(IPAddress.Loopback); int secondReceiverPort = secondReceiver.BindToAnonymousPort(IPAddress.Loopback); var secondReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, secondReceiverPort); sender.SendTo(new byte[1], SocketFlags.None, secondReceiverEndpoint); var list = new List<Socket> { firstReceiver, secondReceiver }; Socket.Select(list, null, null, SelectSuccessTimeoutMicroseconds); Assert.Equal(1, list.Count); Assert.Equal(secondReceiver, list[0]); } } [Fact] public void Select_Write_NotASocket_Throws() { var list = new List<object> { new object() }; Assert.Throws<ArgumentException>(() => Socket.Select(null, list, null, SelectSuccessTimeoutMicroseconds)); } [Fact] public void SelectWrite_Single_Success() { using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { var list = new List<Socket> { sender }; Socket.Select(null, list, null, SelectSuccessTimeoutMicroseconds); Assert.Equal(1, list.Count); Assert.Equal(sender, list[0]); } } [Fact] public void SelectWrite_Single_Timeout() { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); listener.AcceptAsync(); var list = new List<Socket> { listener }; Socket.Select(null, list, null, SelectTimeout); Assert.Equal(0, list.Count); } } [Fact] public void SelectWrite_Multiple_Success() { using (var firstSender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var secondSender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { var list = new List<Socket> { firstSender, secondSender }; Socket.Select(null, list, null, SelectSuccessTimeoutMicroseconds); Assert.Equal(2, list.Count); Assert.Equal(firstSender, list[0]); Assert.Equal(secondSender, list[1]); } } [Fact] public void SelectWrite_Multiple_Timeout() { using (var firstListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var secondListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { firstListener.BindToAnonymousPort(IPAddress.Loopback); firstListener.Listen(1); firstListener.AcceptAsync(); secondListener.BindToAnonymousPort(IPAddress.Loopback); secondListener.Listen(1); secondListener.AcceptAsync(); var list = new List<Socket> { firstListener, secondListener }; Socket.Select(null, list, null, SelectTimeout); Assert.Equal(0, list.Count); } } [Fact] public void SelectWrite_Multiple_Mixed() { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); listener.AcceptAsync(); var list = new List<Socket> { listener, sender }; Socket.Select(null, list, null, SelectSuccessTimeoutMicroseconds); Assert.Equal(1, list.Count); Assert.Equal(sender, list[0]); } } [Fact] public void Select_Error_NotASocket_Throws() { var list = new List<object> { new object() }; Assert.Throws<ArgumentException>(() => Socket.Select(null, null, list, SelectSuccessTimeoutMicroseconds)); } [Fact] public void SelectError_Single_Timeout() { using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { receiver.BindToAnonymousPort(IPAddress.Loopback); var list = new List<Socket> { receiver }; Socket.Select(null, null, list, SelectTimeout); Assert.Equal(0, list.Count); } } [Fact] public void SelectError_Multiple_Timeout() { using (var firstReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var secondReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { firstReceiver.BindToAnonymousPort(IPAddress.Loopback); secondReceiver.BindToAnonymousPort(IPAddress.Loopback); var list = new List<Socket> { firstReceiver, secondReceiver }; Socket.Select(null, null, list, SelectTimeout); Assert.Equal(0, list.Count); } } [Fact] public void PollRead_Single_Success() { using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int receiverPort = receiver.BindToAnonymousPort(IPAddress.Loopback); var receiverEndpoint = new IPEndPoint(IPAddress.Loopback, receiverPort); sender.SendTo(new byte[1], SocketFlags.None, receiverEndpoint); Assert.True(receiver.Poll(SelectSuccessTimeoutMicroseconds, SelectMode.SelectRead)); } } [Fact] public void PollRead_Single_Timeout() { using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { receiver.BindToAnonymousPort(IPAddress.Loopback); Assert.False(receiver.Poll(SelectTimeout, SelectMode.SelectRead)); } } [Fact] public void PollWrite_Single_Success() { using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { Assert.True(sender.Poll(SelectSuccessTimeoutMicroseconds, SelectMode.SelectWrite)); } } [Fact] public void PollWrite_Single_Timeout() { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); listener.AcceptAsync(); Assert.False(listener.Poll(SelectTimeout, SelectMode.SelectWrite)); } } [Fact] public void PollError_Single_Timeout() { using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { receiver.BindToAnonymousPort(IPAddress.Loopback); Assert.False(receiver.Poll(SelectTimeout, SelectMode.SelectError)); } } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { #if !NET3_5 using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using NLog.Config; using NLog.Targets; using Xunit; public class AsyncTaskTargetTest : NLogTestBase { [Target("AsyncTaskTest")] class AsyncTaskTestTarget : AsyncTaskTarget { private readonly AutoResetEvent _writeEvent = new AutoResetEvent(false); internal readonly ConcurrentQueue<string> Logs = new ConcurrentQueue<string>(); internal int WriteTasks => _writeTasks; protected int _writeTasks; public bool WaitForWriteEvent(int timeoutMilliseconds = 1000) { if (_writeEvent.WaitOne(TimeSpan.FromMilliseconds(timeoutMilliseconds))) { Thread.Sleep(25); return true; } return false; } protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token) { Interlocked.Increment(ref _writeTasks); return WriteLogQueue(logEvent, token); } protected async Task WriteLogQueue(LogEventInfo logEvent, CancellationToken token) { if (logEvent.Message == "EXCEPTION") throw new InvalidOperationException("AsyncTaskTargetTest Failure"); else if (logEvent.Message == "ASYNCEXCEPTION") await Task.Delay(10, token).ContinueWith((t) => { throw new InvalidOperationException("AsyncTaskTargetTest Async Failure"); }).ConfigureAwait(false); else if (logEvent.Message == "TIMEOUT") await Task.Delay(15000, token).ConfigureAwait(false); else { if (logEvent.Message == "SLEEP") Task.Delay(5000, token).GetAwaiter().GetResult(); await Task.Delay(10, token).ContinueWith((t) => Logs.Enqueue(RenderLogEvent(Layout, logEvent)), token).ContinueWith(async (t) => await Task.Delay(10).ConfigureAwait(false)).ConfigureAwait(false); } _writeEvent.Set(); } } class AsyncTaskBatchTestTarget : AsyncTaskTestTarget { protected override async Task WriteAsyncTask(IList<LogEventInfo> logEvents, CancellationToken cancellationToken) { Interlocked.Increment(ref _writeTasks); for (int i = 0; i < logEvents.Count; ++i) await WriteLogQueue(logEvents[i], cancellationToken); } protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken) { throw new NotImplementedException(); } } [Fact] public void AsyncTaskTarget_TestLogging() { ILogger logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskTestTarget { Layout = "${threadid}|${level}|${message}|${mdlc:item=Test}" }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); NLog.Common.InternalLogger.LogLevel = LogLevel.Off; int managedThreadId = 0; Task task; using (MappedDiagnosticsLogicalContext.SetScoped("Test", 42)) { task = Task.Run(() => { managedThreadId = Thread.CurrentThread.ManagedThreadId; logger.Trace("TTT"); logger.Debug("DDD"); logger.Info("III"); logger.Warn("WWW"); logger.Error("EEE"); logger.Fatal("FFF"); }); } Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); task.Wait(); LogManager.Flush(); Assert.Equal(6, asyncTarget.Logs.Count); while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { Assert.Equal(0, logEventMessage.IndexOf(managedThreadId.ToString() + "|")); Assert.EndsWith("|42", logEventMessage); } LogManager.Configuration = null; } [Fact] public void AsyncTaskTarget_SkipAsyncTargetWrapper() { try { ConfigurationItemFactory.Default.RegisterType(typeof(AsyncTaskTestTarget), null); LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets async='true'> <target name='asyncDebug' type='AsyncTaskTest' /> <target name='debug' type='Debug' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Assert.NotNull(LogManager.Configuration.FindTargetByName<AsyncTaskTestTarget>("asyncDebug")); Assert.NotNull(LogManager.Configuration.FindTargetByName<NLog.Targets.Wrappers.AsyncTargetWrapper>("debug")); } finally { ConfigurationItemFactory.Default = null; } } [Fact] public void AsyncTaskTarget_SkipDefaultAsyncWrapper() { try { ConfigurationItemFactory.Default.RegisterType(typeof(AsyncTaskTestTarget), null); LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <default-wrapper type='AsyncWrapper' /> <target name='asyncDebug' type='AsyncTaskTest' /> <target name='debug' type='Debug' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Assert.NotNull(LogManager.Configuration.FindTargetByName<AsyncTaskTestTarget>("asyncDebug")); Assert.NotNull(LogManager.Configuration.FindTargetByName<NLog.Targets.Wrappers.AsyncTargetWrapper>("debug")); } finally { ConfigurationItemFactory.Default = null; } } [Fact] public void AsyncTaskTarget_AllowDefaultBufferWrapper() { try { ConfigurationItemFactory.Default.RegisterType(typeof(AsyncTaskTestTarget), null); LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <default-wrapper type='BufferingWrapper' /> <target name='asyncDebug' type='AsyncTaskTest' /> <target name='debug' type='Debug' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Assert.NotNull(LogManager.Configuration.FindTargetByName<NLog.Targets.Wrappers.BufferingTargetWrapper>("asyncDebug")); Assert.NotNull(LogManager.Configuration.FindTargetByName<NLog.Targets.Wrappers.BufferingTargetWrapper>("debug")); } finally { ConfigurationItemFactory.Default = null; } } [Fact] public void AsyncTaskTarget_TestAsyncException() { ILogger logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", RetryDelayMilliseconds = 50 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel == LogLevel.Debug ? "ASYNCEXCEPTION" : logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); LogManager.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal, asyncTarget.Logs.Count); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.NotEqual(LogLevel.Debug, logLevel); Assert.Equal(ordinal++, logLevel.Ordinal); if (ordinal == LogLevel.Debug.Ordinal) ++ordinal; } LogManager.Configuration = null; } [Fact] public void AsyncTaskTarget_TestTimeout() { RetryingIntegrationTest(3, () => { ILogger logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", TaskTimeoutSeconds = 1 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); logger.Trace("TTT"); logger.Debug("TIMEOUT"); logger.Info("III"); logger.Warn("WWW"); logger.Error("EEE"); logger.Fatal("FFF"); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); LogManager.Flush(); Assert.Equal(5, asyncTarget.Logs.Count); while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { Assert.Equal(-1, logEventMessage.IndexOf("Debug|")); } LogManager.Configuration = null; }); } [Fact] public void AsyncTaskTarget_TestRetryAsyncException() { ILogger logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", RetryDelayMilliseconds = 10, RetryCount = 3 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel == LogLevel.Debug ? "ASYNCEXCEPTION" : logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); LogManager.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal, asyncTarget.Logs.Count); Assert.Equal(LogLevel.MaxLevel.Ordinal + 4, asyncTarget.WriteTasks); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.NotEqual(LogLevel.Debug, logLevel); Assert.Equal(ordinal++, logLevel.Ordinal); if (ordinal == LogLevel.Debug.Ordinal) ++ordinal; } LogManager.Configuration = null; } [Fact] public void AsyncTaskTarget_TestRetryException() { ILogger logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", RetryDelayMilliseconds = 10, RetryCount = 3 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel == LogLevel.Debug ? "EXCEPTION" : logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); LogManager.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal, asyncTarget.Logs.Count); Assert.Equal(LogLevel.MaxLevel.Ordinal + 4, asyncTarget.WriteTasks); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.NotEqual(LogLevel.Debug, logLevel); Assert.Equal(ordinal++, logLevel.Ordinal); if (ordinal == LogLevel.Debug.Ordinal) ++ordinal; } LogManager.Configuration = null; } [Fact] public void AsyncTaskTarget_TestBatchWriting() { ILogger logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", BatchSize = 3, TaskDelayMilliseconds = 10 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); LogManager.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal + 1, asyncTarget.Logs.Count); Assert.Equal(LogLevel.MaxLevel.Ordinal / 2, asyncTarget.WriteTasks); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.Equal(ordinal++, logLevel.Ordinal); } LogManager.Configuration = null; } [Fact] public void AsyncTaskTarget_TestFakeBatchWriting() { ILogger logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskTestTarget { Layout = "${level}", BatchSize = 3, TaskDelayMilliseconds = 10 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); foreach (var logLevel in LogLevel.AllLoggingLevels) logger.Log(logLevel, logLevel.Name.ToUpperInvariant()); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); LogManager.Flush(); Assert.Equal(LogLevel.MaxLevel.Ordinal + 1, asyncTarget.Logs.Count); Assert.Equal(LogLevel.MaxLevel.Ordinal + 1, asyncTarget.WriteTasks); int ordinal = 0; while (asyncTarget.Logs.TryDequeue(out var logEventMessage)) { var logLevel = LogLevel.FromString(logEventMessage); Assert.Equal(ordinal++, logLevel.Ordinal); } LogManager.Configuration = null; } [Fact] public void AsyncTaskTarget_TestSlowBatchWriting() { ILogger logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", TaskDelayMilliseconds = 200 }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); DateTime utcNow = DateTime.UtcNow; logger.Log(LogLevel.Info, LogLevel.Info.ToString().ToUpperInvariant()); logger.Log(LogLevel.Fatal, "SLEEP"); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.Single(asyncTarget.Logs); logger.Log(LogLevel.Error, LogLevel.Error.ToString().ToUpperInvariant()); asyncTarget.Dispose(); // Trigger fast shutdown LogManager.Configuration = null; TimeSpan shutdownTime = DateTime.UtcNow - utcNow; Assert.True(shutdownTime < TimeSpan.FromSeconds(4), $"Shutdown took {shutdownTime.TotalMilliseconds} msec"); } [Fact] public void AsyncTaskTarget_TestThrottleOnTaskDelay() { ILogger logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", TaskDelayMilliseconds = 50, BatchSize = 10, }; SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace); for (int i = 0; i < 5; ++i) { for (int j = 0; j < 10; ++j) { logger.Log(LogLevel.Info, i.ToString()); Thread.Sleep(20); } Assert.True(asyncTarget.WaitForWriteEvent()); } Assert.True(asyncTarget.Logs.Count > 25, $"{asyncTarget.Logs.Count} LogEvents are too few after {asyncTarget.WriteTasks} writes"); Assert.True(asyncTarget.WriteTasks < 20, $"{asyncTarget.WriteTasks} writes are too many."); } [Fact] public void AsynTaskTarget_AutoFlushWrapper() { ILogger logger = LogManager.GetCurrentClassLogger(); var asyncTarget = new AsyncTaskBatchTestTarget { Layout = "${level}", TaskDelayMilliseconds = 5000, BatchSize = 10, }; var autoFlush = new NLog.Targets.Wrappers.AutoFlushTargetWrapper("autoflush", asyncTarget); autoFlush.Condition = "level > LogLevel.Warn"; SimpleConfigurator.ConfigureForTargetLogging(autoFlush, LogLevel.Trace); logger.Info("Hello World"); Assert.Empty(asyncTarget.Logs); logger.Error("Goodbye World"); Assert.True(asyncTarget.WaitForWriteEvent()); Assert.NotEmpty(asyncTarget.Logs); } } #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; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MetadataMemberTests : CSharpTestBase { private static readonly string VTableGapClassIL = @" .class public auto ansi beforefieldinit Class extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void _VtblGap1_1() cil managed { ret } .method public hidebysig specialname instance int32 _VtblGap2_1() cil managed { ret } .method public hidebysig specialname instance void set_GetterIsGap(int32 'value') cil managed { ret } .method public hidebysig specialname instance int32 get_SetterIsGap() cil managed { ret } .method public hidebysig specialname instance void _VtblGap3_1(int32 'value') cil managed { ret } .method public hidebysig specialname instance int32 _VtblGap4_1() cil managed { ret } .method public hidebysig specialname instance void _VtblGap5_1(int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .property instance int32 GetterIsGap() { .get instance int32 Class::_VtblGap2_1() .set instance void Class::set_GetterIsGap(int32) } // end of property Class::GetterIsGap .property instance int32 SetterIsGap() { .get instance int32 Class::get_SetterIsGap() .set instance void Class::_VtblGap3_1(int32) } // end of property Class::SetterIsGap .property instance int32 BothAccessorsAreGaps() { .get instance int32 Class::_VtblGap4_1() .set instance void Class::_VtblGap5_1(int32) } // end of property Class::BothAccessorsAreGaps } // end of class Class "; private const string VTableGapInterfaceIL = @" .class interface public abstract auto ansi Interface { .method public hidebysig newslot specialname rtspecialname abstract virtual instance void _VtblGap1_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 _VtblGap2_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_GetterIsGap(int32 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 get_SetterIsGap() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void _VtblGap3_1(int32 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 _VtblGap4_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void _VtblGap5_1(int32 'value') cil managed { } .property instance int32 GetterIsGap() { .get instance int32 Interface::_VtblGap2_1() .set instance void Interface::set_GetterIsGap(int32) } // end of property Interface::GetterIsGap .property instance int32 SetterIsGap() { .get instance int32 Interface::get_SetterIsGap() .set instance void Interface::_VtblGap3_1(int32) } // end of property Interface::SetterIsGap .property instance int32 BothAccessorsAreGaps() { .get instance int32 Interface::_VtblGap4_1() .set instance void Interface::_VtblGap5_1(int32) } // end of property Interface::BothAccessorsAreGaps } // end of class Interface "; [WorkItem(537346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537346")] [Fact] public void MetadataMethodSymbolCtor01() { var text = "public class A {}"; var compilation = CreateStandardCompilation(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal(RuntimeCorLibName.Name, mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var type1 = ns1.GetTypeMembers("StringComparer").Single() as NamedTypeSymbol; var ctor = type1.InstanceConstructors.Single(); Assert.Equal(type1, ctor.ContainingSymbol); Assert.Equal(WellKnownMemberNames.InstanceConstructorName, ctor.Name); Assert.Equal(SymbolKind.Method, ctor.Kind); Assert.Equal(MethodKind.Constructor, ctor.MethodKind); Assert.Equal(Accessibility.Protected, ctor.DeclaredAccessibility); Assert.True(ctor.IsDefinition); Assert.False(ctor.IsStatic); Assert.False(ctor.IsSealed); Assert.False(ctor.IsOverride); Assert.False(ctor.IsExtensionMethod); Assert.True(ctor.ReturnsVoid); Assert.False(ctor.IsVararg); // Bug - 2067 Assert.Equal("System.StringComparer." + WellKnownMemberNames.InstanceConstructorName + "()", ctor.ToTestDisplayString()); Assert.Equal(0, ctor.TypeParameters.Length); Assert.Equal("Void", ctor.ReturnType.Name); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(537345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537345")] [Fact] public void MetadataMethodSymbol01() { var text = "public class A {}"; var compilation = CreateCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns3.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; var members = class1.GetMembers("StrongNameSignatureGeneration"); // 4 overloads Assert.Equal(4, members.Length); var member1 = members.Last() as MethodSymbol; Assert.Equal(mscorNS, member1.ContainingAssembly); Assert.Equal(class1, member1.ContainingSymbol); Assert.Equal(SymbolKind.Method, member1.Kind); Assert.Equal(MethodKind.Ordinary, member1.MethodKind); Assert.Equal(Accessibility.Public, member1.DeclaredAccessibility); Assert.True(member1.IsDefinition); Assert.True(member1.IsStatic); Assert.False(member1.IsAbstract); Assert.False(member1.IsSealed); Assert.False(member1.IsVirtual); Assert.False(member1.IsOverride); // Bug - // Assert.True(member1.IsOverloads); Assert.False(member1.IsGenericMethod); // Not Impl // Assert.False(member1.IsExtensionMethod); Assert.False(member1.ReturnsVoid); Assert.False(member1.IsVararg); var fullName = "System.Boolean Microsoft.Runtime.Hosting.StrongNameHelpers.StrongNameSignatureGeneration(System.String pwzFilePath, System.String pwzKeyContainer, System.Byte[] bKeyBlob, System.Int32 cbKeyBlob, ref System.IntPtr ppbSignatureBlob, out System.Int32 pcbSignatureBlob)"; Assert.Equal(fullName, member1.ToTestDisplayString()); Assert.Equal(0, member1.TypeArguments.Length); Assert.Equal(0, member1.TypeParameters.Length); Assert.Equal(6, member1.Parameters.Length); Assert.Equal("Boolean", member1.ReturnType.Name); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(527150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527150")] [WorkItem(527151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527151")] [Fact] public void MetadataParameterSymbol01() { var text = "public class A {}"; var compilation = CreateCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = (ns1.GetMembers("Runtime").Single() as NamespaceSymbol).GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns2.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; var members = class1.GetMembers("StrongNameSignatureGeneration"); var member1 = members.Last() as MethodSymbol; Assert.Equal(6, member1.Parameters.Length); var p1 = member1.Parameters[0] as ParameterSymbol; var p2 = member1.Parameters[1] as ParameterSymbol; var p3 = member1.Parameters[2] as ParameterSymbol; var p4 = member1.Parameters[3] as ParameterSymbol; var p5 = member1.Parameters[4] as ParameterSymbol; var p6 = member1.Parameters[5] as ParameterSymbol; Assert.Equal(mscorNS, p1.ContainingAssembly); Assert.Equal(class1, p1.ContainingType); Assert.Equal(member1, p1.ContainingSymbol); Assert.Equal(SymbolKind.Parameter, p1.Kind); Assert.Equal(Accessibility.NotApplicable, p1.DeclaredAccessibility); Assert.Equal("pwzFilePath", p1.Name); Assert.Equal("System.String pwzKeyContainer", p2.ToTestDisplayString()); Assert.Equal("String", p2.Type.Name); Assert.True(p2.IsDefinition); Assert.Equal("System.Byte[] bKeyBlob", p3.ToTestDisplayString()); Assert.Equal("System.Byte[]", p3.Type.ToTestDisplayString()); //array types do not have names - use ToTestDisplayString Assert.False(p1.IsStatic); Assert.False(p1.IsAbstract); Assert.False(p2.IsSealed); Assert.False(p2.IsVirtual); Assert.False(p3.IsOverride); Assert.False(p3.IsParams); Assert.False(p4.IsOptional); Assert.False(p4.HasExplicitDefaultValue); // Not Impl - out of scope // Assert.Null(p4.DefaultValue); Assert.Equal("ppbSignatureBlob", p5.Name); Assert.Equal("IntPtr", p5.Type.Name); Assert.Equal(RefKind.Ref, p5.RefKind); Assert.Equal("out System.Int32 pcbSignatureBlob", p6.ToTestDisplayString()); Assert.Equal(RefKind.Out, p6.RefKind); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataMethodSymbolGen02() { var text = "public class A {}"; var compilation = CreateStandardCompilation(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IDictionary").First() as NamedTypeSymbol; var member1 = type1.GetMembers("Add").Single() as MethodSymbol; var member2 = type1.GetMembers("TryGetValue").Single() as MethodSymbol; Assert.Equal(mscorNS, member1.ContainingAssembly); Assert.Equal(type1, member1.ContainingSymbol); Assert.Equal(SymbolKind.Method, member1.Kind); // Not Impl //Assert.Equal(MethodKind.Ordinary, member2.MethodKind); Assert.Equal(Accessibility.Public, member2.DeclaredAccessibility); Assert.True(member2.IsDefinition); Assert.False(member1.IsStatic); Assert.True(member1.IsAbstract); Assert.False(member2.IsSealed); Assert.False(member2.IsVirtual); Assert.False(member2.IsOverride); //Assert.True(member1.IsOverloads); //Assert.True(member2.IsOverloads); Assert.False(member1.IsGenericMethod); // Not Impl //Assert.False(member1.IsExtensionMethod); Assert.True(member1.ReturnsVoid); Assert.False(member2.IsVararg); Assert.Equal(0, member1.TypeArguments.Length); Assert.Equal(0, member2.TypeParameters.Length); Assert.Equal(2, member1.Parameters.Length); Assert.Equal("Boolean", member2.ReturnType.Name); Assert.Equal("System.Boolean System.Collections.Generic.IDictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value)", member2.ToTestDisplayString()); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataParameterSymbolGen02() { var text = "public class A {}"; var compilation = CreateStandardCompilation(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IDictionary").First() as NamedTypeSymbol; var member1 = type1.GetMembers("TryGetValue").Single() as MethodSymbol; Assert.Equal(2, member1.Parameters.Length); var p1 = member1.Parameters[0] as ParameterSymbol; var p2 = member1.Parameters[1] as ParameterSymbol; Assert.Equal(mscorNS, p1.ContainingAssembly); Assert.Equal(type1, p2.ContainingType); Assert.Equal(member1, p1.ContainingSymbol); Assert.Equal(SymbolKind.Parameter, p2.Kind); Assert.Equal(Accessibility.NotApplicable, p1.DeclaredAccessibility); Assert.Equal("value", p2.Name); Assert.Equal("TKey key", p1.ToTestDisplayString()); // Empty // Assert.Equal("TValue", p2.Type.Name); Assert.True(p2.IsDefinition); Assert.False(p1.IsStatic); Assert.False(p1.IsAbstract); Assert.False(p2.IsSealed); Assert.False(p2.IsVirtual); Assert.False(p1.IsOverride); Assert.False(p1.IsExtern); Assert.False(p1.IsParams); Assert.False(p2.IsOptional); Assert.False(p2.HasExplicitDefaultValue); // Not Impl - Not in M2 scope // Assert.Null(p2.DefaultValue); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(537424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537424")] [Fact] public void MetadataMethodStaticAndInstanceCtor() { var text = @" class C { C() { } static C() { } }"; var compilation = CreateStandardCompilation(text); Assert.False(compilation.GetDiagnostics().Any()); var classC = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single(); // NamedTypeSymbol.Constructors only contains instance constructors Assert.Equal(1, classC.InstanceConstructors.Length); Assert.Equal(1, classC.GetMembers(WellKnownMemberNames.StaticConstructorName).Length); } [ClrOnlyFact] public void ImportDecimalConstantAttribute() { const string ilSource = @" .class public C extends [mscorlib]System.Object { .field public static initonly valuetype [mscorlib]System.Decimal MyDecimalTen .custom instance void [mscorlib]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 0A 00 00 00 00 00 ) } // end of class C"; const string cSharpSource = @" class B { static void Main() { var x = C.MyDecimalTen; System.Console.Write(x); } } "; CompileWithCustomILSource(cSharpSource, ilSource, expectedOutput: "10"); } [Fact] public void TypeAndNamespaceWithSameNameButDifferentArities() { var il = @" .class interface public abstract auto ansi A.B.C { } .class interface public abstract auto ansi A.B`1<T> { } "; var csharp = @""; var compilation = CreateCompilationWithCustomILSource(csharp, il); var namespaceA = compilation.GlobalNamespace.GetMember<NamespaceSymbol>("A"); var members = namespaceA.GetMembers("B"); Assert.Equal(2, members.Length); Assert.NotNull(members[0]); Assert.NotNull(members[1]); } [Fact] public void TypeAndNamespaceWithSameNameAndArity() { var il = @" .class interface public abstract auto ansi A.B.C { } .class interface public abstract auto ansi A.B { } "; var csharp = @""; var compilation = CreateCompilationWithCustomILSource(csharp, il); var namespaceA = compilation.GlobalNamespace.GetMember<NamespaceSymbol>("A"); var members = namespaceA.GetMembers("B"); Assert.Equal(2, members.Length); Assert.NotNull(members[0]); Assert.NotNull(members[1]); } // TODO: Update this test if we decide to include gaps in the symbol table for NoPIA (DevDiv #17472). [WorkItem(546951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546951")] [Fact] public void VTableGapsNotInSymbolTable() { var csharp = @""; var comp = CreateCompilationWithCustomILSource(csharp, VTableGapClassIL); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Class"); AssertEx.None(type.GetMembersUnordered(), symbol => symbol.Name.StartsWith("_VtblGap", StringComparison.Ordinal)); // Dropped entirely. Assert.Equal(0, type.GetMembers("_VtblGap1_1").Length); // Dropped entirely, since both accessors are dropped. Assert.Equal(0, type.GetMembers("BothAccessorsAreGaps").Length); // Getter is silently dropped, property appears valid and write-only. var propWithoutGetter = type.GetMember<PropertySymbol>("GetterIsGap"); Assert.Null(propWithoutGetter.GetMethod); Assert.NotNull(propWithoutGetter.SetMethod); Assert.False(propWithoutGetter.MustCallMethodsDirectly); // Setter is silently dropped, property appears valid and read-only. var propWithoutSetter = type.GetMember<PropertySymbol>("SetterIsGap"); Assert.NotNull(propWithoutSetter.GetMethod); Assert.Null(propWithoutSetter.SetMethod); Assert.False(propWithoutSetter.MustCallMethodsDirectly); } [WorkItem(546951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546951")] [Fact] public void CallVTableGap() { var csharp = @" class Test { static void Main() { Class c = new Class(); c._VtblGap1_1(); // CS1061 int x; x = c.BothAccessorsAreGaps; // CS1061 c.BothAccessorsAreGaps = x; // CS1061 x = c.GetterIsGap; // CS0154 c.GetterIsGap = x; x = c.SetterIsGap; c.SetterIsGap = x; // CS0200 } } "; var comp = CreateCompilationWithCustomILSource(csharp, VTableGapClassIL); comp.VerifyDiagnostics( // (8,11): error CS1061: 'Class' does not contain a definition for '_VtblGap1_1' and no extension method '_VtblGap1_1' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c._VtblGap1_1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "_VtblGap1_1").WithArguments("Class", "_VtblGap1_1"), // (12,15): error CS1061: 'Class' does not contain a definition for 'BothAccessorsAreGaps' and no extension method 'BothAccessorsAreGaps' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // x = c.BothAccessorsAreGaps; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BothAccessorsAreGaps").WithArguments("Class", "BothAccessorsAreGaps"), // (13,11): error CS1061: 'Class' does not contain a definition for 'BothAccessorsAreGaps' and no extension method 'BothAccessorsAreGaps' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c.BothAccessorsAreGaps = x; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BothAccessorsAreGaps").WithArguments("Class", "BothAccessorsAreGaps"), // (15,13): error CS0154: The property or indexer 'Class.GetterIsGap' cannot be used in this context because it lacks the get accessor // x = c.GetterIsGap; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "c.GetterIsGap").WithArguments("Class.GetterIsGap"), // (19,9): error CS0200: Property or indexer 'Class.SetterIsGap' cannot be assigned to -- it is read only // c.SetterIsGap = x; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.SetterIsGap").WithArguments("Class.SetterIsGap")); } [WorkItem(546951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546951")] [Fact] public void ImplementVTableGap() { var csharp = @" class Empty : Interface { } class Implicit : Interface { public void _VtblGap1_1() { } public int GetterIsGap { get; set; } public int SetterIsGap { get; set; } public int BothAccessorsAreGaps { get; set; } } class Explicit : Interface { void Interface._VtblGap1_1() { } int Interface.GetterIsGap { get; set; } int Interface.SetterIsGap { get; set; } int Interface.BothAccessorsAreGaps { get; set; } } "; var comp = CreateCompilationWithCustomILSource(csharp, VTableGapInterfaceIL); comp.VerifyDiagnostics( // (2,7): error CS0535: 'Empty' does not implement interface member 'Interface.SetterIsGap' // class Empty : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Empty", "Interface.SetterIsGap"), // (2,7): error CS0535: 'Empty' does not implement interface member 'Interface.GetterIsGap' // class Empty : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Empty", "Interface.GetterIsGap"), // (17,33): error CS0550: 'Explicit.Interface.GetterIsGap.get' adds an accessor not found in interface member 'Interface.GetterIsGap' // int Interface.GetterIsGap { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("Explicit.Interface.GetterIsGap.get", "Interface.GetterIsGap"), // (18,38): error CS0550: 'Explicit.Interface.SetterIsGap.set' adds an accessor not found in interface member 'Interface.SetterIsGap' // int Interface.SetterIsGap { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("Explicit.Interface.SetterIsGap.set", "Interface.SetterIsGap"), // (19,19): error CS0539: 'Explicit.BothAccessorsAreGaps' in explicit interface declaration is not a member of interface // int Interface.BothAccessorsAreGaps { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "BothAccessorsAreGaps").WithArguments("Explicit.BothAccessorsAreGaps"), // (16,20): error CS0539: 'Explicit._VtblGap1_1()' in explicit interface declaration is not a member of interface // void Interface._VtblGap1_1() { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "_VtblGap1_1").WithArguments("Explicit._VtblGap1_1()")); } [Fact, WorkItem(1094411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094411")] public void Bug1094411_01() { var source1 = @" class Test { public int F; public int P {get; set;} public event System.Action E { add { } remove { } } public void M() {} } "; var members = new[] { "F", "P", "E", "M" }; var comp1 = CreateStandardCompilation(source1, options: TestOptions.ReleaseDll); var test1 = comp1.GetTypeByMetadataName("Test"); var memberNames1 = new HashSet<string>(test1.MemberNames); foreach (var m in members) { Assert.True(memberNames1.Contains(m), m); } var comp2 = CreateStandardCompilation("", new[] { comp1.EmitToImageReference() }); var test2 = comp2.GetTypeByMetadataName("Test"); var memberNames2 = new HashSet<string>(test2.MemberNames); foreach (var m in members) { Assert.True(memberNames2.Contains(m), m); } } [Fact, WorkItem(1094411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094411")] public void Bug1094411_02() { var source1 = @" class Test { public int F; public int P {get; set;} public event System.Action E { add { } remove { } } public void M() {} } "; var members = new[] { "F", "P", "E", "M" }; var comp1 = CreateStandardCompilation(source1, options: TestOptions.ReleaseDll); var test1 = comp1.GetTypeByMetadataName("Test"); test1.GetMembers(); var memberNames1 = new HashSet<string>(test1.MemberNames); foreach (var m in members) { Assert.True(memberNames1.Contains(m), m); } var comp2 = CreateStandardCompilation("", new[] { comp1.EmitToImageReference() }); var test2 = comp2.GetTypeByMetadataName("Test"); test2.GetMembers(); var memberNames2 = new HashSet<string>(test2.MemberNames); foreach (var m in members) { Assert.True(memberNames2.Contains(m), m); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Dynamic; using System.Linq; using System.Threading; namespace MickeySmith { // Largely lifted from DannyBoy - https://github.com/swxben/danny-boy // This will be DannyPink - https://github.com/bendetat/dannypink internal class Danny : IDisposable { private readonly Func<ConnectionWrapper> _connectionFactory; private readonly Func<ConnectionWrapper> _masterConnectionFactory; private SqlTransaction _transaction; private bool _transactionComplete = false; public Danny(string connectionString) : this(null, null, null) { ConnectionString = connectionString; } private Danny(SqlTransaction transaction, Func<ConnectionWrapper> connectionFactory, Func<ConnectionWrapper> masterConnectionFactory) { _transaction = transaction; _connectionFactory = connectionFactory ?? (() => { var connection = new SqlConnection(ConnectionString); const int maxAttempts = 10; int attempt = 0; var exceptions = new List<Exception>(); var random = new Random(); while (true) { attempt++; try { connection.Open(); break; } catch (Exception ex) { exceptions.Add(ex); if (attempt == maxAttempts) { throw new AggregateException($"Maximum number of attempts reached ({maxAttempts}) when opening connection", exceptions.ToArray()); } Thread.Sleep(random.Next(200, 500)); } } return new ConnectionWrapper(connection, true); }); _masterConnectionFactory = masterConnectionFactory ?? (() => { var connection = new SqlConnection(MasterConnectionString); connection.Open(); return new ConnectionWrapper(connection, true); }); } public string ConnectionString { get; } private string MasterConnectionString { get { var builder = new SqlConnectionStringBuilder(ConnectionString) {InitialCatalog = "master"}; return builder.ConnectionString; } } public string DatabaseName { get { var builder = new SqlConnectionStringBuilder(ConnectionString); return builder.InitialCatalog; } } public void Dispose() { if (_transaction != null) { _transaction.Dispose(); _transaction = null; _connectionFactory().AllowDispose(); _connectionFactory().Dispose(); } } public void ExecuteCommand(string sql, object parameters = null) => ExecuteCommand(sql, parameters, _connectionFactory); public void ExecuteCommandOnMaster(string sql, object parameters = null) => ExecuteCommand(sql, parameters, _masterConnectionFactory); private void ExecuteCommand(string sql, object parameters, Func<ConnectionWrapper> connectionFactory) { using (var connection = connectionFactory()) using (var command = this.CreateCommand(connection.Connection, sql, parameters)) { command.ExecuteNonQuery(); } } public dynamic ExecuteScalar(string sql, object parameters = null) => ExecuteScalar(sql, parameters, _connectionFactory); public dynamic ExecuteScalarOnMaster(string sql, object parameters = null) => ExecuteScalar(sql, parameters, _masterConnectionFactory); private dynamic ExecuteScalar(string sql, object parameters, Func<ConnectionWrapper> connectionFactory) { using (var connection = connectionFactory()) { using (var command = this.CreateCommand(connection.Connection, sql, parameters)) { dynamic result = command.ExecuteScalar(); return result; } } } public IEnumerable<dynamic> ExecuteQuery(string sql, object parameters = null) => ExecuteQuery(sql, parameters, _connectionFactory); public IEnumerable<dynamic> ExecuteQueryOnMaster(string sql, object parameters = null) => ExecuteQuery(sql, parameters, _masterConnectionFactory); private IEnumerable<dynamic> ExecuteQuery(string sql, object parameters, Func<ConnectionWrapper> connectionFactory) { var results = new List<dynamic>(); using (var connection = connectionFactory()) { using (var command = this.CreateCommand(connection.Connection, sql, parameters)) using (var reader = command.ExecuteReader()) { while (reader.Read()) { var item = (new ExpandoObject()) as IDictionary<string, object>; for (var i = 0; i < reader.FieldCount; i++) { item.Add(reader.GetName(i), DBNull.Value.Equals(reader[i]) ? null : reader[i]); } results.Add(item); } } } return results; } public void ExecuteTransaction( System.Data.IsolationLevel isolationLevel, Action<Danny> transactionPayload, int maximumAttempts = 30) { if (_transaction != null) { throw new InvalidOperationException("Cannot create non-nested transactions per connection"); } var attempt = 0; var exceptions = new List<Exception>(); var random = new Random(); while (true) { attempt++; try { var connection = _connectionFactory(); connection.DisallowDispose(); var transaction = connection.Connection.BeginTransaction(isolationLevel); var danny = new Danny(transaction, () => connection, null); transactionPayload(danny); break; } catch (Exception ex) { exceptions.Add(ex); if (attempt == maximumAttempts) { throw new AggregateException( $"Maximum number of attempts reached ({maximumAttempts}) when executing transaction payload", exceptions); } Thread.Sleep(random.Next(200, 500)); } } } public void Commit() { if (_transaction == null) { throw new InvalidOperationException("Can't commit without an active transaction"); } if (_transactionComplete) { throw new InvalidOperationException("Transaction is already complete"); } _transactionComplete = true; _transaction.Commit(); _connectionFactory().AllowDispose(); } public void Rollback() { if (_transaction == null) { throw new InvalidOperationException("Can't roll back without an active transaction"); } if (_transactionComplete) { throw new InvalidOperationException("Transaction is already complete"); } _transactionComplete = true; _transaction.Rollback(); _connectionFactory().AllowDispose(); } private SqlCommand CreateCommand(SqlConnection connection, string sql, object parameters) { var command = connection.CreateCommand(); command.CommandType = CommandType.Text; command.CommandText = sql; command.Transaction = this._transaction; if (parameters != null) { command.Parameters.AddRange(parameters.GetType().GetProperties().Select(x => GetCommandParameter(command, x.Name, x.GetValue(parameters, null))).ToArray()); command.Parameters.AddRange(parameters.GetType().GetFields().Select(x => GetCommandParameter(command, x.Name, x.GetValue(parameters))).ToArray()); } return command; } private static SqlParameter GetCommandParameter(SqlCommand command, string name, object value) { var parameter = command.CreateParameter(); parameter.ParameterName = $"@{name}"; if (value != null && value.GetType().IsEnum) { value = value.ToString(); } parameter.Value = value ?? DBNull.Value; var s = value as string; if (s != null) { parameter.Size = s.Length > 4000 ? -1 : 4000; } return parameter; } private class ConnectionWrapper : IDisposable { private bool _allowDispose; public ConnectionWrapper(SqlConnection connection, bool allowDispose) { _allowDispose = allowDispose; Connection = connection; } public SqlConnection Connection { get; } public void Dispose() { if (_allowDispose) { Connection.Close(); Connection.Dispose(); } } public void AllowDispose() { _allowDispose = true; } public void DisallowDispose() { _allowDispose = false; } } } }
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class ModifyS3TargetSpectraS3Request : Ds3Request { public string S3Target { get; private set; } private string _accessKey; public string AccessKey { get { return _accessKey; } set { WithAccessKey(value); } } private int? _autoVerifyFrequencyInDays; public int? AutoVerifyFrequencyInDays { get { return _autoVerifyFrequencyInDays; } set { WithAutoVerifyFrequencyInDays(value); } } private string _cloudBucketPrefix; public string CloudBucketPrefix { get { return _cloudBucketPrefix; } set { WithCloudBucketPrefix(value); } } private string _cloudBucketSuffix; public string CloudBucketSuffix { get { return _cloudBucketSuffix; } set { WithCloudBucketSuffix(value); } } private string _dataPathEndPoint; public string DataPathEndPoint { get { return _dataPathEndPoint; } set { WithDataPathEndPoint(value); } } private TargetReadPreferenceType? _defaultReadPreference; public TargetReadPreferenceType? DefaultReadPreference { get { return _defaultReadPreference; } set { WithDefaultReadPreference(value); } } private bool? _https; public bool? Https { get { return _https; } set { WithHttps(value); } } private string _name; public string Name { get { return _name; } set { WithName(value); } } private int? _offlineDataStagingWindowInTb; public int? OfflineDataStagingWindowInTb { get { return _offlineDataStagingWindowInTb; } set { WithOfflineDataStagingWindowInTb(value); } } private bool? _permitGoingOutOfSync; public bool? PermitGoingOutOfSync { get { return _permitGoingOutOfSync; } set { WithPermitGoingOutOfSync(value); } } private string _proxyDomain; public string ProxyDomain { get { return _proxyDomain; } set { WithProxyDomain(value); } } private string _proxyHost; public string ProxyHost { get { return _proxyHost; } set { WithProxyHost(value); } } private string _proxyPassword; public string ProxyPassword { get { return _proxyPassword; } set { WithProxyPassword(value); } } private int? _proxyPort; public int? ProxyPort { get { return _proxyPort; } set { WithProxyPort(value); } } private string _proxyUsername; public string ProxyUsername { get { return _proxyUsername; } set { WithProxyUsername(value); } } private Quiesced? _quiesced; public Quiesced? Quiesced { get { return _quiesced; } set { WithQuiesced(value); } } private S3Region? _region; public S3Region? Region { get { return _region; } set { WithRegion(value); } } private string _secretKey; public string SecretKey { get { return _secretKey; } set { WithSecretKey(value); } } private int? _stagedDataExpirationInDays; public int? StagedDataExpirationInDays { get { return _stagedDataExpirationInDays; } set { WithStagedDataExpirationInDays(value); } } public ModifyS3TargetSpectraS3Request WithAccessKey(string accessKey) { this._accessKey = accessKey; if (accessKey != null) { this.QueryParams.Add("access_key", accessKey); } else { this.QueryParams.Remove("access_key"); } return this; } public ModifyS3TargetSpectraS3Request WithAutoVerifyFrequencyInDays(int? autoVerifyFrequencyInDays) { this._autoVerifyFrequencyInDays = autoVerifyFrequencyInDays; if (autoVerifyFrequencyInDays != null) { this.QueryParams.Add("auto_verify_frequency_in_days", autoVerifyFrequencyInDays.ToString()); } else { this.QueryParams.Remove("auto_verify_frequency_in_days"); } return this; } public ModifyS3TargetSpectraS3Request WithCloudBucketPrefix(string cloudBucketPrefix) { this._cloudBucketPrefix = cloudBucketPrefix; if (cloudBucketPrefix != null) { this.QueryParams.Add("cloud_bucket_prefix", cloudBucketPrefix); } else { this.QueryParams.Remove("cloud_bucket_prefix"); } return this; } public ModifyS3TargetSpectraS3Request WithCloudBucketSuffix(string cloudBucketSuffix) { this._cloudBucketSuffix = cloudBucketSuffix; if (cloudBucketSuffix != null) { this.QueryParams.Add("cloud_bucket_suffix", cloudBucketSuffix); } else { this.QueryParams.Remove("cloud_bucket_suffix"); } return this; } public ModifyS3TargetSpectraS3Request WithDataPathEndPoint(string dataPathEndPoint) { this._dataPathEndPoint = dataPathEndPoint; if (dataPathEndPoint != null) { this.QueryParams.Add("data_path_end_point", dataPathEndPoint); } else { this.QueryParams.Remove("data_path_end_point"); } return this; } public ModifyS3TargetSpectraS3Request WithDefaultReadPreference(TargetReadPreferenceType? defaultReadPreference) { this._defaultReadPreference = defaultReadPreference; if (defaultReadPreference != null) { this.QueryParams.Add("default_read_preference", defaultReadPreference.ToString()); } else { this.QueryParams.Remove("default_read_preference"); } return this; } public ModifyS3TargetSpectraS3Request WithHttps(bool? https) { this._https = https; if (https != null) { this.QueryParams.Add("https", https.ToString()); } else { this.QueryParams.Remove("https"); } return this; } public ModifyS3TargetSpectraS3Request WithName(string name) { this._name = name; if (name != null) { this.QueryParams.Add("name", name); } else { this.QueryParams.Remove("name"); } return this; } public ModifyS3TargetSpectraS3Request WithOfflineDataStagingWindowInTb(int? offlineDataStagingWindowInTb) { this._offlineDataStagingWindowInTb = offlineDataStagingWindowInTb; if (offlineDataStagingWindowInTb != null) { this.QueryParams.Add("offline_data_staging_window_in_tb", offlineDataStagingWindowInTb.ToString()); } else { this.QueryParams.Remove("offline_data_staging_window_in_tb"); } return this; } public ModifyS3TargetSpectraS3Request WithPermitGoingOutOfSync(bool? permitGoingOutOfSync) { this._permitGoingOutOfSync = permitGoingOutOfSync; if (permitGoingOutOfSync != null) { this.QueryParams.Add("permit_going_out_of_sync", permitGoingOutOfSync.ToString()); } else { this.QueryParams.Remove("permit_going_out_of_sync"); } return this; } public ModifyS3TargetSpectraS3Request WithProxyDomain(string proxyDomain) { this._proxyDomain = proxyDomain; if (proxyDomain != null) { this.QueryParams.Add("proxy_domain", proxyDomain); } else { this.QueryParams.Remove("proxy_domain"); } return this; } public ModifyS3TargetSpectraS3Request WithProxyHost(string proxyHost) { this._proxyHost = proxyHost; if (proxyHost != null) { this.QueryParams.Add("proxy_host", proxyHost); } else { this.QueryParams.Remove("proxy_host"); } return this; } public ModifyS3TargetSpectraS3Request WithProxyPassword(string proxyPassword) { this._proxyPassword = proxyPassword; if (proxyPassword != null) { this.QueryParams.Add("proxy_password", proxyPassword); } else { this.QueryParams.Remove("proxy_password"); } return this; } public ModifyS3TargetSpectraS3Request WithProxyPort(int? proxyPort) { this._proxyPort = proxyPort; if (proxyPort != null) { this.QueryParams.Add("proxy_port", proxyPort.ToString()); } else { this.QueryParams.Remove("proxy_port"); } return this; } public ModifyS3TargetSpectraS3Request WithProxyUsername(string proxyUsername) { this._proxyUsername = proxyUsername; if (proxyUsername != null) { this.QueryParams.Add("proxy_username", proxyUsername); } else { this.QueryParams.Remove("proxy_username"); } return this; } public ModifyS3TargetSpectraS3Request WithQuiesced(Quiesced? quiesced) { this._quiesced = quiesced; if (quiesced != null) { this.QueryParams.Add("quiesced", quiesced.ToString()); } else { this.QueryParams.Remove("quiesced"); } return this; } public ModifyS3TargetSpectraS3Request WithRegion(S3Region? region) { this._region = region; if (region != null) { this.QueryParams.Add("region", region.ToString()); } else { this.QueryParams.Remove("region"); } return this; } public ModifyS3TargetSpectraS3Request WithSecretKey(string secretKey) { this._secretKey = secretKey; if (secretKey != null) { this.QueryParams.Add("secret_key", secretKey); } else { this.QueryParams.Remove("secret_key"); } return this; } public ModifyS3TargetSpectraS3Request WithStagedDataExpirationInDays(int? stagedDataExpirationInDays) { this._stagedDataExpirationInDays = stagedDataExpirationInDays; if (stagedDataExpirationInDays != null) { this.QueryParams.Add("staged_data_expiration_in_days", stagedDataExpirationInDays.ToString()); } else { this.QueryParams.Remove("staged_data_expiration_in_days"); } return this; } public ModifyS3TargetSpectraS3Request(string s3Target) { this.S3Target = s3Target; } internal override HttpVerb Verb { get { return HttpVerb.PUT; } } internal override string Path { get { return "/_rest_/s3_target/" + S3Target; } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for VirtualNetworkPeeringsOperations. /// </summary> public static partial class VirtualNetworkPeeringsOperationsExtensions { /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> public static void Delete(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName) { operations.DeleteAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> public static VirtualNetworkPeering Get(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName) { return operations.GetAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkPeering> GetAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> public static VirtualNetworkPeering CreateOrUpdate(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters) { return operations.CreateOrUpdateAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkPeering> CreateOrUpdateAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> public static IPage<VirtualNetworkPeering> List(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName) { return operations.ListAsync(resourceGroupName, virtualNetworkName).GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkPeering>> ListAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> public static void BeginDelete(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName) { operations.BeginDeleteAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> public static VirtualNetworkPeering BeginCreateOrUpdate(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkPeering> BeginCreateOrUpdateAsync(this IVirtualNetworkPeeringsOperations operations, string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<VirtualNetworkPeering> ListNext(this IVirtualNetworkPeeringsOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkPeering>> ListNextAsync(this IVirtualNetworkPeeringsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using UnityEditor; using System.Collections; #pragma warning disable 0618 // Ignore GvrAudio* deprecation /// A custom editor for properties on the GvrAudioSource script. This appears in the Inspector /// window of a GvrAudioSource object. [CustomEditor(typeof(GvrAudioSource))] [CanEditMultipleObjects] public class GvrAudioSourceEditor : Editor { private SerializedProperty clip = null; private SerializedProperty loop = null; private SerializedProperty mute = null; private SerializedProperty pitch = null; private SerializedProperty playOnAwake = null; private SerializedProperty priority = null; private SerializedProperty spatialBlend = null; private SerializedProperty volume = null; private SerializedProperty dopplerLevel = null; private SerializedProperty spread = null; private SerializedProperty rolloffMode = null; private SerializedProperty maxDistance = null; private SerializedProperty minDistance = null; private SerializedProperty bypassRoomEffects = null; private SerializedProperty directivityAlpha = null; private SerializedProperty directivitySharpness = null; private SerializedProperty listenerDirectivityAlpha = null; private SerializedProperty listenerDirectivitySharpness = null; private Texture2D directivityTexture = null; private SerializedProperty gainDb = null; private SerializedProperty hrtfEnabled = null; private SerializedProperty occlusionEnabled = null; private GUIContent clipLabel = new GUIContent("AudioClip", "The AudioClip asset played by the GvrAudioSource."); private GUIContent loopLabel = new GUIContent("Loop", "Sets the source to loop."); private GUIContent muteLabel = new GUIContent("Mute", "Mutes the sound."); private GUIContent pitchLabel = new GUIContent("Pitch", "Sets the frequency of the sound. Use this to slow down or speed up the sound."); private GUIContent priorityLabel = new GUIContent("Priority", "Sets the priority of the source. Note that a sound with a larger priority value will more " + "likely be stolen by sounds with smaller priority values."); private GUIContent spatialBlendLabel = new GUIContent("Spatial Blend", "Sets how much this source is treated as a 3D source. Setting this value to 0 will ignore " + "distance attenuation and doppler effects. However, it does not affect panning the sound " + "around the listener."); private GUIContent volumeLabel = new GUIContent("Volume", "Sets the overall volume of the sound."); private GUIContent dopplerLevelLabel = new GUIContent("Doppler Level", "Specifies how much the pitch is changed based on the relative velocity between the source " + "and the listener."); private GUIContent spreadLabel = new GUIContent("Spread", "Source spread in degrees."); private GUIContent rolloffModeLabel = new GUIContent("Volume Rolloff", "Which type of rolloff curve to use."); private GUIContent maxDistanceLabel = new GUIContent("Max Distance", "Max distance is the distance a sound stops attenuating at."); private GUIContent minDistanceLabel = new GUIContent("Min Distance", "Within the min distance, the volume will stay at the loudest possible. " + "Outside this min distance it will begin to attenuate."); private GUIContent playOnAwakeLabel = new GUIContent("Play On Awake", "Play the sound when the scene loads."); private GUIContent bypassRoomEffectsLabel = new GUIContent("Bypass Room Effects", "Sets whether the room effects for the source should be bypassed."); private GUIContent directivityLabel = new GUIContent("Directivity", "Controls the pattern of sound emission of the source. This can change the perceived " + "loudness of the source depending on which way it is facing relative to the listener. " + "Patterns are aligned to the 'forward' direction of the parent object."); private GUIContent directivityAlphaLabel = new GUIContent("Alpha", "Controls the balance between dipole pattern and omnidirectional pattern for source " + "emission. By varying this value, differing directivity patterns can be formed."); private GUIContent directivitySharpnessLabel = new GUIContent("Sharpness", "Sets the sharpness of the directivity pattern. Higher values will result in increased " + "directivity."); private GUIContent listenerDirectivityLabel = new GUIContent("Listener Directivity", "Controls the pattern of sound sensitivity of the listener for the source. This can " + "change the perceived loudness of the source depending on which way the listener is facing " + "relative to the source. Patterns are aligned to the 'forward' direction of the listener."); private GUIContent listenerDirectivityAlphaLabel = new GUIContent("Alpha", "Controls the balance between dipole pattern and omnidirectional pattern for listener " + "sensitivity. By varying this value, differing directivity patterns can be formed."); private GUIContent listenerDirectivitySharpnessLabel = new GUIContent("Sharpness", "Sets the sharpness of the listener directivity pattern. Higher values will result in " + "increased directivity."); private GUIContent gainLabel = new GUIContent("Gain (dB)", "Applies a gain to the source for adjustment of relative loudness."); private GUIContent hrtfEnabledLabel = new GUIContent("Enable HRTF", "Sets HRTF binaural rendering for the source. Note that this setting has no effect when " + "stereo quality mode is selected globally."); private GUIContent occlusionLabel = new GUIContent("Enable Occlusion", "Sets whether the sound of the source should be occluded when there are other objects " + "between the source and the listener."); void OnEnable () { clip = serializedObject.FindProperty("sourceClip"); loop = serializedObject.FindProperty("sourceLoop"); mute = serializedObject.FindProperty("sourceMute"); pitch = serializedObject.FindProperty("sourcePitch"); playOnAwake = serializedObject.FindProperty("playOnAwake"); priority = serializedObject.FindProperty("sourcePriority"); spatialBlend = serializedObject.FindProperty("sourceSpatialBlend"); volume = serializedObject.FindProperty("sourceVolume"); dopplerLevel = serializedObject.FindProperty("sourceDopplerLevel"); spread = serializedObject.FindProperty("sourceSpread"); rolloffMode = serializedObject.FindProperty("sourceRolloffMode"); maxDistance = serializedObject.FindProperty("sourceMaxDistance"); minDistance = serializedObject.FindProperty("sourceMinDistance"); bypassRoomEffects = serializedObject.FindProperty("bypassRoomEffects"); directivityAlpha = serializedObject.FindProperty("directivityAlpha"); directivitySharpness = serializedObject.FindProperty("directivitySharpness"); listenerDirectivityAlpha = serializedObject.FindProperty("listenerDirectivityAlpha"); listenerDirectivitySharpness = serializedObject.FindProperty("listenerDirectivitySharpness"); directivityTexture = Texture2D.blackTexture; gainDb = serializedObject.FindProperty("gainDb"); hrtfEnabled = serializedObject.FindProperty("hrtfEnabled"); occlusionEnabled = serializedObject.FindProperty("occlusionEnabled"); } /// @cond public override void OnInspectorGUI () { serializedObject.Update(); // Add clickable script field, as would have been provided by DrawDefaultInspector() MonoScript script = MonoScript.FromMonoBehaviour (target as MonoBehaviour); EditorGUI.BeginDisabledGroup (true); EditorGUILayout.ObjectField ("Script", script, typeof(MonoScript), false); EditorGUI.EndDisabledGroup (); EditorGUILayout.PropertyField(clip, clipLabel); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(mute, muteLabel); EditorGUILayout.PropertyField(bypassRoomEffects, bypassRoomEffectsLabel); EditorGUILayout.PropertyField(playOnAwake, playOnAwakeLabel); EditorGUILayout.PropertyField(loop, loopLabel); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(priority, priorityLabel); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(volume, volumeLabel); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(pitch, pitchLabel); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(spatialBlend, spatialBlendLabel); EditorGUILayout.Separator(); EditorGUILayout.Slider(gainDb, GvrAudio.minGainDb, GvrAudio.maxGainDb, gainLabel); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(dopplerLevel, dopplerLevelLabel); EditorGUILayout.PropertyField(spread, spreadLabel); EditorGUILayout.PropertyField(rolloffMode, rolloffModeLabel); ++EditorGUI.indentLevel; EditorGUILayout.PropertyField(minDistance, minDistanceLabel); EditorGUILayout.PropertyField(maxDistance, maxDistanceLabel); --EditorGUI.indentLevel; if (rolloffMode.enumValueIndex == (int)AudioRolloffMode.Custom) { EditorGUILayout.HelpBox("Custom rolloff mode is not supported, no distance attenuation " + "will be applied.", MessageType.Warning); } EditorGUILayout.Separator(); // Draw the listener directivity properties. EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); GUILayout.Label(listenerDirectivityLabel); ++EditorGUI.indentLevel; EditorGUILayout.Slider(listenerDirectivityAlpha, 0.0f, 1.0f, listenerDirectivityAlphaLabel); EditorGUILayout.Slider(listenerDirectivitySharpness, 1.0f, 10.0f, listenerDirectivitySharpnessLabel); --EditorGUI.indentLevel; EditorGUILayout.EndVertical(); DrawDirectivityPattern(listenerDirectivityAlpha.floatValue, listenerDirectivitySharpness.floatValue, GvrAudio.listenerDirectivityColor, (int)(3.0f * EditorGUIUtility.singleLineHeight)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Separator(); // Draw the source directivity properties. EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); GUILayout.Label(directivityLabel); ++EditorGUI.indentLevel; EditorGUILayout.Slider(directivityAlpha, 0.0f, 1.0f, directivityAlphaLabel); EditorGUILayout.Slider(directivitySharpness, 1.0f, 10.0f, directivitySharpnessLabel); --EditorGUI.indentLevel; EditorGUILayout.EndVertical(); DrawDirectivityPattern(directivityAlpha.floatValue, directivitySharpness.floatValue, GvrAudio.sourceDirectivityColor, (int)(3.0f * EditorGUIUtility.singleLineHeight)); EditorGUILayout.EndHorizontal(); EditorGUILayout.PropertyField(occlusionEnabled, occlusionLabel); EditorGUILayout.Separator(); // HRTF toggle can only be modified through the Inspector in Edit mode. EditorGUI.BeginDisabledGroup (EditorApplication.isPlaying); EditorGUILayout.PropertyField(hrtfEnabled, hrtfEnabledLabel); EditorGUI.EndDisabledGroup (); serializedObject.ApplyModifiedProperties(); } /// @endcond private void DrawDirectivityPattern (float alpha, float sharpness, Color color, int size) { directivityTexture.Resize(size, size); // Draw the axes. Color axisColor = color.a * Color.black; for (int i = 0; i < size; ++i) { directivityTexture.SetPixel(i, size / 2, axisColor); directivityTexture.SetPixel(size / 2, i, axisColor); } // Draw the 2D polar directivity pattern. float offset = 0.5f * size; float cardioidSize = 0.45f * size; Vector2[] vertices = GvrAudio.Generate2dPolarPattern(alpha, sharpness, 180); for (int i = 0; i < vertices.Length; ++i) { directivityTexture.SetPixel((int)(offset + cardioidSize * vertices[i].x), (int)(offset + cardioidSize * vertices[i].y), color); } directivityTexture.Apply(); // Show the texture. GUILayout.Box(directivityTexture); } } #pragma warning restore 0618 // Restore warnings
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections; using System.Diagnostics; using System.Globalization; using System.Net; namespace System.Security.Authentication.ExtendedProtection { public class ServiceNameCollection : ReadOnlyCollectionBase { public ServiceNameCollection(ICollection items) { if (items == null) { throw new ArgumentNullException("items"); } // Normalize and filter for duplicates. foreach (string serviceName in items) { AddIfNew(InnerList, serviceName); } } public ServiceNameCollection Merge(string serviceName) { ArrayList newServiceNames = new ArrayList(); newServiceNames.AddRange(this.InnerList); AddIfNew(newServiceNames, serviceName); ServiceNameCollection newCollection = new ServiceNameCollection(newServiceNames); return newCollection; } public ServiceNameCollection Merge(IEnumerable serviceNames) { ArrayList newServiceNames = new ArrayList(); newServiceNames.AddRange(this.InnerList); // We have a pretty bad performance here: O(n^2), but since service name lists should // be small (<<50) and Merge() should not be called frequently, this shouldn't be an issue. foreach (object item in serviceNames) { AddIfNew(newServiceNames, item as string); } ServiceNameCollection newCollection = new ServiceNameCollection(newServiceNames); return newCollection; } // Normalize, check for duplicates, and add if the value is unique. private static void AddIfNew(ArrayList newServiceNames, string serviceName) { if (String.IsNullOrEmpty(serviceName)) { throw new ArgumentException(SR.security_ServiceNameCollection_EmptyServiceName); } serviceName = NormalizeServiceName(serviceName); if (!Contains(serviceName, newServiceNames)) { newServiceNames.Add(serviceName); } } // Assumes searchServiceName and serviceNames have already been normalized. internal static bool Contains(string searchServiceName, ICollection serviceNames) { Debug.Assert(serviceNames != null); Debug.Assert(!String.IsNullOrEmpty(searchServiceName)); foreach (string serviceName in serviceNames) { if (Match(serviceName, searchServiceName)) { return true; } } return false; } public bool Contains(string searchServiceName) { string searchName = NormalizeServiceName(searchServiceName); return Contains(searchName, InnerList); } // Normalizes any punycode to unicode in an Service Name (SPN) host. // If the algorithm fails at any point then the original input is returned. // ServiceName is in one of the following forms: // prefix/host // prefix/host:port // prefix/host/DistinguishedName // prefix/host:port/DistinguishedName internal static string NormalizeServiceName(string inputServiceName) { if (string.IsNullOrWhiteSpace(inputServiceName)) { return inputServiceName; } // Separate out the prefix int slashIndex = inputServiceName.IndexOf('/'); if (slashIndex < 0) { return inputServiceName; } string prefix = inputServiceName.Substring(0, slashIndex + 1); // Includes slash string hostPortAndDistinguisher = inputServiceName.Substring(slashIndex + 1); // Excludes slash if (string.IsNullOrWhiteSpace(hostPortAndDistinguisher)) { return inputServiceName; } string host = hostPortAndDistinguisher; string port = string.Empty; string distinguisher = string.Empty; // Check for the absence of a port or distinguisher. UriHostNameType hostType = Uri.CheckHostName(hostPortAndDistinguisher); if (hostType == UriHostNameType.Unknown) { string hostAndPort = hostPortAndDistinguisher; // Check for distinguisher. int nextSlashIndex = hostPortAndDistinguisher.IndexOf('/'); if (nextSlashIndex >= 0) { // host:port/distinguisher or host/distinguisher hostAndPort = hostPortAndDistinguisher.Substring(0, nextSlashIndex); // Excludes Slash distinguisher = hostPortAndDistinguisher.Substring(nextSlashIndex); // Includes Slash host = hostAndPort; // We don't know if there is a port yet. // No need to validate the distinguisher. } // Check for port. int colonIndex = hostAndPort.LastIndexOf(':'); // Allow IPv6 addresses. if (colonIndex >= 0) { // host:port host = hostAndPort.Substring(0, colonIndex); // Excludes colon port = hostAndPort.Substring(colonIndex + 1); // Excludes colon // Loosely validate the port just to make sure it was a port and not something else. UInt16 portValue; if (!UInt16.TryParse(port, NumberStyles.Integer, CultureInfo.InvariantCulture, out portValue)) { return inputServiceName; } // Re-include the colon for the final output. Do not change the port format. port = hostAndPort.Substring(colonIndex); } hostType = Uri.CheckHostName(host); // Re-validate the host. } if (hostType != UriHostNameType.Dns) { // UriHostNameType.IPv4, UriHostNameType.IPv6: Do not normalize IPv4/6 hosts. // UriHostNameType.Basic: This is never returned by CheckHostName today // UriHostNameType.Unknown: Nothing recognizable to normalize // default Some new UriHostNameType? return inputServiceName; } // Now we have a valid DNS host, normalize it. Uri constructedUri; // We need to avoid any unexpected exceptions on this code path. if (!Uri.TryCreate(UriScheme.Http + UriScheme.SchemeDelimiter + host, UriKind.Absolute, out constructedUri)) { return inputServiceName; } string normalizedHost = constructedUri.GetComponents( UriComponents.NormalizedHost, UriFormat.SafeUnescaped); string normalizedServiceName = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", prefix, normalizedHost, port, distinguisher); // Don't return the new one unless we absolutely have to. It may have only changed casing. if (Match(inputServiceName, normalizedServiceName)) { return inputServiceName; } return normalizedServiceName; } // Assumes already normalized. internal static bool Match(string serviceName1, string serviceName2) { return (String.Compare(serviceName1, serviceName2, StringComparison.OrdinalIgnoreCase) == 0); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NPOI.SS.UserModel; using System; using System.Text; using NPOI.Util; using NPOI.OpenXmlFormats.Spreadsheet; using System.Text.RegularExpressions; namespace NPOI.XSSF.UserModel { /** * @author <a href="rjankiraman@emptoris.com">Radhakrishnan J</a> * */ public class XSSFDataValidationConstraint : IDataValidationConstraint { /** * Excel validation constraints with static lists are delimited with optional whitespace and the Windows List Separator, * which is typically comma, but can be changed by users. POI will just assume comma. */ private static String LIST_SEPARATOR = ","; private static Regex LIST_SPLIT_REGEX = new Regex("\\s*" + LIST_SEPARATOR + "\\s*"); private static String QUOTE = "\""; private String formula1; private String formula2; private int validationType = -1; private int operator1 = -1; private String[] explicitListOfValues; public XSSFDataValidationConstraint(String[] explicitListOfValues) { if (explicitListOfValues == null || explicitListOfValues.Length == 0) { throw new ArgumentException("List validation with explicit values must specify at least one value"); } this.validationType = ValidationType.LIST; ExplicitListValues = (explicitListOfValues); Validate(); } public XSSFDataValidationConstraint(int validationType, String formula1) : base() { Formula1 = (formula1); this.validationType = validationType; Validate(); } public XSSFDataValidationConstraint(int validationType, int operator1, String formula1) : base() { Formula1 = (formula1); this.validationType = validationType; this.operator1 = operator1; Validate(); } /// <summary> /// This is the constructor called using the OOXML raw data. Excel overloads formula1 to also encode explicit value lists, /// so this constructor has to check for and parse that syntax. /// </summary> /// <param name="validationType"></param> /// <param name="operator1"></param> /// <param name="formula1">Overloaded: formula1 or list of explicit values</param> /// <param name="formula2">formula1 is a list of explicit values, this is ignored: use <code>null</code></param> public XSSFDataValidationConstraint(int validationType, int operator1, String formula1, String formula2) : base() { Formula1 = (formula1); Formula2 = (formula2); this.validationType = validationType; this.operator1 = operator1; Validate(); //FIXME: Need to confirm if this is not a formula. // empirical testing shows Excel saves explicit lists surrounded by double quotes, // range formula expressions can't start with quotes (I think - anyone have a creative counter example?) if (ValidationType.LIST == validationType && formula1 != null && formula1.StartsWith(QUOTE) && formula1.EndsWith(QUOTE)) { String formulaWithoutQuotes = formula1.Substring(1, formula1.Length - 2); explicitListOfValues = LIST_SPLIT_REGEX.Split(formulaWithoutQuotes); } } public String[] ExplicitListValues { get { return explicitListOfValues; } set { this.explicitListOfValues = value; // for OOXML we need to set formula1 to the quoted csv list of values (doesn't appear documented, but that's where Excel puts its lists) // further, Excel has no escaping for commas in explicit lists, so we don't need to worry about that. if (explicitListOfValues != null && explicitListOfValues.Length > 0) { StringBuilder builder = new StringBuilder(QUOTE); for (int i = 0; i < value.Length; i++) { String string1 = value[i]; if (builder.Length > 1) { builder.Append(LIST_SEPARATOR); } builder.Append(string1); } builder.Append(QUOTE); Formula1 = builder.ToString(); } } } /* (non-Javadoc) * @see NPOI.ss.usermodel.DataValidationConstraint#getFormula1() */ public String Formula1 { get { return formula1; } set { this.formula1 = RemoveLeadingEquals(value); } } /* (non-Javadoc) * @see NPOI.ss.usermodel.DataValidationConstraint#getFormula2() */ public String Formula2 { get { return formula2; } set { this.formula2 = RemoveLeadingEquals(value); } } /* (non-Javadoc) * @see NPOI.ss.usermodel.DataValidationConstraint#getOperator() */ public int Operator { get { return operator1; } set { this.operator1 = value; } } /* (non-Javadoc) * @see NPOI.ss.usermodel.DataValidationConstraint#getValidationType() */ public int GetValidationType() { return validationType; } protected static String RemoveLeadingEquals(String formula1) { return IsFormulaEmpty(formula1) ? formula1 : formula1[0] == '=' ? formula1.Substring(1) : formula1; } public void Validate() { if (validationType == ValidationType.ANY) { return; } if (validationType == ValidationType.LIST) { if (IsFormulaEmpty(formula1)) { throw new ArgumentException("A valid formula or a list of values must be specified for list validation."); } } else { if (IsFormulaEmpty(formula1)) { throw new ArgumentException("Formula is not specified. Formula is required for all validation types except explicit list validation."); } if (validationType != ValidationType.FORMULA) { if (operator1 == -1) { throw new ArgumentException("This validation type requires an operator to be specified."); } else if ((operator1 == OperatorType.BETWEEN || operator1 == OperatorType.NOT_BETWEEN) && IsFormulaEmpty(formula2)) { throw new ArgumentException("Between and not between comparisons require two formulae to be specified."); } } } } protected static bool IsFormulaEmpty(String formula1) { return formula1 == null || formula1.Trim().Length == 0; } public String PrettyPrint() { StringBuilder builder = new StringBuilder(); ST_DataValidationType vt = XSSFDataValidation.validationTypeMappings[validationType]; Enum ot = XSSFDataValidation.operatorTypeMappings[operator1]; builder.Append(vt); builder.Append(' '); if (validationType != ValidationType.ANY) { if (validationType != ValidationType.LIST && validationType != ValidationType.ANY && validationType != ValidationType.FORMULA) { builder.Append(LIST_SEPARATOR).Append(ot).Append(", "); } if (validationType == ValidationType.LIST && explicitListOfValues != null) { builder.Append(QUOTE).Append(Arrays.AsList(explicitListOfValues)).Append(QUOTE).Append(' '); } else { builder.Append(QUOTE).Append(formula1).Append(QUOTE).Append(' '); } if (formula2 != null) { builder.Append(QUOTE).Append(formula2).Append(QUOTE).Append(' '); } } return builder.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Text.RegularExpressions; using Xunit; namespace System.Runtime.Serialization.Formatters.Tests { public partial class BinaryFormatterTests : RemoteExecutorTestBase { [Theory] [MemberData(nameof(BasicObjectsRoundtrip_MemberData))] public void ValidateBasicObjectsRoundtrip(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat) { object clone = BinaryFormatterHelpers.Clone(obj, null, assemblyFormat, filterLevel, typeFormat); // string.Empty and DBNull are both singletons if (!ReferenceEquals(obj, string.Empty) && !(obj is DBNull)) { Assert.NotSame(obj, clone); } EqualityExtensions.CheckEquals(obj, clone, isSamePlatform: true); } // Used for updating blobs in BinaryFormatterTestData.cs //[Fact] public void UpdateBlobs() { string testDataFilePath = GetTestDataFilePath(); string[] coreTypeBlobs = SerializableEqualityComparers_MemberData() .Concat(SerializableObjects_MemberData()) .Select(record => BinaryFormatterHelpers.ToBase64String(record[0])) .ToArray(); var (numberOfBlobs, numberOfFoundBlobs, numberOfUpdatedBlobs) = UpdateCoreTypeBlobs(testDataFilePath, coreTypeBlobs); Console.WriteLine($"{numberOfBlobs} existing blobs" + $"{Environment.NewLine}{numberOfFoundBlobs} found blobs with regex search" + $"{Environment.NewLine}{numberOfUpdatedBlobs} updated blobs with regex replace"); } [Theory] [MemberData(nameof(SerializableObjects_MemberData))] public void ValidateAgainstBlobs(object obj, string[] blobs) => ValidateAndRoundtrip(obj, blobs, false); [Theory] [MemberData(nameof(SerializableEqualityComparers_MemberData))] public void ValidateEqualityComparersAgainstBlobs(object obj, string[] blobs) => ValidateAndRoundtrip(obj, blobs, true); private static void ValidateAndRoundtrip(object obj, string[] blobs, bool isEqualityComparer) { if (obj == null) { throw new ArgumentNullException("The serializable object must not be null", nameof(obj)); } if (blobs == null || blobs.Length == 0) { throw new ArgumentOutOfRangeException($"Type {obj} has no blobs to deserialize and test equality against. Blob: " + BinaryFormatterHelpers.ToBase64String(obj, FormatterAssemblyStyle.Full)); } SanityCheckBlob(obj, blobs); // SqlException, ReflectionTypeLoadException and LicenseException aren't deserializable from Desktop --> Core. // Therefore we remove the second blob which is the one from Desktop. if (!PlatformDetection.IsFullFramework && (obj is SqlException || obj is ReflectionTypeLoadException || obj is LicenseException)) { var tmpList = new List<string>(blobs); tmpList.RemoveAt(1); blobs = tmpList.ToArray(); } // We store our framework blobs in index 1 int platformBlobIndex = PlatformDetection.IsFullFramework ? 1 : 0; for (int i = 0; i < blobs.Length; i++) { // Check if the current blob is from the current running platform. bool isSamePlatform = i == platformBlobIndex; if (isEqualityComparer) { ValidateEqualityComparer(BinaryFormatterHelpers.FromBase64String(blobs[i], FormatterAssemblyStyle.Simple)); ValidateEqualityComparer(BinaryFormatterHelpers.FromBase64String(blobs[i], FormatterAssemblyStyle.Full)); } else { EqualityExtensions.CheckEquals(obj, BinaryFormatterHelpers.FromBase64String(blobs[i], FormatterAssemblyStyle.Simple), isSamePlatform); EqualityExtensions.CheckEquals(obj, BinaryFormatterHelpers.FromBase64String(blobs[i], FormatterAssemblyStyle.Full), isSamePlatform); } } } [Fact] public void ArraySegmentDefaultCtor() { // This is workaround for Xunit bug which tries to pretty print test case name and enumerate this object. // When inner array is not initialized it throws an exception when this happens. object obj = new ArraySegment<int>(); string corefxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs="; string netfxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs="; EqualityExtensions.CheckEquals(obj, BinaryFormatterHelpers.FromBase64String(corefxBlob, FormatterAssemblyStyle.Full), isSamePlatform: true); EqualityExtensions.CheckEquals(obj, BinaryFormatterHelpers.FromBase64String(netfxBlob, FormatterAssemblyStyle.Full), isSamePlatform: true); } [Fact] public void ValidateDeserializationOfObjectWithDifferentAssemblyVersion() { // To generate this properly, change AssemblyVersion to a value which is unlikely to happen in production and generate base64(serialized-data) // For this test 9.98.7.987 is being used var obj = new SomeType() { SomeField = 7 }; string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAAA2U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlAQAAAAlTb21lRmllbGQACAIAAAAHAAAACw=="; var deserialized = (SomeType)BinaryFormatterHelpers.FromBase64String(serializedObj, FormatterAssemblyStyle.Simple); Assert.Equal(obj, deserialized); } [Fact] public void ValidateDeserializationOfObjectWithGenericTypeWhichGenericArgumentHasDifferentAssemblyVersion() { // To generate this properly, change AssemblyVersion to a value which is unlikely to happen in production and generate base64(serialized-data) // For this test 9.98.7.987 is being used var obj = new GenericTypeWithArg<SomeType>() { Test = new SomeType() { SomeField = 9 } }; string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAADxAVN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HZW5lcmljVHlwZVdpdGhBcmdgMVtbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAABFRlc3QENlN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Tb21lVHlwZQIAAAACAAAACQMAAAAFAwAAADZTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuU29tZVR5cGUBAAAACVNvbWVGaWVsZAAIAgAAAAkAAAAL"; var deserialized = (GenericTypeWithArg<SomeType>)BinaryFormatterHelpers.FromBase64String(serializedObj, FormatterAssemblyStyle.Simple); Assert.Equal(obj, deserialized); } [Fact] public void RoundtripManyObjectsInOneStream() { object[][] objects = SerializableObjects_MemberData().ToArray(); var s = new MemoryStream(); var f = new BinaryFormatter(); foreach (object[] obj in objects) { f.Serialize(s, obj[0]); } s.Position = 0; foreach (object[] obj in objects) { object clone = f.Deserialize(s); EqualityExtensions.CheckEquals(obj[0], clone, isSamePlatform: true); } } [Fact] public void SameObjectRepeatedInArray() { object o = new object(); object[] arr = new[] { o, o, o, o, o }; object[] result = BinaryFormatterHelpers.Clone(arr); Assert.Equal(arr.Length, result.Length); Assert.NotSame(arr, result); Assert.NotSame(arr[0], result[0]); for (int i = 1; i < result.Length; i++) { Assert.Same(result[0], result[i]); } } [Theory] [MemberData(nameof(NonSerializableTypes_MemberData))] public void ValidateNonSerializableTypes(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat) { var f = new BinaryFormatter() { AssemblyFormat = assemblyFormat, FilterLevel = filterLevel, TypeFormat = typeFormat }; using (var s = new MemoryStream()) { Assert.Throws<SerializationException>(() => f.Serialize(s, obj)); } } [Fact] public void SerializeNonSerializableTypeWithSurrogate() { var p = new NonSerializablePair<int, string>() { Value1 = 1, Value2 = "2" }; Assert.False(p.GetType().IsSerializable); Assert.Throws<SerializationException>(() => BinaryFormatterHelpers.Clone(p)); NonSerializablePair<int, string> result = BinaryFormatterHelpers.Clone(p, new NonSerializablePairSurrogate()); Assert.NotSame(p, result); Assert.Equal(p.Value1, result.Value1); Assert.Equal(p.Value2, result.Value2); } [Fact] public void SerializationEvents_FireAsExpected() { var f = new BinaryFormatter(); var obj = new IncrementCountsDuringRoundtrip(null); Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); using (var s = new MemoryStream()) { f.Serialize(s, obj); s.Position = 0; Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); var result = (IncrementCountsDuringRoundtrip)f.Deserialize(s); Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, result.IncrementedDuringOnSerializingMethod); Assert.Equal(0, result.IncrementedDuringOnSerializedMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod); } } [Fact] public void SerializationEvents_DerivedTypeWithEvents_FireAsExpected() { var f = new BinaryFormatter(); var obj = new DerivedIncrementCountsDuringRoundtrip(null); Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod); using (var s = new MemoryStream()) { f.Serialize(s, obj); s.Position = 0; Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod); var result = (DerivedIncrementCountsDuringRoundtrip)f.Deserialize(s); Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod); Assert.Equal(1, result.IncrementedDuringOnSerializingMethod); Assert.Equal(0, result.IncrementedDuringOnSerializedMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, result.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(0, result.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializedMethod); } } [Fact] public void Properties_Roundtrip() { var f = new BinaryFormatter(); Assert.Null(f.Binder); var binder = new DelegateBinder(); f.Binder = binder; Assert.Same(binder, f.Binder); Assert.NotNull(f.Context); Assert.Null(f.Context.Context); Assert.Equal(StreamingContextStates.All, f.Context.State); var context = new StreamingContext(StreamingContextStates.Clone); f.Context = context; Assert.Equal(StreamingContextStates.Clone, f.Context.State); Assert.Null(f.SurrogateSelector); var selector = new SurrogateSelector(); f.SurrogateSelector = selector; Assert.Same(selector, f.SurrogateSelector); Assert.Equal(FormatterAssemblyStyle.Simple, f.AssemblyFormat); f.AssemblyFormat = FormatterAssemblyStyle.Full; Assert.Equal(FormatterAssemblyStyle.Full, f.AssemblyFormat); Assert.Equal(TypeFilterLevel.Full, f.FilterLevel); f.FilterLevel = TypeFilterLevel.Low; Assert.Equal(TypeFilterLevel.Low, f.FilterLevel); Assert.Equal(FormatterTypeStyle.TypesAlways, f.TypeFormat); f.TypeFormat = FormatterTypeStyle.XsdString; Assert.Equal(FormatterTypeStyle.XsdString, f.TypeFormat); } [Fact] public void SerializeDeserialize_InvalidArguments_ThrowsException() { var f = new BinaryFormatter(); AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Serialize(null, new object())); AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Deserialize(null)); Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream())); // seekable, 0-length } [Theory] [InlineData(FormatterAssemblyStyle.Simple, false)] [InlineData(FormatterAssemblyStyle.Full, true)] public void MissingField_FailsWithAppropriateStyle(FormatterAssemblyStyle style, bool exceptionExpected) { var f = new BinaryFormatter(); var s = new MemoryStream(); f.Serialize(s, new Version1ClassWithoutField()); s.Position = 0; f = new BinaryFormatter() { AssemblyFormat = style }; f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithoutOptionalField) }; if (exceptionExpected) { Assert.Throws<SerializationException>(() => f.Deserialize(s)); } else { var result = (Version2ClassWithoutOptionalField)f.Deserialize(s); Assert.NotNull(result); Assert.Equal(null, result.Value); } } [Theory] [InlineData(FormatterAssemblyStyle.Simple)] [InlineData(FormatterAssemblyStyle.Full)] public void OptionalField_Missing_Success(FormatterAssemblyStyle style) { var f = new BinaryFormatter(); var s = new MemoryStream(); f.Serialize(s, new Version1ClassWithoutField()); s.Position = 0; f = new BinaryFormatter() { AssemblyFormat = style }; f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithOptionalField) }; var result = (Version2ClassWithOptionalField)f.Deserialize(s); Assert.NotNull(result); Assert.Equal(null, result.Value); } [Fact] public void ObjectReference_RealObjectSerialized() { var obj = new ObjRefReturnsObj { Real = 42 }; object real = BinaryFormatterHelpers.Clone<object>(obj); Assert.Equal(42, real); } // Test is disabled becaues it can cause improbable memory allocations leading to interminable paging. // We're keeping the code because it could be useful to a dev making local changes to binary formatter code. //[OuterLoop] //[Theory] //[MemberData(nameof(FuzzInputs_MemberData))] public void Deserialize_FuzzInput(object obj, Random rand) { // Get the serialized data for the object byte[] data = BinaryFormatterHelpers.ToByteArray(obj, FormatterAssemblyStyle.Simple); // Make some "random" changes to it for (int i = 1; i < rand.Next(1, 100); i++) { data[rand.Next(data.Length)] = (byte)rand.Next(256); } // Try to deserialize that. try { BinaryFormatterHelpers.FromByteArray(data, FormatterAssemblyStyle.Simple); // Since there's no checksum, it's possible we changed data that didn't corrupt the instance } catch (ArgumentOutOfRangeException) { } catch (ArrayTypeMismatchException) { } catch (DecoderFallbackException) { } catch (FormatException) { } catch (IndexOutOfRangeException) { } catch (InvalidCastException) { } catch (OutOfMemoryException) { } catch (OverflowException) { } catch (NullReferenceException) { } catch (SerializationException) { } catch (TargetInvocationException) { } catch (ArgumentException) { } catch (FileLoadException) { } } [Fact] public void Deserialize_EndOfStream_ThrowsException() { var f = new BinaryFormatter(); var s = new MemoryStream(); f.Serialize(s, 1024); for (long i = s.Length - 1; i >= 0; i--) { s.Position = 0; byte[] data = new byte[i]; Assert.Equal(data.Length, s.Read(data, 0, data.Length)); Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream(data))); } } [Theory] [MemberData(nameof(CrossProcessObjects_MemberData))] public void Roundtrip_CrossProcess(object obj) { string outputPath = GetTestFilePath(); string inputPath = GetTestFilePath(); // Serialize out to a file using (FileStream fs = File.OpenWrite(outputPath)) { new BinaryFormatter().Serialize(fs, obj); } // In another process, deserialize from that file and serialize to another RemoteInvoke((remoteInput, remoteOutput) => { Assert.False(File.Exists(remoteOutput)); using (FileStream input = File.OpenRead(remoteInput)) using (FileStream output = File.OpenWrite(remoteOutput)) { var b = new BinaryFormatter(); b.Serialize(output, b.Deserialize(input)); return SuccessExitCode; } }, outputPath, inputPath).Dispose(); // Deserialize what the other process serialized and compare it to the original using (FileStream fs = File.OpenRead(inputPath)) { object deserialized = new BinaryFormatter().Deserialize(fs); Assert.Equal(obj, deserialized); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework fails when serializing arrays with non-zero lower bounds")] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "UAPAOT does not support non-zero lower bounds")] public void Roundtrip_ArrayContainingArrayAtNonZeroLowerBound() { BinaryFormatterHelpers.Clone(Array.CreateInstance(typeof(uint[]), new[] { 5 }, new[] { 1 })); } private static void ValidateEqualityComparer(object obj) { Type objType = obj.GetType(); Assert.True(objType.IsGenericType, $"Type `{objType.FullName}` must be generic."); Assert.Equal("System.Collections.Generic.ObjectEqualityComparer`1", objType.GetGenericTypeDefinition().FullName); Assert.Equal(obj.GetType().GetGenericArguments()[0], objType.GetGenericArguments()[0]); } private static void SanityCheckBlob(object obj, string[] blobs) { // These types are unstable during serialization and produce different blobs. if (obj is WeakReference<Point> || obj is Collections.Specialized.HybridDictionary) { return; } // In most cases exceptions in Core have a different layout than in Desktop, // therefore we are skipping the string comparison of the blobs. if (obj is Exception) { return; } // Check if runtime generated blob is the same as the stored one int frameworkBlobNumber = PlatformDetection.IsFullFramework ? 1 : 0; if (frameworkBlobNumber < blobs.Length) { string runtimeBlob = BinaryFormatterHelpers.ToBase64String(obj, FormatterAssemblyStyle.Full); string storedComparableBlob = CreateComparableBlobInfo(blobs[frameworkBlobNumber]); string runtimeComparableBlob = CreateComparableBlobInfo(runtimeBlob); Assert.True(storedComparableBlob == runtimeComparableBlob, $"The stored blob for type {obj.GetType().FullName} is outdated and needs to be updated.{Environment.NewLine}{Environment.NewLine}" + $"-------------------- Stored blob ---------------------{Environment.NewLine}" + $"Encoded: {blobs[frameworkBlobNumber]}{Environment.NewLine}" + $"Decoded: {storedComparableBlob}{Environment.NewLine}{Environment.NewLine}" + $"--------------- Runtime generated blob ---------------{Environment.NewLine}" + $"Encoded: {runtimeBlob}{Environment.NewLine}" + $"Decoded: {runtimeComparableBlob}"); } } private static string GetTestDataFilePath() { string GetRepoRootPath() { var exeFile = new FileInfo(Assembly.GetExecutingAssembly().Location); DirectoryInfo root = exeFile.Directory; while (!Directory.Exists(Path.Combine(root.FullName, ".git"))) { if (root.Parent == null) return null; root = root.Parent; } return root.FullName; } // Get path to binary formatter test data string repositoryRootPath = GetRepoRootPath(); Assert.NotNull(repositoryRootPath); string testDataFilePath = Path.Combine(repositoryRootPath, "src", "System.Runtime.Serialization.Formatters", "tests", "BinaryFormatterTestData.cs"); Assert.True(File.Exists(testDataFilePath)); return testDataFilePath; } private static string CreateComparableBlobInfo(string base64Blob) { string lineSeparator = ((char)0x2028).ToString(); string paragraphSeparator = ((char)0x2029).ToString(); byte[] data = Convert.FromBase64String(base64Blob); base64Blob = Encoding.UTF8.GetString(data); return Regex.Replace(base64Blob, @"Version=\d.\d.\d.\d.", "Version=0.0.0.0", RegexOptions.Multiline) .Replace("\r\n", string.Empty) .Replace("\n", string.Empty) .Replace("\r", string.Empty) .Replace(lineSeparator, string.Empty) .Replace(paragraphSeparator, string.Empty); } private static (int blobs, int foundBlobs, int updatedBlobs) UpdateCoreTypeBlobs(string testDataFilePath, string[] blobs) { // Replace existing test data blobs with updated ones string[] testDataLines = File.ReadAllLines(testDataFilePath); List<string> updatedTestDataLines = new List<string>(); int numberOfBlobs = 0; int numberOfFoundBlobs = 0; int numberOfUpdatedBlobs = 0; for (int i = 0; i < testDataLines.Length; i++) { string testDataLine = testDataLines[i]; if (!testDataLine.Trim().StartsWith("yield") || numberOfBlobs >= blobs.Length) { updatedTestDataLines.Add(testDataLine); continue; } string pattern = null; string replacement = null; if (PlatformDetection.IsFullFramework) { pattern = ", \"AAEAAAD[^\"]+\"(?!,)"; replacement = ", \"" + blobs[numberOfBlobs] + "\""; } else { pattern = "\"AAEAAAD[^\"]+\","; replacement = "\"" + blobs[numberOfBlobs] + "\","; } Regex regex = new Regex(pattern); Match match = regex.Match(testDataLine); if (match.Success) { numberOfFoundBlobs++; } string updatedLine = regex.Replace(testDataLine, replacement); if (testDataLine != updatedLine) { numberOfUpdatedBlobs++; } testDataLine = updatedLine; updatedTestDataLines.Add(testDataLine); numberOfBlobs++; } // Check if all blobs were recognized and write updates to file Assert.Equal(numberOfBlobs, blobs.Length); File.WriteAllLines(testDataFilePath, updatedTestDataLines); return (numberOfBlobs, numberOfFoundBlobs, numberOfUpdatedBlobs); } private class DelegateBinder : SerializationBinder { public Func<string, string, Type> BindToTypeDelegate = null; public override Type BindToType(string assemblyName, string typeName) => BindToTypeDelegate?.Invoke(assemblyName, typeName); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// ExecutionStepResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Studio.V1.Flow.Execution { public class ExecutionStepResource : Resource { private static Request BuildReadRequest(ReadExecutionStepOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Studio, "/v1/Flows/" + options.PathFlowSid + "/Executions/" + options.PathExecutionSid + "/Steps", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all Steps for an Execution. /// </summary> /// <param name="options"> Read ExecutionStep parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ExecutionStep </returns> public static ResourceSet<ExecutionStepResource> Read(ReadExecutionStepOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<ExecutionStepResource>.FromJson("steps", response.Content); return new ResourceSet<ExecutionStepResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Steps for an Execution. /// </summary> /// <param name="options"> Read ExecutionStep parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ExecutionStep </returns> public static async System.Threading.Tasks.Task<ResourceSet<ExecutionStepResource>> ReadAsync(ReadExecutionStepOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<ExecutionStepResource>.FromJson("steps", response.Content); return new ResourceSet<ExecutionStepResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all Steps for an Execution. /// </summary> /// <param name="pathFlowSid"> The SID of the Flow </param> /// <param name="pathExecutionSid"> The SID of the Execution </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ExecutionStep </returns> public static ResourceSet<ExecutionStepResource> Read(string pathFlowSid, string pathExecutionSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadExecutionStepOptions(pathFlowSid, pathExecutionSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Steps for an Execution. /// </summary> /// <param name="pathFlowSid"> The SID of the Flow </param> /// <param name="pathExecutionSid"> The SID of the Execution </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ExecutionStep </returns> public static async System.Threading.Tasks.Task<ResourceSet<ExecutionStepResource>> ReadAsync(string pathFlowSid, string pathExecutionSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadExecutionStepOptions(pathFlowSid, pathExecutionSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<ExecutionStepResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<ExecutionStepResource>.FromJson("steps", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<ExecutionStepResource> NextPage(Page<ExecutionStepResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Studio) ); var response = client.Request(request); return Page<ExecutionStepResource>.FromJson("steps", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<ExecutionStepResource> PreviousPage(Page<ExecutionStepResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Studio) ); var response = client.Request(request); return Page<ExecutionStepResource>.FromJson("steps", response.Content); } private static Request BuildFetchRequest(FetchExecutionStepOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Studio, "/v1/Flows/" + options.PathFlowSid + "/Executions/" + options.PathExecutionSid + "/Steps/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a Step. /// </summary> /// <param name="options"> Fetch ExecutionStep parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ExecutionStep </returns> public static ExecutionStepResource Fetch(FetchExecutionStepOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Retrieve a Step. /// </summary> /// <param name="options"> Fetch ExecutionStep parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ExecutionStep </returns> public static async System.Threading.Tasks.Task<ExecutionStepResource> FetchAsync(FetchExecutionStepOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Retrieve a Step. /// </summary> /// <param name="pathFlowSid"> The SID of the Flow </param> /// <param name="pathExecutionSid"> The SID of the Execution </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ExecutionStep </returns> public static ExecutionStepResource Fetch(string pathFlowSid, string pathExecutionSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchExecutionStepOptions(pathFlowSid, pathExecutionSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Retrieve a Step. /// </summary> /// <param name="pathFlowSid"> The SID of the Flow </param> /// <param name="pathExecutionSid"> The SID of the Execution </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ExecutionStep </returns> public static async System.Threading.Tasks.Task<ExecutionStepResource> FetchAsync(string pathFlowSid, string pathExecutionSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchExecutionStepOptions(pathFlowSid, pathExecutionSid, pathSid); return await FetchAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a ExecutionStepResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> ExecutionStepResource object represented by the provided JSON </returns> public static ExecutionStepResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<ExecutionStepResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the Flow /// </summary> [JsonProperty("flow_sid")] public string FlowSid { get; private set; } /// <summary> /// The SID of the Execution /// </summary> [JsonProperty("execution_sid")] public string ExecutionSid { get; private set; } /// <summary> /// The event that caused the Flow to transition to the Step /// </summary> [JsonProperty("name")] public string Name { get; private set; } /// <summary> /// The current state of the flow /// </summary> [JsonProperty("context")] public object Context { get; private set; } /// <summary> /// The Widget that preceded the Widget for the Step /// </summary> [JsonProperty("transitioned_from")] public string TransitionedFrom { get; private set; } /// <summary> /// The Widget that will follow the Widget for the Step /// </summary> [JsonProperty("transitioned_to")] public string TransitionedTo { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The absolute URL of the resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The URLs of related resources /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } private ExecutionStepResource() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { // enum identifying all predefined methods used in the C# compiler // // Naming convention is PREDEFMETH.PM_ <Predefined CType> _ < Predefined Name of Method> // if methods can only be disambiguated by signature, then follow the // above with _ <argument types> // // Keep this list sorted by containing type and name. internal enum PREDEFMETH { PM_DECIMAL_OPDECREMENT, PM_DECIMAL_OPINCREMENT, PM_DECIMAL_OPUNARYMINUS, PM_DELEGATE_COMBINE, PM_DELEGATE_OPEQUALITY, PM_DELEGATE_OPINEQUALITY, PM_DELEGATE_REMOVE, PM_EXPRESSION_ADD, PM_EXPRESSION_ADD_USER_DEFINED, PM_EXPRESSION_ADDCHECKED, PM_EXPRESSION_ADDCHECKED_USER_DEFINED, PM_EXPRESSION_AND, PM_EXPRESSION_AND_USER_DEFINED, PM_EXPRESSION_ANDALSO, PM_EXPRESSION_ANDALSO_USER_DEFINED, PM_EXPRESSION_ARRAYINDEX, PM_EXPRESSION_ARRAYINDEX2, PM_EXPRESSION_ASSIGN, PM_EXPRESSION_CONSTANT_OBJECT_TYPE, PM_EXPRESSION_CONVERT, PM_EXPRESSION_CONVERT_USER_DEFINED, PM_EXPRESSION_CONVERTCHECKED, PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED, PM_EXPRESSION_DIVIDE, PM_EXPRESSION_DIVIDE_USER_DEFINED, PM_EXPRESSION_EQUAL, PM_EXPRESSION_EQUAL_USER_DEFINED, PM_EXPRESSION_EXCLUSIVEOR, PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED, PM_EXPRESSION_FIELD, PM_EXPRESSION_GREATERTHAN, PM_EXPRESSION_GREATERTHAN_USER_DEFINED, PM_EXPRESSION_GREATERTHANOREQUAL, PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED, PM_EXPRESSION_LAMBDA, PM_EXPRESSION_LEFTSHIFT, PM_EXPRESSION_LEFTSHIFT_USER_DEFINED, PM_EXPRESSION_LESSTHAN, PM_EXPRESSION_LESSTHAN_USER_DEFINED, PM_EXPRESSION_LESSTHANOREQUAL, PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED, PM_EXPRESSION_MODULO, PM_EXPRESSION_MODULO_USER_DEFINED, PM_EXPRESSION_MULTIPLY, PM_EXPRESSION_MULTIPLY_USER_DEFINED, PM_EXPRESSION_MULTIPLYCHECKED, PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED, PM_EXPRESSION_NOTEQUAL, PM_EXPRESSION_NOTEQUAL_USER_DEFINED, PM_EXPRESSION_OR, PM_EXPRESSION_OR_USER_DEFINED, PM_EXPRESSION_ORELSE, PM_EXPRESSION_ORELSE_USER_DEFINED, PM_EXPRESSION_PARAMETER, PM_EXPRESSION_RIGHTSHIFT, PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED, PM_EXPRESSION_SUBTRACT, PM_EXPRESSION_SUBTRACT_USER_DEFINED, PM_EXPRESSION_SUBTRACTCHECKED, PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED, PM_EXPRESSION_UNARYPLUS_USER_DEFINED, PM_EXPRESSION_NEGATE, PM_EXPRESSION_NEGATE_USER_DEFINED, PM_EXPRESSION_NEGATECHECKED, PM_EXPRESSION_NEGATECHECKED_USER_DEFINED, PM_EXPRESSION_CALL, PM_EXPRESSION_NEW, PM_EXPRESSION_NEW_TYPE, PM_EXPRESSION_QUOTE, PM_EXPRESSION_NOT, PM_EXPRESSION_NOT_USER_DEFINED, PM_EXPRESSION_NEWARRAYINIT, PM_EXPRESSION_PROPERTY, PM_EXPRESSION_INVOKE, PM_G_OPTIONAL_CTOR, PM_G_OPTIONAL_GETVALUE, PM_STRING_CONCAT_OBJECT_2, PM_STRING_CONCAT_OBJECT_3, PM_STRING_CONCAT_STRING_2, PM_STRING_OPEQUALITY, PM_STRING_OPINEQUALITY, PM_COUNT } // enum identifying all predefined properties used in the C# compiler // Naming convention is PREDEFMETH.PM_ <Predefined CType> _ < Predefined Name of Property> // Keep this list sorted by containing type and name. internal enum PREDEFPROP { PP_G_OPTIONAL_VALUE, PP_COUNT, }; internal enum MethodCallingConventionEnum { Static, Virtual, Instance } // Enum used to encode a method signature // A signature is encoded as a sequence of int values. // The grammar for signatures is: // // signature // return_type count_of_parameters parameter_types // // type // any predefined type (ex: PredefinedType.PT_OBJECT, PredefinedType.PT_VOID) type_args // MethodSignatureEnum.SIG_CLASS_TYVAR index_of_class_tyvar // MethodSignatureEnum.SIG_METH_TYVAR index_of_method_tyvar // MethodSignatureEnum.SIG_SZ_ARRAY type // MethodSignatureEnum.SIG_REF type // MethodSignatureEnum.SIG_OUT type // internal enum MethodSignatureEnum { // Values 0 to PredefinedType.PT_VOID are reserved for predefined types in signatures // start next value at PredefinedType.PT_VOID + 1, SIG_CLASS_TYVAR = (int)PredefinedType.PT_VOID + 1, // next element in signature is index of class tyvar SIG_METH_TYVAR, // next element in signature is index of method tyvar SIG_SZ_ARRAY // must be followed by signature type of array elements } // A description of a method the compiler uses while compiling. internal sealed class PredefinedMethodInfo { public PREDEFMETH method; public PredefinedType type; public PredefinedName name; public MethodCallingConventionEnum callingConvention; public ACCESS access; // ACCESS.ACC_UNKNOWN means any accessibility is ok public int cTypeVars; public int[] signature; // Size 8. expand this if a new method has a signature which doesn't fit in the current space public PredefinedMethodInfo(PREDEFMETH method, PredefinedType type, PredefinedName name, MethodCallingConventionEnum callingConvention, ACCESS access, int cTypeVars, int[] signature) { this.method = method; this.type = type; this.name = name; this.callingConvention = callingConvention; this.access = access; this.cTypeVars = cTypeVars; this.signature = signature; } } // A description of a method the compiler uses while compiling. internal sealed class PredefinedPropertyInfo { public PREDEFPROP property; public PredefinedName name; public PREDEFMETH getter; public PredefinedPropertyInfo(PREDEFPROP property, PredefinedName name, PREDEFMETH getter) { this.property = property; this.name = name; this.getter = getter; } } // Loads and caches predefined members. // Also finds constructors on delegate types. internal static class PredefinedMembers { private static readonly MethodSymbol[] _methods = new MethodSymbol[(int)PREDEFMETH.PM_COUNT]; private static readonly PropertySymbol[] _properties = new PropertySymbol[(int)PREDEFPROP.PP_COUNT]; private static PropertySymbol LoadProperty(PREDEFPROP property) { PredefinedPropertyInfo info = GetPropInfo(property); return LoadProperty(property, NameManager.GetPredefinedName(info.name), info.getter); } private static PropertySymbol LoadProperty( PREDEFPROP predefProp, Name propertyName, PREDEFMETH propertyGetter) { Debug.Assert(propertyName != null); Debug.Assert(propertyGetter >= 0 && propertyGetter < PREDEFMETH.PM_COUNT); SymbolTable.AddPredefinedPropertyToSymbolTable( GetPredefAgg(GetPropPredefType(predefProp)), propertyName); MethodSymbol getter = GetMethod(propertyGetter); getter.SetMethKind(MethodKindEnum.PropAccessor); PropertySymbol property = getter.getProperty(); Debug.Assert(property != null); return property; } private static AggregateSymbol GetPredefAgg(PredefinedType pt) => SymbolLoader.GetPredefAgg(pt); private static CType LoadTypeFromSignature(int[] signature, ref int indexIntoSignatures, TypeArray classTyVars) { Debug.Assert(signature != null); MethodSignatureEnum current = (MethodSignatureEnum)signature[indexIntoSignatures]; indexIntoSignatures++; switch (current) { case MethodSignatureEnum.SIG_SZ_ARRAY: return TypeManager.GetArray(LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars), 1, true); case MethodSignatureEnum.SIG_METH_TYVAR: return TypeManager.GetStdMethTypeVar(signature[indexIntoSignatures++]); case MethodSignatureEnum.SIG_CLASS_TYVAR: return classTyVars[signature[indexIntoSignatures++]]; case (MethodSignatureEnum)PredefinedType.PT_VOID: return VoidType.Instance; default: Debug.Assert(current >= 0 && (int)current < (int)PredefinedType.PT_COUNT); AggregateSymbol agg = GetPredefAgg((PredefinedType)current); int typeCount = agg.GetTypeVars().Count; if (typeCount == 0) { return TypeManager.GetAggregate(agg, TypeArray.Empty); } CType[] typeArgs = new CType[typeCount]; for (int iTypeArg = 0; iTypeArg < typeArgs.Length; iTypeArg++) { typeArgs[iTypeArg] = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); } return TypeManager.GetAggregate(agg, TypeArray.Allocate(typeArgs)); } } private static TypeArray LoadTypeArrayFromSignature(int[] signature, ref int indexIntoSignatures, TypeArray classTyVars) { Debug.Assert(signature != null); int count = signature[indexIntoSignatures]; indexIntoSignatures++; Debug.Assert(count >= 0); CType[] ptypes = new CType[count]; for (int i = 0; i < ptypes.Length; i++) { ptypes[i] = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); } return TypeArray.Allocate(ptypes); } #if DEBUG static PredefinedMembers() { // validate the tables for (int i = 0; i < (int)PREDEFMETH.PM_COUNT; i++) { Debug.Assert((int)GetMethInfo((PREDEFMETH)i).method == i); } for (int i = 0; i < (int)PREDEFPROP.PP_COUNT; i++) { Debug.Assert((int)GetPropInfo((PREDEFPROP)i).property == i); } } #endif public static PropertySymbol GetProperty(PREDEFPROP property) { Debug.Assert(property >= 0 && property < PREDEFPROP.PP_COUNT); return _properties[(int)property] ?? (_properties[(int)property] = LoadProperty(property)); } public static MethodSymbol GetMethod(PREDEFMETH method) { Debug.Assert(method >= 0 && method < PREDEFMETH.PM_COUNT); return _methods[(int)method] ?? (_methods[(int)method] = LoadMethod(method)); } private static MethodSymbol LoadMethod( AggregateSymbol type, int[] signature, int cMethodTyVars, Name methodName, ACCESS methodAccess, bool isStatic, bool isVirtual ) { Debug.Assert(signature != null); Debug.Assert(cMethodTyVars >= 0); Debug.Assert(methodName != null); Debug.Assert(type != null); TypeArray classTyVars = type.GetTypeVarsAll(); int index = 0; CType returnType = LoadTypeFromSignature(signature, ref index, classTyVars); Debug.Assert(returnType != null); TypeArray argumentTypes = LoadTypeArrayFromSignature(signature, ref index, classTyVars); Debug.Assert(argumentTypes != null); MethodSymbol ret = LookupMethodWhileLoading(type, cMethodTyVars, methodName, methodAccess, isStatic, isVirtual, returnType, argumentTypes); if (ret == null) { SymbolTable.AddPredefinedMethodToSymbolTable(type, methodName); ret = LookupMethodWhileLoading(type, cMethodTyVars, methodName, methodAccess, isStatic, isVirtual, returnType, argumentTypes); } return ret; } private static MethodSymbol LookupMethodWhileLoading(AggregateSymbol type, int cMethodTyVars, Name methodName, ACCESS methodAccess, bool isStatic, bool isVirtual, CType returnType, TypeArray argumentTypes) { for (Symbol sym = SymbolLoader.LookupAggMember(methodName, type, symbmask_t.MASK_ALL); sym != null; sym = sym.LookupNext(symbmask_t.MASK_ALL)) { if (sym is MethodSymbol methsym) { if ((methsym.GetAccess() == methodAccess || methodAccess == ACCESS.ACC_UNKNOWN) && methsym.isStatic == isStatic && methsym.isVirtual == isVirtual && methsym.typeVars.Count == cMethodTyVars && TypeManager.SubstEqualTypes(methsym.RetType, returnType, null, methsym.typeVars, true) && TypeManager.SubstEqualTypeArrays(methsym.Params, argumentTypes, null, methsym.typeVars)) { return methsym; } } } return null; } private static MethodSymbol LoadMethod(PREDEFMETH method) { PredefinedMethodInfo info = GetMethInfo(method); return LoadMethod( GetPredefAgg(info.type), info.signature, info.cTypeVars, NameManager.GetPredefinedName(info.name), info.access, info.callingConvention == MethodCallingConventionEnum.Static, info.callingConvention == MethodCallingConventionEnum.Virtual); } private static PREDEFMETH GetPropGetter(PREDEFPROP property) { PREDEFMETH result = GetPropInfo(property).getter; // getters are MethodRequiredEnum.Required Debug.Assert(result >= 0 && result < PREDEFMETH.PM_COUNT); return result; } private static PredefinedType GetPropPredefType(PREDEFPROP property) { return GetMethInfo(GetPropGetter(property)).type; } // the list of predefined property definitions. // This list must be in the same order as the PREDEFPROP enum. private static readonly PredefinedPropertyInfo[] s_predefinedProperties = { new PredefinedPropertyInfo(PREDEFPROP.PP_G_OPTIONAL_VALUE, PredefinedName.PN_CAP_VALUE, PREDEFMETH.PM_G_OPTIONAL_GETVALUE) }; private static PredefinedPropertyInfo GetPropInfo(PREDEFPROP property) { Debug.Assert(property >= 0 && property < PREDEFPROP.PP_COUNT); Debug.Assert(s_predefinedProperties[(int)property].property == property); return s_predefinedProperties[(int)property]; } private static PredefinedMethodInfo GetMethInfo(PREDEFMETH method) { Debug.Assert(method >= 0 && method < PREDEFMETH.PM_COUNT); Debug.Assert(s_predefinedMethods[(int)method].method == method); return s_predefinedMethods[(int)method]; } // the list of predefined method definitions. // This list must be in the same order as the PREDEFMETH enum. private static readonly PredefinedMethodInfo[] s_predefinedMethods = new PredefinedMethodInfo[(int)PREDEFMETH.PM_COUNT] { new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPDECREMENT, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPDECREMENT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPINCREMENT, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPINCREMENT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPUNARYMINUS, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPUNARYMINUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_COMBINE, PredefinedType.PT_DELEGATE, PredefinedName.PN_COMBINE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }), new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_OPEQUALITY, PredefinedType.PT_DELEGATE, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }), new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_OPINEQUALITY, PredefinedType.PT_DELEGATE, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }), new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_REMOVE, PredefinedType.PT_DELEGATE, PredefinedName.PN_REMOVE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADD, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADDCHECKED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADDCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADDCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_AND, PredefinedType.PT_EXPRESSION, PredefinedName.PN_AND, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_AND, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ANDALSO, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ANDALSO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ANDALSO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYINDEX, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYINDEX, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_METHODCALLEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ASSIGN, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ASSIGN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONSTANT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CONSTANTEXPRESSION, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_TYPE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERT, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_DIVIDE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_DIVIDE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_DIVIDE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EQUAL, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXCLUSIVEOR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXCLUSIVEOR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_FIELD, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CAP_FIELD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_MEMBEREXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_FIELDINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHAN, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LAMBDA, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LAMBDA, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 1, new int[] { (int)PredefinedType.PT_G_EXPRESSION, (int)MethodSignatureEnum.SIG_METH_TYVAR, 0, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_PARAMETEREXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LEFTSHIFT, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LEFTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LEFTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHAN, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MODULO, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MODULO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MODULO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLY, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLYCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLYCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOTEQUAL, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOTEQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOTEQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_OR, PredefinedType.PT_EXPRESSION, PredefinedName.PN_OR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_OR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ORELSE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ORELSE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ORELSE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_PARAMETER, PredefinedType.PT_EXPRESSION, PredefinedName.PN_PARAMETER, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_PARAMETEREXPRESSION, 2, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT, PredefinedType.PT_EXPRESSION, PredefinedName.PN_RIGHTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_RIGHTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACT, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_PLUS , MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATECHECKED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATECHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATECHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CALL, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CALL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_METHODCALLEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 2, (int)PredefinedType.PT_CONSTRUCTORINFO, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW_TYPE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 1, (int)PredefinedType.PT_TYPE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_QUOTE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_QUOTE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOT, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEWARRAYINIT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWARRAYEXPRESSION, 2, (int)PredefinedType.PT_TYPE, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_PROPERTY, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXPRESSION_PROPERTY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_MEMBEREXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_PROPERTYINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_INVOKE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_INVOKE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INVOCATIONEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_CTOR, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_CTOR, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_VOID, 1, (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GETVALUE, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GETVALUE, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_2, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_3, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 3, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_2, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_OPEQUALITY, PredefinedType.PT_STRING, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_OPINEQUALITY, PredefinedType.PT_STRING, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), }; } }
//----------------------------------------------------------------------- // <copyright file="MeshOcclusionUIController.cs" company="Google"> // // Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading; using System.Xml; using System.Xml.Serialization; using Tango; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; /// <summary> /// Occlusion test controller. /// </summary> public class MeshOcclusionUIController : MonoBehaviour, ITangoLifecycle, ITangoPose { /// <summary> /// The object that is used to test occlusion. /// </summary> [Header("Marker Objects")] public GameObject m_markerObject; /// <summary> /// The canvas panel used during mesh construction. /// </summary> [Header("UI Elements")] public GameObject m_meshBuildPanel; /// <summary> /// The canvas panel used for interaction after Area Description and mesh have been loaded. /// </summary> public GameObject m_meshInteractionPanel; /// <summary> /// The canvas button that changes the mesh to a visible material. /// </summary> public GameObject m_viewMeshButton; /// <summary> /// The canvas button that change the mesh to depth mask. /// </summary> public GameObject m_hideMeshButton; /// <summary> /// The image overlay shown while waiting to relocalize to Area Description. /// </summary> public Image m_relocalizeImage; /// <summary> /// The text overlay that is shown when the Area Description or mesh is being saved. /// </summary> public Text m_savingText; /// <summary> /// The button to create new mesh with selected Area Description, available only if an Area Description is selected. /// </summary> public Button m_createSelectedButton; /// <summary> /// The button to begin using an Area Description and mesh. Interactable only when an Area Description with mesh is selected. /// </summary> public Button m_startGameButton; /// <summary> /// The parent panel that loads the selected Area Description. /// </summary> [Header("Area Description Loader")] public GameObject m_areaDescriptionLoaderPanel; /// <summary> /// The prefab of a standard button in the scrolling list. /// </summary> public GameObject m_listElement; /// <summary> /// The container panel of the Tango space Area Description scrolling list. /// </summary> public RectTransform m_listContentParent; /// <summary> /// Toggle group for the Area Description list. /// /// You can only toggle one Area Description at a time. After we get the list of Area Description from Tango, /// they are all added to this toggle group. /// </summary> public ToggleGroup m_toggleGroup; /// <summary> /// The reference to the depth mask material to be applied to the mesh. /// </summary> [Header("Materials")] public Material m_depthMaskMat; /// <summary> /// The reference to the visible material applied to the mesh. /// </summary> public Material m_visibleMat; /// <summary> /// The tango dynamic mesh used for occlusion. /// </summary> private TangoDynamicMesh m_tangoDynamicMesh; /// <summary> /// The loaded mesh reconstructed from the serialized AreaDescriptionMesh file. /// </summary> private GameObject m_meshFromFile; /// <summary> /// The Area Description currently loaded in the Tango Service. /// </summary> private AreaDescription m_curAreaDescription; /// <summary> /// The AR pose controller. /// </summary> private TangoPoseController m_poseController; /// <summary> /// The tango application, to create and clear 3d construction. /// </summary> private TangoApplication m_tangoApplication; /// <summary> /// The thread used to save the Area Description. /// </summary> private Thread m_saveThread; /// <summary> /// If the interaction is initialized. /// /// Note that the initialization is triggered by the relocalization event. We don't want user to place object before /// the device is relocalized. /// </summary> private bool m_initialized = false; /// <summary> /// The check whether user has selected to create a new mesh or start the game with an existing one. /// </summary> private bool m_3dReconstruction = false; /// <summary> /// The check whether the menu is currently open. Determines the back button behavior. /// </summary> private bool m_menuOpen = true; /// <summary> /// The UUID of the selected Area Description. /// </summary> private string m_savedUUID; /// <summary> /// The path where the generated meshes are saved. /// </summary> private string m_meshSavePath; /// <summary> /// Start is called on the frame when a script is enabled just before any of the Update methods is called the first time. /// </summary> public void Start() { m_meshSavePath = Application.persistentDataPath + "/meshes"; Directory.CreateDirectory(m_meshSavePath); m_poseController = FindObjectOfType<TangoPoseController>(); m_tangoDynamicMesh = FindObjectOfType<TangoDynamicMesh>(); m_areaDescriptionLoaderPanel.SetActive(true); m_meshBuildPanel.SetActive(false); m_meshInteractionPanel.SetActive(false); m_relocalizeImage.gameObject.SetActive(false); // Initialize tango application. m_tangoApplication = FindObjectOfType<TangoApplication>(); if (m_tangoApplication != null) { m_tangoApplication.Register(this); if (AndroidHelper.IsTangoCorePresent()) { m_tangoApplication.RequestPermissions(); } } } /// <summary> /// Update is called once per frame. /// Return to menu or quit current application when back button is triggered. /// </summary> public void Update() { if (Input.GetKey(KeyCode.Escape)) { if (m_menuOpen) { // This is a fix for a lifecycle issue where calling // Application.Quit() here, and restarting the application // immediately results in a deadlocked app. AndroidHelper.AndroidQuit(); } else { #pragma warning disable 618 Application.LoadLevel(Application.loadedLevel); #pragma warning restore 618 } } } /// <summary> /// Application onPause / onResume callback. /// </summary> /// <param name="pauseStatus"><c>true</c> if the application about to pause, otherwise <c>false</c>.</param> public void OnApplicationPause(bool pauseStatus) { if (pauseStatus && m_initialized) { // When application is backgrounded, we reload the level because the Tango Service is disconected. All // learned area and placed marker should be discarded as they are not saved. #pragma warning disable 618 Application.LoadLevel(Application.loadedLevel); #pragma warning restore 618 } } /// <summary> /// Unity destroy function. /// </summary> public void OnDestroy() { if (m_tangoApplication != null) { m_tangoApplication.Unregister(this); } } /// <summary> /// Internal callback when a permissions event happens. /// </summary> /// <param name="permissionsGranted">If set to <c>true</c> permissions granted.</param> public void OnTangoPermissions(bool permissionsGranted) { if (permissionsGranted) { m_tangoApplication.Set3DReconstructionEnabled(false); m_poseController.gameObject.SetActive(false); _PopulateAreaDescriptionUIList(); } else { AndroidHelper.ShowAndroidToastMessage("Motion Tracking and Area Learning Permissions Needed"); Application.Quit(); } } /// <summary> /// This is called when successfully connected to the Tango service. /// </summary> public void OnTangoServiceConnected() { } /// <summary> /// This is called when disconnected from the Tango service. /// </summary> public void OnTangoServiceDisconnected() { } /// <summary> /// OnTangoPoseAvailable event from Tango. /// /// In this function, we only listen to the Start-Of-Service with respect to Area-Description frame pair. This pair /// indicates a relocalization or loop closure event happened, base on that, we either start the initialize the /// interaction or begin meshing if applicable. /// </summary> /// <param name="poseData">Returned pose data from TangoService.</param> public void OnTangoPoseAvailable(Tango.TangoPoseData poseData) { // This frame pair's callback indicates that a loop closure or relocalization has happened. // // When learning mode is off, and an Area Description is loaded, this callback indicates a relocalization event. // In our case, when the device is relocalized, user interaction is allowed and meshing starts if applicable. if (poseData.framePair.baseFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION && poseData.framePair.targetFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE && poseData.status_code == TangoEnums.TangoPoseStatusType.TANGO_POSE_VALID) { // When we get the first loop closure/ relocalization event, we initialized all the in-game interactions. if (!m_initialized) { Debug.Log("First loop closure/relocalization"); m_initialized = true; m_relocalizeImage.gameObject.SetActive(false); if (m_3dReconstruction) { m_tangoApplication.Set3DReconstructionEnabled(true); } else { m_tangoApplication.Set3DReconstructionEnabled(false); } } } } /// <summary> /// From button press: start creating a mesh for occlusion. /// /// If an Area Description has been selected, use it and link it to the dynamic mesh. /// If no Area Description selected, create one while meshing. /// </summary> /// <param name="createNew">If set to <c>true</c> create new mesh and new Area Description.</param> public void Button_CreateAreaDescriptionMesh(bool createNew) { m_3dReconstruction = true; m_menuOpen = false; // Enable the pose controller, but disable the AR screen. m_poseController.gameObject.SetActive(true); m_poseController.gameObject.GetComponent<TangoARScreen>().enabled = false; // Need to enable depth to build the mesh. m_tangoApplication.m_enableDepth = true; // Set UI panel to the mesh construction panel. m_areaDescriptionLoaderPanel.SetActive(false); m_meshBuildPanel.SetActive(true); m_meshInteractionPanel.SetActive(false); // Initialize tango application and pose controller depending on whether Area Description has been selected. if (createNew) { m_curAreaDescription = null; m_tangoApplication.m_areaDescriptionLearningMode = true; m_poseController.m_baseFrameMode = TangoPoseController.BaseFrameSelectionModeEnum.USE_START_OF_SERVICE; m_relocalizeImage.gameObject.SetActive(false); m_tangoApplication.Startup(null); } else { if (!string.IsNullOrEmpty(m_savedUUID)) { m_curAreaDescription = AreaDescription.ForUUID(m_savedUUID); m_tangoApplication.m_areaDescriptionLearningMode = false; m_poseController.m_baseFrameMode = TangoPoseController.BaseFrameSelectionModeEnum.USE_AREA_DESCRIPTION; m_relocalizeImage.gameObject.SetActive(true); m_tangoApplication.Startup(m_curAreaDescription); } else { Debug.LogError("No Area Description loaded."); } } } /// <summary> /// From button press: start the game by loading the mesh and the Area Description. /// /// Generate a new mesh from the saved area definition mesh data linked to the selected Area Description. /// </summary> public void Button_StartAreaDescriptionMesh() { if (string.IsNullOrEmpty(m_savedUUID)) { AndroidHelper.ShowAndroidToastMessage("Please choose an Area Description."); return; } if (!File.Exists(m_meshSavePath + "/" + m_savedUUID)) { AndroidHelper.ShowAndroidToastMessage("Please choose an Area Description with mesh data."); return; } m_3dReconstruction = false; m_menuOpen = false; // Enable objects needed to use Area Description and mesh for occlusion. m_poseController.gameObject.SetActive(true); m_poseController.m_baseFrameMode = TangoPoseController.BaseFrameSelectionModeEnum.USE_AREA_DESCRIPTION; // Disable unused components in tango application. m_tangoApplication.m_areaDescriptionLearningMode = false; m_tangoApplication.m_enableDepth = false; // Set UI panel to the mesh interaction panel. m_relocalizeImage.gameObject.SetActive(true); m_areaDescriptionLoaderPanel.SetActive(false); m_meshBuildPanel.SetActive(false); m_meshInteractionPanel.SetActive(true); // Load mesh. AreaDescriptionMesh mesh = _DeserializeAreaDescriptionMesh(m_savedUUID); if (mesh == null) { return; } // Create GameObject container with mesh components for the loaded mesh. m_meshFromFile = new GameObject(); MeshFilter mf = m_meshFromFile.AddComponent<MeshFilter>(); mf.mesh = _AreaDescriptionMeshToUnityMesh(mesh); MeshRenderer mr = m_meshFromFile.AddComponent<MeshRenderer>(); mr.material = m_depthMaskMat; m_meshFromFile.AddComponent<MeshCollider>(); m_meshFromFile.layer = LayerMask.NameToLayer("Occlusion"); // Load Area Description file. m_curAreaDescription = AreaDescription.ForUUID(m_savedUUID); m_tangoApplication.Startup(m_curAreaDescription); } /// <summary> /// From button press: delete all saved meshes associated with area definitions. /// </summary> public void Button_DeleteAllAreaDescriptionMeshes() { string[] filePaths = Directory.GetFiles(m_meshSavePath); foreach (string filePath in filePaths) { File.Delete(filePath); } AndroidHelper.ShowAndroidToastMessage("All Area Description meshes have been deleted."); #pragma warning disable 618 Application.LoadLevel(Application.loadedLevel); #pragma warning restore 618 } /// <summary> /// Clear the 3D mesh on canvas button press. /// </summary> public void Button_Clear() { m_tangoDynamicMesh.Clear(); m_tangoApplication.Tango3DRClear(); AndroidHelper.ShowAndroidToastMessage("Mesh cleared."); } /// <summary> /// Finalize the 3D mesh on canvas button press. /// </summary> public void Button_Finalize() { m_tangoApplication.Set3DReconstructionEnabled(false); m_meshBuildPanel.SetActive(false); m_savingText.gameObject.SetActive(true); StartCoroutine(_DoSaveAreaDescriptionAndMesh()); } /// <summary> /// Set the marker object at the raycast location when the user has interacted with the image overlay. /// </summary> /// <param name="data">Event data from canvas event trigger.</param> public void Image_PlaceMarker(BaseEventData data) { PointerEventData pdata = (PointerEventData)data; // Place marker object at target point hit by raycast. RaycastHit hit; if (Physics.Raycast(Camera.main.ScreenPointToRay(pdata.position), out hit, Mathf.Infinity)) { m_markerObject.SetActive(true); m_markerObject.transform.position = hit.point; m_markerObject.transform.up = hit.normal; } } /// <summary> /// Show the mesh as visible. /// </summary> public void Button_ViewMesh() { m_meshFromFile.GetComponent<MeshRenderer>().material = m_visibleMat; m_viewMeshButton.SetActive(false); m_hideMeshButton.SetActive(true); } /// <summary> /// Set the mesh as masked. /// </summary> public void Button_HideMesh() { m_meshFromFile.GetComponent<MeshRenderer>().material = m_depthMaskMat; m_viewMeshButton.SetActive(true); m_hideMeshButton.SetActive(false); } /// <summary> /// Exit the game and return to mesh selection. /// </summary> public void Button_Exit() { #pragma warning disable 618 Application.LoadLevel(Application.loadedLevel); #pragma warning restore 618 } /// <summary> /// Populate a scrolling list with Area Descriptions. Each element will check if there is any associated /// mesh data tied to the Area Description by UUID. The Area Description file and linked mesh data are /// loaded when starting the game. /// </summary> private void _PopulateAreaDescriptionUIList() { // Load Area Descriptions. foreach (Transform t in m_listContentParent.transform) { Destroy(t.gameObject); } // Update Tango space Area Description list. AreaDescription[] areaDescriptionList = AreaDescription.GetList(); if (areaDescriptionList == null) { return; } foreach (AreaDescription areaDescription in areaDescriptionList) { GameObject newElement = Instantiate(m_listElement) as GameObject; MeshOcclusionAreaDescriptionListElement listElement = newElement.GetComponent<MeshOcclusionAreaDescriptionListElement>(); listElement.m_toggle.group = m_toggleGroup; listElement.m_areaDescriptionName.text = areaDescription.GetMetadata().m_name; listElement.m_areaDescriptionUUID.text = areaDescription.m_uuid; // Check if there is an associated Area Description mesh. bool hasMeshData = File.Exists(m_meshSavePath + "/" + areaDescription.m_uuid) ? true : false; listElement.m_hasMeshData.gameObject.SetActive(hasMeshData); // Ensure the lambda makes a copy of areaDescription. AreaDescription lambdaParam = areaDescription; listElement.m_toggle.onValueChanged.AddListener((value) => _OnToggleChanged(lambdaParam, value)); newElement.transform.SetParent(m_listContentParent.transform, false); } } /// <summary> /// Callback function when toggle button is selected. /// </summary> /// <param name="item">Caller item object.</param> /// <param name="value">Selected value of the toggle button.</param> private void _OnToggleChanged(AreaDescription item, bool value) { if (value) { m_savedUUID = item.m_uuid; m_createSelectedButton.interactable = true; if (File.Exists(m_meshSavePath + "/" + item.m_uuid)) { m_startGameButton.interactable = true; } else { m_startGameButton.interactable = false; } } else { m_savedUUID = null; m_createSelectedButton.interactable = false; m_startGameButton.interactable = false; } } /// <summary> /// Actually do the Area Description save. /// </summary> /// <returns>Coroutine IEnumerator.</returns> private IEnumerator _DoSaveAreaDescriptionAndMesh() { if (m_saveThread != null) { yield break; } // Disable interaction before saving. m_initialized = false; m_savingText.text = "Saving Area Description..."; if (string.IsNullOrEmpty(m_savedUUID)) { m_saveThread = new Thread(delegate() { // Save the Area Description to file. m_curAreaDescription = AreaDescription.SaveCurrent(); AreaDescription.Metadata metadata = m_curAreaDescription.GetMetadata(); m_savedUUID = m_curAreaDescription.m_uuid; metadata.m_name = metadata.m_dateTime.ToLongTimeString(); m_curAreaDescription.SaveMetadata(metadata); }); m_saveThread.Start(); while (m_saveThread.IsAlive) { yield return null; } // Save the tango dynamic mesh to file. StartCoroutine(_DoSaveTangoDynamicMesh()); } else { StartCoroutine(_DoSaveTangoDynamicMesh()); } } /// <summary> /// Save the tango dynamic mesh. /// /// Process the mesh in 3 steps. /// 1. Extract the whole mesh from tango 3D Reconstruction. /// 2. Convert to a serializable format. /// 3. Serialize with XML on to the SD card. /// </summary> /// <returns>The coroutine IEnumerator.</returns> private IEnumerator _DoSaveTangoDynamicMesh() { m_savingText.gameObject.SetActive(true); m_savingText.text = "Extracting Whole Mesh..."; // Each list is filled out with values from extracting the whole mesh. List<Vector3> vertices = new List<Vector3>(); List<int> triangles = new List<int>(); Tango3DReconstruction.Status status = m_tangoApplication.Tango3DRExtractWholeMesh(vertices, null, null, triangles); if (status != Tango3DReconstruction.Status.SUCCESS) { Debug.Log("Tango3DRExtractWholeMesh failed, status code = " + status); yield break; } Debug.Log("Tango3DRExtractWholeMesh finished"); Mesh extractedMesh = new Mesh(); extractedMesh.vertices = vertices.ToArray(); extractedMesh.triangles = triangles.ToArray(); // Save the generated unity mesh. m_savingText.text = "Saving Area Description Mesh..."; AreaDescriptionMesh mesh = _UnityMeshToAreaDescriptionMesh(m_savedUUID, extractedMesh); _SerializeAreaDescriptionMesh(mesh); // Restart scene after completion. #pragma warning disable 618 Application.LoadLevel(Application.loadedLevel); #pragma warning restore 618 } /// <summary> /// Convert a unity mesh to an Area Description mesh. /// </summary> /// <returns>The Area Description mesh.</returns> /// <param name="uuid">The Area Description UUID.</param> /// <param name="mesh">The Unity mesh.</param> private AreaDescriptionMesh _UnityMeshToAreaDescriptionMesh(string uuid, Mesh mesh) { AreaDescriptionMesh saveMesh = new AreaDescriptionMesh(); saveMesh.m_uuid = m_savedUUID; saveMesh.m_vertices = mesh.vertices; saveMesh.m_triangles = mesh.triangles; return saveMesh; } /// <summary> /// Convert an Area Description mesh to a unity mesh. /// </summary> /// <returns>The unity mesh.</returns> /// <param name="saveMesh">The Area Description mesh.</param> private Mesh _AreaDescriptionMeshToUnityMesh(AreaDescriptionMesh saveMesh) { Mesh mesh = new Mesh(); mesh.vertices = saveMesh.m_vertices; mesh.triangles = saveMesh.m_triangles; mesh.RecalculateNormals(); return mesh; } /// <summary> /// Serialize an Area Description mesh to file. /// </summary> /// <param name="saveMesh">The Area Description mesh to serialize.</param> private void _SerializeAreaDescriptionMesh(AreaDescriptionMesh saveMesh) { XmlSerializer serializer = new XmlSerializer(typeof(AreaDescriptionMesh)); FileStream file = File.Create(m_meshSavePath + "/" + saveMesh.m_uuid); serializer.Serialize(file, saveMesh); file.Close(); } /// <summary> /// Deserialize an Area Description mesh from file. /// </summary> /// <returns>The loaded Area Description mesh.</returns> /// <param name="uuid">The UUID of the associated Area Description.</param> private AreaDescriptionMesh _DeserializeAreaDescriptionMesh(string uuid) { if (File.Exists(m_meshSavePath + "/" + uuid)) { XmlSerializer serializer = new XmlSerializer(typeof(AreaDescriptionMesh)); FileStream file = File.Open(m_meshSavePath + "/" + uuid, FileMode.Open); AreaDescriptionMesh saveMesh = serializer.Deserialize(file) as AreaDescriptionMesh; file.Close(); return saveMesh; } return null; } /// <summary> /// Xml container for vertices and triangles from extracted mesh and linked Area Description. /// </summary> [XmlRoot("AreaDescriptionMesh")] public class AreaDescriptionMesh { /// <summary> /// The UUID of the linked Area Description. /// </summary> public string m_uuid; /// <summary> /// The mesh vertices. /// </summary> public Vector3[] m_vertices; /// <summary> /// The mesh triangles. /// </summary> public int[] m_triangles; } }
// 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.Linq; using Xunit; namespace System.Collections.Tests { /// <summary> /// Contains tests that ensure the correctness of any class that implements the generic /// ICollection interface /// </summary> public abstract class ICollection_Generic_Tests<T> : IEnumerable_Generic_Tests<T> { #region ICollection<T> Helper Methods /// <summary> /// Creates an instance of an ICollection{T} that can be used for testing. /// </summary> /// <returns>An instance of an ICollection{T} that can be used for testing.</returns> protected abstract ICollection<T> GenericICollectionFactory(); /// <summary> /// Creates an instance of an ICollection{T} that can be used for testing. /// </summary> /// <param name="count">The number of unique items that the returned ICollection{T} contains.</param> /// <returns>An instance of an ICollection{T} that can be used for testing.</returns> protected virtual ICollection<T> GenericICollectionFactory(int count) { ICollection<T> collection = GenericICollectionFactory(); AddToCollection(collection, count); return collection; } protected virtual bool DuplicateValuesAllowed => true; protected virtual bool DefaultValueWhenNotAllowed_Throws => true; protected virtual bool IsReadOnly => false; protected virtual bool IsReadOnly_ValidityValue => IsReadOnly; protected virtual bool AddRemoveClear_ThrowsNotSupported => false; protected virtual bool DefaultValueAllowed => true; protected virtual IEnumerable<T> InvalidValues => Array.Empty<T>(); protected virtual void AddToCollection(ICollection<T> collection, int numberOfItemsToAdd) { int seed = 9600; IEqualityComparer<T> comparer = GetIEqualityComparer(); while (collection.Count < numberOfItemsToAdd) { T toAdd = CreateT(seed++); while (collection.Contains(toAdd, comparer) || InvalidValues.Contains(toAdd, comparer)) toAdd = CreateT(seed++); collection.Add(toAdd); } } protected virtual Type ICollection_Generic_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentException); #endregion #region IEnumerable<T> Helper Methods protected override IEnumerable<T> GenericIEnumerableFactory(int count) { return GenericICollectionFactory(count); } /// <summary> /// Returns a set of ModifyEnumerable delegates that modify the enumerable passed to them. /// </summary> protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) { if (!AddRemoveClear_ThrowsNotSupported && (operations & ModifyOperation.Add) == ModifyOperation.Add) { yield return (IEnumerable<T> enumerable) => { var casted = (ICollection<T>)enumerable; casted.Add(CreateT(2344)); return true; }; } if (!AddRemoveClear_ThrowsNotSupported && (operations & ModifyOperation.Remove) == ModifyOperation.Remove) { yield return (IEnumerable<T> enumerable) => { var casted = (ICollection<T>)enumerable; if (casted.Count() > 0) { casted.Remove(casted.ElementAt(0)); return true; } return false; }; } if (!AddRemoveClear_ThrowsNotSupported && (operations & ModifyOperation.Clear) == ModifyOperation.Clear) { yield return (IEnumerable<T> enumerable) => { var casted = (ICollection<T>)enumerable; if (casted.Count() > 0) { casted.Clear(); return true; } return false; }; } } #endregion #region IsReadOnly [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_IsReadOnly_Validity(int count) { ICollection<T> collection = GenericICollectionFactory(count); Assert.Equal(IsReadOnly_ValidityValue , collection.IsReadOnly); } #endregion #region Count [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Count_Validity(int count) { ICollection<T> collection = GenericICollectionFactory(count); Assert.Equal(count, collection.Count); } #endregion #region Add [Theory] [MemberData(nameof(ValidCollectionSizes))] public virtual void ICollection_Generic_Add_DefaultValue(int count) { if (DefaultValueAllowed && !IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { ICollection<T> collection = GenericICollectionFactory(count); collection.Add(default(T)); Assert.Equal(count + 1, collection.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Add_InvalidValueToMiddleOfCollection(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { Assert.All(InvalidValues, invalidValue => { ICollection<T> collection = GenericICollectionFactory(count); collection.Add(invalidValue); for (int i = 0; i < count; i++) collection.Add(CreateT(i)); Assert.Equal(count * 2, collection.Count); }); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Add_InvalidValueToBeginningOfCollection(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { Assert.All(InvalidValues, invalidValue => { ICollection<T> collection = GenericICollectionFactory(0); collection.Add(invalidValue); for (int i = 0; i < count; i++) collection.Add(CreateT(i)); Assert.Equal(count, collection.Count); }); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Add_InvalidValueToEndOfCollection(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { Assert.All(InvalidValues, invalidValue => { ICollection<T> collection = GenericICollectionFactory(count); collection.Add(invalidValue); Assert.Equal(count, collection.Count); }); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Add_DuplicateValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported && DuplicateValuesAllowed) { ICollection<T> collection = GenericICollectionFactory(count); T duplicateValue = CreateT(700); collection.Add(duplicateValue); collection.Add(duplicateValue); Assert.Equal(count + 2, collection.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Add_AfterCallingClear(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { ICollection<T> collection = GenericICollectionFactory(count); collection.Clear(); AddToCollection(collection, 5); Assert.Equal(5, collection.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Add_AfterRemovingAnyValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { int seed = 840; ICollection<T> collection = GenericICollectionFactory(count); List<T> items = collection.ToList(); T toAdd = CreateT(seed++); while (collection.Contains(toAdd)) toAdd = CreateT(seed++); collection.Add(toAdd); collection.Remove(toAdd); toAdd = CreateT(seed++); while (collection.Contains(toAdd)) toAdd = CreateT(seed++); collection.Add(toAdd); items.Add(toAdd); CollectionAsserts.EqualUnordered(items, collection); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Add_AfterRemovingAllItems(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { ICollection<T> collection = GenericICollectionFactory(count); List<T> itemsToRemove = collection.ToList(); for (int i = 0; i < count; i++) collection.Remove(collection.ElementAt(0)); collection.Add(CreateT(254)); Assert.Equal(1, collection.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Add_ToReadOnlyCollection(int count) { if (IsReadOnly || AddRemoveClear_ThrowsNotSupported) { ICollection<T> collection = GenericICollectionFactory(count); Assert.Throws<NotSupportedException>(() => collection.Add(CreateT(0))); Assert.Equal(count, collection.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Add_AfterRemoving(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { int seed = 840; ICollection<T> collection = GenericICollectionFactory(count); T toAdd = CreateT(seed++); while (collection.Contains(toAdd)) toAdd = CreateT(seed++); collection.Add(toAdd); collection.Remove(toAdd); collection.Add(toAdd); } } #endregion #region Clear [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Clear(int count) { ICollection<T> collection = GenericICollectionFactory(count); if (IsReadOnly || AddRemoveClear_ThrowsNotSupported) { Assert.Throws<NotSupportedException>(() => collection.Clear()); Assert.Equal(count, collection.Count); } else { collection.Clear(); Assert.Equal(0, collection.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Clear_Repeatedly(int count) { ICollection<T> collection = GenericICollectionFactory(count); if (IsReadOnly || AddRemoveClear_ThrowsNotSupported) { Assert.Throws<NotSupportedException>(() => collection.Clear()); Assert.Throws<NotSupportedException>(() => collection.Clear()); Assert.Throws<NotSupportedException>(() => collection.Clear()); Assert.Equal(count, collection.Count); } else { collection.Clear(); collection.Clear(); collection.Clear(); Assert.Equal(0, collection.Count); } } #endregion #region Contains [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Contains_ValidValueOnCollectionNotContainingThatValue(int count) { ICollection<T> collection = GenericICollectionFactory(count); int seed = 4315; T item = CreateT(seed++); while (collection.Contains(item)) item = CreateT(seed++); Assert.False(collection.Contains(item)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Contains_ValidValueOnCollectionContainingThatValue(int count) { ICollection<T> collection = GenericICollectionFactory(count); foreach (T item in collection) Assert.True(collection.Contains(item)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Contains_DefaultValueOnCollectionNotContainingDefaultValue(int count) { ICollection<T> collection = GenericICollectionFactory(count); if (DefaultValueAllowed) Assert.False(collection.Contains(default(T))); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public virtual void ICollection_Generic_Contains_DefaultValueOnCollectionContainingDefaultValue(int count) { if (DefaultValueAllowed && !IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { ICollection<T> collection = GenericICollectionFactory(count); collection.Add(default(T)); Assert.True(collection.Contains(default(T))); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Contains_ValidValueThatExistsTwiceInTheCollection(int count) { if (DuplicateValuesAllowed && !IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { ICollection<T> collection = GenericICollectionFactory(count); T item = CreateT(12); collection.Add(item); collection.Add(item); Assert.Equal(count + 2, collection.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Contains_InvalidValue_ThrowsArgumentException(int count) { ICollection<T> collection = GenericICollectionFactory(count); Assert.All(InvalidValues, invalidValue => Assert.Throws<ArgumentException>(() => collection.Contains(invalidValue)) ); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public virtual void ICollection_Generic_Contains_DefaultValueWhenNotAllowed(int count) { if (!DefaultValueAllowed && !IsReadOnly) { ICollection<T> collection = GenericICollectionFactory(count); if (DefaultValueWhenNotAllowed_Throws) AssertExtensions.Throws<ArgumentNullException>("item", () => collection.Contains(default(T))); else Assert.False(collection.Contains(default(T))); } } #endregion #region CopyTo [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_CopyTo_NullArray_ThrowsArgumentNullException(int count) { ICollection<T> collection = GenericICollectionFactory(count); Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_CopyTo_NegativeIndex_ThrowsArgumentOutOfRangeException(int count) { ICollection<T> collection = GenericICollectionFactory(count); T[] array = new T[count]; Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(array, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(array, int.MinValue)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_CopyTo_IndexEqualToArrayCount_ThrowsArgumentException(int count) { ICollection<T> collection = GenericICollectionFactory(count); T[] array = new T[count]; if (count > 0) Assert.Throws<ArgumentException>(() => collection.CopyTo(array, count)); else collection.CopyTo(array, count); // does nothing since the array is empty } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_CopyTo_IndexLargerThanArrayCount_ThrowsAnyArgumentException(int count) { ICollection<T> collection = GenericICollectionFactory(count); T[] array = new T[count]; Assert.Throws(ICollection_Generic_CopyTo_IndexLargerThanArrayCount_ThrowType, () => collection.CopyTo(array, count + 1)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_CopyTo_NotEnoughSpaceInOffsettedArray_ThrowsArgumentException(int count) { if (count > 0) // Want the T array to have at least 1 element { ICollection<T> collection = GenericICollectionFactory(count); T[] array = new T[count]; Assert.Throws<ArgumentException>(() => collection.CopyTo(array, 1)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_CopyTo_ExactlyEnoughSpaceInArray(int count) { ICollection<T> collection = GenericICollectionFactory(count); T[] array = new T[count]; collection.CopyTo(array, 0); Assert.True(Enumerable.SequenceEqual(collection, array)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_CopyTo_ArrayIsLargerThanCollection(int count) { ICollection<T> collection = GenericICollectionFactory(count); T[] array = new T[count * 3 / 2]; collection.CopyTo(array, 0); Assert.True(Enumerable.SequenceEqual(collection, array.Take(count))); } #endregion #region Remove [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Remove_OnReadOnlyCollection_ThrowsNotSupportedException(int count) { if (IsReadOnly || AddRemoveClear_ThrowsNotSupported) { ICollection<T> collection = GenericICollectionFactory(count); Assert.Throws<NotSupportedException>(() => collection.Remove(CreateT(34543))); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Remove_DefaultValueNotContainedInCollection(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported && DefaultValueAllowed && !Enumerable.Contains(InvalidValues, default(T))) { int seed = count * 21; ICollection<T> collection = GenericICollectionFactory(count); T value = default(T); while (collection.Contains(value)) { collection.Remove(value); count--; } Assert.False(collection.Remove(value)); Assert.Equal(count, collection.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Remove_NonDefaultValueNotContainedInCollection(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { int seed = count * 251; ICollection<T> collection = GenericICollectionFactory(count); T value = CreateT(seed++); while (collection.Contains(value) || Enumerable.Contains(InvalidValues, value)) value = CreateT(seed++); Assert.False(collection.Remove(value)); Assert.Equal(count, collection.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public virtual void ICollection_Generic_Remove_DefaultValueContainedInCollection(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported && DefaultValueAllowed && !Enumerable.Contains(InvalidValues, default(T))) { int seed = count * 21; ICollection<T> collection = GenericICollectionFactory(count); T value = default(T); if (!collection.Contains(value)) { collection.Add(value); count++; } Assert.True(collection.Remove(value)); Assert.Equal(count - 1, collection.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Remove_NonDefaultValueContainedInCollection(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { int seed = count * 251; ICollection<T> collection = GenericICollectionFactory(count); T value = CreateT(seed++); if (!collection.Contains(value)) { collection.Add(value); count++; } Assert.True(collection.Remove(value)); Assert.Equal(count - 1, collection.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Remove_ValueThatExistsTwiceInCollection(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported && DuplicateValuesAllowed) { int seed = count * 90; ICollection<T> collection = GenericICollectionFactory(count); T value = CreateT(seed++); collection.Add(value); collection.Add(value); count += 2; Assert.True(collection.Remove(value)); Assert.True(collection.Contains(value)); Assert.Equal(count - 1, collection.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Remove_EveryValue(int count) { if (!IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { ICollection<T> collection = GenericICollectionFactory(count); Assert.All(collection.ToList(), value => { Assert.True(collection.Remove(value)); }); Assert.Empty(collection); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Remove_InvalidValue_ThrowsArgumentException(int count) { ICollection<T> collection = GenericICollectionFactory(count); Assert.All(InvalidValues, value => { Assert.Throws<ArgumentException>(() => collection.Remove(value)); }); Assert.Equal(count, collection.Count); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Remove_DefaultValueWhenNotAllowed(int count) { if (!DefaultValueAllowed && !IsReadOnly && !AddRemoveClear_ThrowsNotSupported) { ICollection<T> collection = GenericICollectionFactory(count); if (DefaultValueWhenNotAllowed_Throws) Assert.Throws<ArgumentNullException>(() => collection.Remove(default(T))); else Assert.False(collection.Remove(default(T))); } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Xml; using System.IO; using System.Collections.Generic; using System.Collections; using System.Reflection; using System.Threading; using OpenMetaverse; using log4net; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes.Scripting; using OpenSim.Region.Framework.Scenes.Serialization; namespace OpenSim.Region.Framework.Scenes { public class SceneObjectPartInventory : IEntityInventory { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_inventoryFileName = String.Empty; private byte[] m_inventoryFileData = new byte[0]; private uint m_inventoryFileNameSerial = 0; /// <value> /// The part to which the inventory belongs. /// </value> private SceneObjectPart m_part; /// <summary> /// Serial count for inventory file , used to tell if inventory has changed /// no need for this to be part of Database backup /// </summary> protected uint m_inventorySerial = 0; /// <summary> /// Holds in memory prim inventory /// </summary> protected TaskInventoryDictionary m_items = new TaskInventoryDictionary(); /// <summary> /// Tracks whether inventory has changed since the last persistent backup /// </summary> internal bool HasInventoryChanged; /// <value> /// Inventory serial number /// </value> protected internal uint Serial { get { return m_inventorySerial; } set { m_inventorySerial = value; } } /// <value> /// Raw inventory data /// </value> protected internal TaskInventoryDictionary Items { get { return m_items; } set { m_items = value; m_inventorySerial++; } } /// <summary> /// Constructor /// </summary> /// <param name="part"> /// A <see cref="SceneObjectPart"/> /// </param> public SceneObjectPartInventory(SceneObjectPart part) { m_part = part; } /// <summary> /// Force the task inventory of this prim to persist at the next update sweep /// </summary> public void ForceInventoryPersistence() { HasInventoryChanged = true; } /// <summary> /// Reset UUIDs for all the items in the prim's inventory. This involves either generating /// new ones or setting existing UUIDs to the correct parent UUIDs. /// /// If this method is called and there are inventory items, then we regard the inventory as having changed. /// </summary> /// <param name="linkNum">Link number for the part</param> public void ResetInventoryIDs() { if (null == m_part || null == m_part.ParentGroup) return; lock (m_items) { if (0 == m_items.Count) return; IList<TaskInventoryItem> items = GetInventoryItems(); m_items.Clear(); foreach (TaskInventoryItem item in items) { item.ResetIDs(m_part.UUID); m_items.Add(item.ItemID, item); } } } public void ResetObjectID() { lock (Items) { IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values); Items.Clear(); foreach (TaskInventoryItem item in items) { item.ParentPartID = m_part.UUID; item.ParentID = m_part.UUID; Items.Add(item.ItemID, item); } } } /// <summary> /// Change every item in this inventory to a new owner. /// </summary> /// <param name="ownerId"></param> public void ChangeInventoryOwner(UUID ownerId) { lock (Items) { if (0 == Items.Count) { return; } } HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; List<TaskInventoryItem> items = GetInventoryItems(); foreach (TaskInventoryItem item in items) { if (ownerId != item.OwnerID) item.LastOwnerID = item.OwnerID; item.OwnerID = ownerId; item.PermsMask = 0; item.PermsGranter = UUID.Zero; item.OwnerChanged = true; } } /// <summary> /// Change every item in this inventory to a new group. /// </summary> /// <param name="groupID"></param> public void ChangeInventoryGroup(UUID groupID) { lock (Items) { if (0 == Items.Count) { return; } } // Don't let this set the HasGroupChanged flag for attachments // as this happens during rez and we don't want a new asset // for each attachment each time if (!m_part.ParentGroup.RootPart.IsAttachment) { HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; } List<TaskInventoryItem> items = GetInventoryItems(); foreach (TaskInventoryItem item in items) { if (groupID != item.GroupID) item.GroupID = groupID; } } /// <summary> /// Start all the scripts contained in this prim's inventory /// </summary> public void CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource) { List<TaskInventoryItem> scripts = GetInventoryScripts(); foreach (TaskInventoryItem item in scripts) CreateScriptInstance(item, startParam, postOnRez, engine, stateSource); } public ArrayList GetScriptErrors(UUID itemID) { ArrayList ret = new ArrayList(); IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines == null) // No engine at all return ret; foreach (IScriptModule e in engines) { if (e != null) { ArrayList errors = e.GetScriptErrors(itemID); foreach (Object line in errors) ret.Add(line); } } return ret; } /// <summary> /// Stop all the scripts in this prim. /// </summary> /// <param name="sceneObjectBeingDeleted"> /// Should be true if these scripts are being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void RemoveScriptInstances(bool sceneObjectBeingDeleted) { List<TaskInventoryItem> scripts = GetInventoryScripts(); foreach (TaskInventoryItem item in scripts) RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted); } /// <summary> /// Start a script which is in this prim's inventory. /// </summary> /// <param name="item"></param> /// <returns></returns> public void CreateScriptInstance(TaskInventoryItem item, int startParam, bool postOnRez, string engine, int stateSource) { // m_log.InfoFormat( // "[PRIM INVENTORY]: " + // "Starting script {0}, {1} in prim {2}, {3}", // item.Name, item.ItemID, Name, UUID); if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID)) return; m_part.AddFlag(PrimFlags.Scripted); if (!m_part.ParentGroup.Scene.RegionInfo.RegionSettings.DisableScripts) { if (stateSource == 2 && // Prim crossing m_part.ParentGroup.Scene.m_trustBinaries) { lock (m_items) { m_items[item.ItemID].PermsMask = 0; m_items[item.ItemID].PermsGranter = UUID.Zero; } m_part.ParentGroup.Scene.EventManager.TriggerRezScript( m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource); m_part.ParentGroup.AddActiveScriptCount(1); m_part.ScheduleFullUpdate(); return; } AssetBase asset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString()); if (null == asset) { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found", item.Name, item.ItemID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName, item.AssetID); } else { if (m_part.ParentGroup.m_savedScriptState != null) RestoreSavedScriptState(item.OldItemID, item.ItemID); lock (m_items) { m_items[item.ItemID].PermsMask = 0; m_items[item.ItemID].PermsGranter = UUID.Zero; } string script = Utils.BytesToString(asset.Data); m_part.ParentGroup.Scene.EventManager.TriggerRezScript( m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource); m_part.ParentGroup.AddActiveScriptCount(1); m_part.ScheduleFullUpdate(); } } } private void RestoreSavedScriptState(UUID oldID, UUID newID) { IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines == null) // No engine at all return; if (m_part.ParentGroup.m_savedScriptState.ContainsKey(oldID)) { XmlDocument doc = new XmlDocument(); doc.LoadXml(m_part.ParentGroup.m_savedScriptState[oldID]); ////////// CRUFT WARNING /////////////////////////////////// // // Old objects will have <ScriptState><State> ... // This format is XEngine ONLY // // New objects have <State Engine="...." ...><ScriptState>... // This can be passed to any engine // XmlNode n = doc.SelectSingleNode("ScriptState"); if (n != null) // Old format data { XmlDocument newDoc = new XmlDocument(); XmlElement rootN = newDoc.CreateElement("", "State", ""); XmlAttribute uuidA = newDoc.CreateAttribute("", "UUID", ""); uuidA.Value = oldID.ToString(); rootN.Attributes.Append(uuidA); XmlAttribute engineA = newDoc.CreateAttribute("", "Engine", ""); engineA.Value = "XEngine"; rootN.Attributes.Append(engineA); newDoc.AppendChild(rootN); XmlNode stateN = newDoc.ImportNode(n, true); rootN.AppendChild(stateN); // This created document has only the minimun data // necessary for XEngine to parse it successfully m_part.ParentGroup.m_savedScriptState[oldID] = newDoc.OuterXml; } foreach (IScriptModule e in engines) { if (e != null) { if (e.SetXMLState(newID, m_part.ParentGroup.m_savedScriptState[oldID])) break; } } m_part.ParentGroup.m_savedScriptState.Remove(oldID); } } /// <summary> /// Start a script which is in this prim's inventory. /// </summary> /// <param name="itemId"> /// A <see cref="UUID"/> /// </param> public void CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource) { TaskInventoryItem item = GetInventoryItem(itemId); if (item != null) CreateScriptInstance(item, startParam, postOnRez, engine, stateSource); else m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", itemId, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } /// <summary> /// Stop a script which is in this prim's inventory. /// </summary> /// <param name="itemId"></param> /// <param name="sceneObjectBeingDeleted"> /// Should be true if this script is being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted) { bool scriptPresent = false; lock (m_items) { if (m_items.ContainsKey(itemId)) scriptPresent = true; } if (scriptPresent) { if (!sceneObjectBeingDeleted) m_part.RemoveScriptEvents(itemId); m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemId); m_part.ParentGroup.AddActiveScriptCount(-1); } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", itemId, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } } /// <summary> /// Check if the inventory holds an item with a given name. /// </summary> /// <param name="name"></param> /// <returns></returns> private bool InventoryContainsName(string name) { lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.Name == name) return true; } } return false; } /// <summary> /// For a given item name, return that name if it is available. Otherwise, return the next available /// similar name (which is currently the original name with the next available numeric suffix). /// </summary> /// <param name="name"></param> /// <returns></returns> private string FindAvailableInventoryName(string name) { if (!InventoryContainsName(name)) return name; int suffix=1; while (suffix < 256) { string tryName=String.Format("{0} {1}", name, suffix); if (!InventoryContainsName(tryName)) return tryName; suffix++; } return String.Empty; } /// <summary> /// Add an item to this prim's inventory. If an item with the same name already exists, then an alternative /// name is chosen. /// </summary> /// <param name="item"></param> public void AddInventoryItem(TaskInventoryItem item, bool allowedDrop) { AddInventoryItem(item.Name, item, allowedDrop); } /// <summary> /// Add an item to this prim's inventory. If an item with the same name already exists, it is replaced. /// </summary> /// <param name="item"></param> public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop) { List<TaskInventoryItem> il = GetInventoryItems(); foreach (TaskInventoryItem i in il) { if (i.Name == item.Name) { if (i.InvType == (int)InventoryType.LSL) RemoveScriptInstance(i.ItemID, false); RemoveInventoryItem(i.ItemID); break; } } AddInventoryItem(item.Name, item, allowedDrop); } /// <summary> /// Add an item to this prim's inventory. /// </summary> /// <param name="name">The name that the new item should have.</param> /// <param name="item"> /// The item itself. The name within this structure is ignored in favour of the name /// given in this method's arguments /// </param> /// <param name="allowedDrop"> /// Item was only added to inventory because AllowedDrop is set /// </param> protected void AddInventoryItem(string name, TaskInventoryItem item, bool allowedDrop) { name = FindAvailableInventoryName(name); if (name == String.Empty) return; item.ParentID = m_part.UUID; item.ParentPartID = m_part.UUID; item.Name = name; item.GroupID = m_part.GroupID; lock (m_items) m_items.Add(item.ItemID, item); if (allowedDrop) m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP); else m_part.TriggerScriptChangedEvent(Changed.INVENTORY); m_inventorySerial++; //m_inventorySerial += 2; HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; } /// <summary> /// Restore a whole collection of items to the prim's inventory at once. /// We assume that the items already have all their fields correctly filled out. /// The items are not flagged for persistence to the database, since they are being restored /// from persistence rather than being newly added. /// </summary> /// <param name="items"></param> public void RestoreInventoryItems(ICollection<TaskInventoryItem> items) { lock (m_items) { foreach (TaskInventoryItem item in items) { m_items.Add(item.ItemID, item); // m_part.TriggerScriptChangedEvent(Changed.INVENTORY); } m_inventorySerial++; } } /// <summary> /// Returns an existing inventory item. Returns the original, so any changes will be live. /// </summary> /// <param name="itemID"></param> /// <returns>null if the item does not exist</returns> public TaskInventoryItem GetInventoryItem(UUID itemId) { TaskInventoryItem item; lock (m_items) m_items.TryGetValue(itemId, out item); return item; } /// <summary> /// Get inventory items by name. /// </summary> /// <param name="name"></param> /// <returns> /// A list of inventory items with that name. /// If no inventory item has that name then an empty list is returned. /// </returns> public IList<TaskInventoryItem> GetInventoryItems(string name) { IList<TaskInventoryItem> items = new List<TaskInventoryItem>(); lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.Name == name) items.Add(item); } } return items; } public SceneObjectGroup GetRezReadySceneObject(TaskInventoryItem item) { AssetBase rezAsset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString()); if (null == rezAsset) { m_log.WarnFormat( "[PRIM INVENTORY]: Could not find asset {0} for inventory item {1} in {2}", item.AssetID, item.Name, m_part.Name); return null; } string xmlData = Utils.BytesToString(rezAsset.Data); SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xmlData); group.ResetIDs(); SceneObjectPart rootPart = group.GetChildPart(group.UUID); // Since renaming the item in the inventory does not affect the name stored // in the serialization, transfer the correct name from the inventory to the // object itself before we rez. rootPart.Name = item.Name; rootPart.Description = item.Description; SceneObjectPart[] partList = group.Parts; group.SetGroup(m_part.GroupID, null); // TODO: Remove magic number badness if ((rootPart.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0 || (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0) // Magic number { if (m_part.ParentGroup.Scene.Permissions.PropagatePermissions()) { foreach (SceneObjectPart part in partList) { if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0) part.EveryoneMask = item.EveryonePermissions; if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0) part.NextOwnerMask = item.NextPermissions; if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteGroup) != 0) part.GroupMask = item.GroupPermissions; } group.ApplyNextOwnerPermissions(); } } foreach (SceneObjectPart part in partList) { // TODO: Remove magic number badness if ((part.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0 || (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0) // Magic number { part.LastOwnerID = part.OwnerID; part.OwnerID = item.OwnerID; part.Inventory.ChangeInventoryOwner(item.OwnerID); } if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0) part.EveryoneMask = item.EveryonePermissions; if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0) part.NextOwnerMask = item.NextPermissions; if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteGroup) != 0) part.GroupMask = item.GroupPermissions; } rootPart.TrimPermissions(); return group; } /// <summary> /// Update an existing inventory item. /// </summary> /// <param name="item">The updated item. An item with the same id must already exist /// in this prim's inventory.</param> /// <returns>false if the item did not exist, true if the update occurred successfully</returns> public bool UpdateInventoryItem(TaskInventoryItem item) { return UpdateInventoryItem(item, true, true); } public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents) { return UpdateInventoryItem(item, fireScriptEvents, true); } public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged) { TaskInventoryItem it = GetInventoryItem(item.ItemID); if (it != null) { // m_log.DebugFormat("[PRIM INVENTORY]: Updating item {0} in {1}", item.Name, m_part.Name); item.ParentID = m_part.UUID; item.ParentPartID = m_part.UUID; // If group permissions have been set on, check that the groupID is up to date in case it has // changed since permissions were last set. if (item.GroupPermissions != (uint)PermissionMask.None) item.GroupID = m_part.GroupID; if (item.AssetID == UUID.Zero) item.AssetID = it.AssetID; lock (m_items) { m_items[item.ItemID] = item; m_inventorySerial++; } if (fireScriptEvents) m_part.TriggerScriptChangedEvent(Changed.INVENTORY); if (considerChanged) { HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; } return true; } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Tried to retrieve item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory", item.ItemID, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } return false; } /// <summary> /// Remove an item from this prim's inventory /// </summary> /// <param name="itemID"></param> /// <returns>Numeric asset type of the item removed. Returns -1 if the item did not exist /// in this prim's inventory.</returns> public int RemoveInventoryItem(UUID itemID) { TaskInventoryItem item = GetInventoryItem(itemID); if (item != null) { int type = m_items[itemID].InvType; if (type == 10) // Script { m_part.RemoveScriptEvents(itemID); m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID); } m_items.Remove(itemID); m_inventorySerial++; m_part.TriggerScriptChangedEvent(Changed.INVENTORY); HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; if (!ContainsScripts()) m_part.RemFlag(PrimFlags.Scripted); m_part.ScheduleFullUpdate(); return type; } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Tried to remove item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory", itemID, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } return -1; } private bool CreateInventoryFile() { if (m_inventoryFileName == String.Empty || m_inventoryFileNameSerial < m_inventorySerial) { // Something changed, we need to create a new file m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp"; m_inventoryFileNameSerial = m_inventorySerial; InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero); lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { UUID ownerID = item.OwnerID; uint everyoneMask = 0; uint baseMask = item.BasePermissions; uint ownerMask = item.CurrentPermissions; uint groupMask = item.GroupPermissions; invString.AddItemStart(); invString.AddNameValueLine("item_id", item.ItemID.ToString()); invString.AddNameValueLine("parent_id", m_part.UUID.ToString()); invString.AddPermissionsStart(); invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask)); invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask)); invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask)); invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask)); invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions)); invString.AddNameValueLine("creator_id", item.CreatorID.ToString()); invString.AddNameValueLine("owner_id", ownerID.ToString()); invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString()); invString.AddNameValueLine("group_id", item.GroupID.ToString()); invString.AddSectionEnd(); invString.AddNameValueLine("asset_id", item.AssetID.ToString()); invString.AddNameValueLine("type", TaskInventoryItem.Types[item.Type]); invString.AddNameValueLine("inv_type", TaskInventoryItem.InvTypes[item.InvType]); invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags)); invString.AddSaleStart(); invString.AddNameValueLine("sale_type", "not"); invString.AddNameValueLine("sale_price", "0"); invString.AddSectionEnd(); invString.AddNameValueLine("name", item.Name + "|"); invString.AddNameValueLine("desc", item.Description + "|"); invString.AddNameValueLine("creation_date", item.CreationDate.ToString()); invString.AddSectionEnd(); } } m_inventoryFileData = Utils.StringToBytes(invString.BuildString); return true; } // No need to recreate, the existing file is fine return false; } /// <summary> /// Serialize all the metadata for the items in this prim's inventory ready for sending to the client /// </summary> /// <param name="xferManager"></param> public void RequestInventoryFile(IClientAPI client, IXfer xferManager) { CreateInventoryFile(); if (m_inventorySerial == 0) // No inventory { client.SendTaskInventory(m_part.UUID, 0, new byte[0]); return; } // In principle, we should only do the rest if the inventory changed; // by sending m_inventorySerial to the client, it ought to know // that nothing changed and that it doesn't need to request the file. // Unfortunately, it doesn't look like the client optimizes this; // the client seems to always come back and request the Xfer, // no matter what value m_inventorySerial has. if (m_inventoryFileData.Length > 2) // Add the file for Xfer xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData); // Tell the client we're ready to Xfer the file client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial, Util.StringToBytes256(m_inventoryFileName)); } /// <summary> /// Process inventory backup /// </summary> /// <param name="datastore"></param> public void ProcessInventoryBackup(ISimulationDataService datastore) { if (HasInventoryChanged) { HasInventoryChanged = false; List<TaskInventoryItem> items = GetInventoryItems(); datastore.StorePrimInventory(m_part.UUID, items); } } public class InventoryStringBuilder { public string BuildString = String.Empty; public InventoryStringBuilder(UUID folderID, UUID parentID) { BuildString += "\tinv_object\t0\n\t{\n"; AddNameValueLine("obj_id", folderID.ToString()); AddNameValueLine("parent_id", parentID.ToString()); AddNameValueLine("type", "category"); AddNameValueLine("name", "Contents|"); AddSectionEnd(); } public void AddItemStart() { BuildString += "\tinv_item\t0\n"; AddSectionStart(); } public void AddPermissionsStart() { BuildString += "\tpermissions 0\n"; AddSectionStart(); } public void AddSaleStart() { BuildString += "\tsale_info\t0\n"; AddSectionStart(); } protected void AddSectionStart() { BuildString += "\t{\n"; } public void AddSectionEnd() { BuildString += "\t}\n"; } public void AddLine(string addLine) { BuildString += addLine; } public void AddNameValueLine(string name, string value) { BuildString += "\t\t"; BuildString += name + "\t"; BuildString += value + "\n"; } public void Close() { } } public uint MaskEffectivePermissions() { uint mask=0x7fffffff; lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); if (item.InvType != (int)InventoryType.Object) { if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); } else { if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); } if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~(uint)PermissionMask.Copy; if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~(uint)PermissionMask.Transfer; if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~(uint)PermissionMask.Modify; } } return mask; } public void ApplyNextOwnerPermissions() { lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0) { if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Copy; if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Transfer; if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Modify; } item.CurrentPermissions &= item.NextPermissions; item.BasePermissions &= item.NextPermissions; item.EveryonePermissions &= item.NextPermissions; item.OwnerChanged = true; item.PermsMask = 0; item.PermsGranter = UUID.Zero; } } } public void ApplyGodPermissions(uint perms) { lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { item.CurrentPermissions = perms; item.BasePermissions = perms; } } m_inventorySerial++; HasInventoryChanged = true; } public bool ContainsScripts() { lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.LSL) { return true; } } } return false; } public List<UUID> GetInventoryList() { List<UUID> ret = new List<UUID>(); lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) ret.Add(item.ItemID); } return ret; } public List<TaskInventoryItem> GetInventoryItems() { List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); lock (m_items) ret = new List<TaskInventoryItem>(m_items.Values); return ret; } public List<TaskInventoryItem> GetInventoryScripts() { List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) if (item.InvType == (int)InventoryType.LSL) ret.Add(item); } return ret; } public Dictionary<UUID, string> GetScriptStates() { Dictionary<UUID, string> ret = new Dictionary<UUID, string>(); if (m_part.ParentGroup.Scene == null) // Group not in a scene return ret; IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines == null) // No engine at all return ret; List<TaskInventoryItem> scripts = GetInventoryScripts(); foreach (TaskInventoryItem item in scripts) { foreach (IScriptModule e in engines) { if (e != null) { string n = e.GetXMLState(item.ItemID); if (n != String.Empty) { if (!ret.ContainsKey(item.ItemID)) ret[item.ItemID] = n; break; } } } } return ret; } public void ResumeScripts() { IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines == null) return; List<TaskInventoryItem> scripts = GetInventoryScripts(); foreach (TaskInventoryItem item in scripts) { foreach (IScriptModule engine in engines) { if (engine != null) { if (item.OwnerChanged) engine.PostScriptEvent(item.ItemID, "changed", new Object[] { (int)Changed.OWNER }); item.OwnerChanged = false; engine.ResumeScript(item.ItemID); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.ServiceModel.Channels { using System.ComponentModel; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using System.ServiceModel.Security; using Microsoft.Xml; public sealed class ReliableSessionBindingElement : BindingElement, IPolicyExportExtension { private TimeSpan _acknowledgementInterval = ReliableSessionDefaults.AcknowledgementInterval; private bool _flowControlEnabled = ReliableSessionDefaults.FlowControlEnabled; private TimeSpan _inactivityTimeout = ReliableSessionDefaults.InactivityTimeout; private int _maxPendingChannels = ReliableSessionDefaults.MaxPendingChannels; private int _maxRetryCount = ReliableSessionDefaults.MaxRetryCount; private int _maxTransferWindowSize = ReliableSessionDefaults.MaxTransferWindowSize; private bool _ordered = ReliableSessionDefaults.Ordered; private ReliableMessagingVersion _reliableMessagingVersion = ReliableMessagingVersion.Default; private static MessagePartSpecification s_bodyOnly; public ReliableSessionBindingElement() { } internal ReliableSessionBindingElement(ReliableSessionBindingElement elementToBeCloned) : base(elementToBeCloned) { this.AcknowledgementInterval = elementToBeCloned.AcknowledgementInterval; this.FlowControlEnabled = elementToBeCloned.FlowControlEnabled; this.InactivityTimeout = elementToBeCloned.InactivityTimeout; this.MaxPendingChannels = elementToBeCloned.MaxPendingChannels; this.MaxRetryCount = elementToBeCloned.MaxRetryCount; this.MaxTransferWindowSize = elementToBeCloned.MaxTransferWindowSize; this.Ordered = elementToBeCloned.Ordered; this.ReliableMessagingVersion = elementToBeCloned.ReliableMessagingVersion; } public ReliableSessionBindingElement(bool ordered) { _ordered = ordered; } [DefaultValue(typeof(TimeSpan), ReliableSessionDefaults.AcknowledgementIntervalString)] public TimeSpan AcknowledgementInterval { get { return _acknowledgementInterval; } set { if (value <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SRServiceModel.TimeSpanMustbeGreaterThanTimeSpanZero)); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SRServiceModel.SFxTimeoutOutOfRangeTooBig)); } _acknowledgementInterval = value; } } [DefaultValue(ReliableSessionDefaults.FlowControlEnabled)] public bool FlowControlEnabled { get { return _flowControlEnabled; } set { _flowControlEnabled = value; } } [DefaultValue(typeof(TimeSpan), ReliableSessionDefaults.InactivityTimeoutString)] public TimeSpan InactivityTimeout { get { return _inactivityTimeout; } set { if (value <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SRServiceModel.TimeSpanMustbeGreaterThanTimeSpanZero)); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SRServiceModel.SFxTimeoutOutOfRangeTooBig)); } _inactivityTimeout = value; } } [DefaultValue(ReliableSessionDefaults.MaxPendingChannels)] public int MaxPendingChannels { get { return _maxPendingChannels; } set { if (value <= 0 || value > 16384) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, string.Format(SRServiceModel.ValueMustBeInRange, 0, 16384))); _maxPendingChannels = value; } } [DefaultValue(ReliableSessionDefaults.MaxRetryCount)] public int MaxRetryCount { get { return _maxRetryCount; } set { if (value <= 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SRServiceModel.ValueMustBePositive)); _maxRetryCount = value; } } [DefaultValue(ReliableSessionDefaults.MaxTransferWindowSize)] public int MaxTransferWindowSize { get { return _maxTransferWindowSize; } set { if (value <= 0 || value > 4096) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, string.Format(SRServiceModel.ValueMustBeInRange, 0, 4096))); _maxTransferWindowSize = value; } } [DefaultValue(ReliableSessionDefaults.Ordered)] public bool Ordered { get { return _ordered; } set { _ordered = value; } } [DefaultValue(typeof(ReliableMessagingVersion), ReliableSessionDefaults.ReliableMessagingVersionString)] public ReliableMessagingVersion ReliableMessagingVersion { get { return _reliableMessagingVersion; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (!ReliableMessagingVersion.IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); } _reliableMessagingVersion = value; } } private static MessagePartSpecification BodyOnly { get { if (s_bodyOnly == null) { MessagePartSpecification temp = new MessagePartSpecification(true); temp.MakeReadOnly(); s_bodyOnly = temp; } return s_bodyOnly; } } public override BindingElement Clone() { return new ReliableSessionBindingElement(this); } public override T GetProperty<T>(BindingContext context) { throw new NotImplementedException(); } public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context) { throw new NotImplementedException(); } public override bool CanBuildChannelFactory<TChannel>(BindingContext context) { throw new NotImplementedException(); } internal override bool IsMatch(BindingElement b) { if (b == null) return false; ReliableSessionBindingElement session = b as ReliableSessionBindingElement; if (session == null) return false; if (_acknowledgementInterval != session._acknowledgementInterval) return false; if (_flowControlEnabled != session._flowControlEnabled) return false; if (_inactivityTimeout != session._inactivityTimeout) return false; if (_maxPendingChannels != session._maxPendingChannels) return false; if (_maxRetryCount != session._maxRetryCount) return false; if (_maxTransferWindowSize != session._maxTransferWindowSize) return false; if (_ordered != session._ordered) return false; if (_reliableMessagingVersion != session._reliableMessagingVersion) return false; return true; } private static void ProtectProtocolMessage( ScopedMessagePartSpecification signaturePart, ScopedMessagePartSpecification encryptionPart, string action) { signaturePart.AddParts(BodyOnly, action); encryptionPart.AddParts(MessagePartSpecification.NoParts, action); //encryptionPart.AddParts(BodyOnly, action); } private void SetSecuritySettings(BindingContext context) { SecurityBindingElement element = context.RemainingBindingElements.Find<SecurityBindingElement>(); if (element != null) { element.LocalServiceSettings.ReconnectTransportOnFailure = true; } } private void VerifyTransportMode(BindingContext context) { TransportBindingElement transportElement = context.RemainingBindingElements.Find<TransportBindingElement>(); // Verify ManualAdderssing is turned off. if ((transportElement != null) && (transportElement.ManualAddressing)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SRServiceModel.ManualAddressingNotSupported)); } ConnectionOrientedTransportBindingElement connectionElement = transportElement as ConnectionOrientedTransportBindingElement; HttpTransportBindingElement httpElement = transportElement as HttpTransportBindingElement; // Verify TransportMode is Buffered. TransferMode transportTransferMode; if (connectionElement != null) { transportTransferMode = connectionElement.TransferMode; } else if (httpElement != null) { transportTransferMode = httpElement.TransferMode; } else { // Not one of the elements we can check, we have to assume TransferMode.Buffered. transportTransferMode = TransferMode.Buffered; } if (transportTransferMode != TransferMode.Buffered) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(string.Format(SRServiceModel.TransferModeNotSupported, transportTransferMode, this.GetType().Name))); } } void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context) { if (exporter == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); if (context == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); if (context.BindingElements != null) { BindingElementCollection bindingElements = context.BindingElements; ReliableSessionBindingElement settings = bindingElements.Find<ReliableSessionBindingElement>(); if (settings != null) { // ReliableSession assertion XmlElement assertion = settings.CreateReliabilityAssertion(exporter.PolicyVersion, bindingElements); context.GetBindingAssertions().Add(assertion); } } } private static XmlElement CreatePolicyElement(PolicyVersion policyVersion, XmlDocument doc) { string policy = MetadataStrings.WSPolicy.Elements.Policy; string policyNs = policyVersion.Namespace; string policyPrefix = MetadataStrings.WSPolicy.Prefix; return doc.CreateElement(policyPrefix, policy, policyNs); } private XmlElement CreateReliabilityAssertion(PolicyVersion policyVersion, BindingElementCollection bindingElements) { XmlDocument doc = new XmlDocument(); XmlElement child = null; string reliableSessionPrefix; string reliableSessionNs; string assertionPrefix; string assertionNs; if (this.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { reliableSessionPrefix = ReliableSessionPolicyStrings.ReliableSessionFebruary2005Prefix; reliableSessionNs = ReliableSessionPolicyStrings.ReliableSessionFebruary2005Namespace; assertionPrefix = reliableSessionPrefix; assertionNs = reliableSessionNs; } else { reliableSessionPrefix = ReliableSessionPolicyStrings.ReliableSession11Prefix; reliableSessionNs = ReliableSessionPolicyStrings.ReliableSession11Namespace; assertionPrefix = ReliableSessionPolicyStrings.NET11Prefix; assertionNs = ReliableSessionPolicyStrings.NET11Namespace; } // ReliableSession assertion XmlElement assertion = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.ReliableSessionName, reliableSessionNs); if (this.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11) { // Policy XmlElement policy = CreatePolicyElement(policyVersion, doc); // SequenceSTR if (IsSecureConversationEnabled(bindingElements)) { XmlElement sequenceSTR = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.SequenceSTR, reliableSessionNs); policy.AppendChild(sequenceSTR); } // DeliveryAssurance XmlElement deliveryAssurance = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.DeliveryAssurance, reliableSessionNs); // Policy XmlElement nestedPolicy = CreatePolicyElement(policyVersion, doc); // ExactlyOnce XmlElement exactlyOnce = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.ExactlyOnce, reliableSessionNs); nestedPolicy.AppendChild(exactlyOnce); if (_ordered) { // InOrder XmlElement inOrder = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.InOrder, reliableSessionNs); nestedPolicy.AppendChild(inOrder); } deliveryAssurance.AppendChild(nestedPolicy); policy.AppendChild(deliveryAssurance); assertion.AppendChild(policy); } // Nested InactivityTimeout assertion child = doc.CreateElement(assertionPrefix, ReliableSessionPolicyStrings.InactivityTimeout, assertionNs); WriteMillisecondsAttribute(child, this.InactivityTimeout); assertion.AppendChild(child); // Nested AcknowledgementInterval assertion child = doc.CreateElement(assertionPrefix, ReliableSessionPolicyStrings.AcknowledgementInterval, assertionNs); WriteMillisecondsAttribute(child, this.AcknowledgementInterval); assertion.AppendChild(child); return assertion; } private static bool IsSecureConversationEnabled(BindingElementCollection bindingElements) { bool foundRM = false; for (int i = 0; i < bindingElements.Count; i++) { if (!foundRM) { ReliableSessionBindingElement bindingElement = bindingElements[i] as ReliableSessionBindingElement; foundRM = (bindingElement != null); } else { SecurityBindingElement securityBindingElement = bindingElements[i] as SecurityBindingElement; if (securityBindingElement != null) { SecurityBindingElement bootstrapSecurity; // The difference in bool (requireCancellation) does not affect whether the binding is valid, // but the method does match on the value so we need to pass both true and false. return SecurityBindingElement.IsSecureConversationBinding(securityBindingElement, true, out bootstrapSecurity) || SecurityBindingElement.IsSecureConversationBinding(securityBindingElement, false, out bootstrapSecurity); } break; } } return false; } private static void WriteMillisecondsAttribute(XmlElement childElement, TimeSpan timeSpan) { UInt64 milliseconds = Convert.ToUInt64(timeSpan.TotalMilliseconds); childElement.SetAttribute(ReliableSessionPolicyStrings.Milliseconds, XmlConvert.ToString(milliseconds)); } private class BindingDeliveryCapabilitiesHelper : IBindingDeliveryCapabilities { private ReliableSessionBindingElement _element; private IBindingDeliveryCapabilities _inner; internal BindingDeliveryCapabilitiesHelper(ReliableSessionBindingElement element, IBindingDeliveryCapabilities inner) { _element = element; _inner = inner; } bool IBindingDeliveryCapabilities.AssuresOrderedDelivery { get { return _element.Ordered; } } bool IBindingDeliveryCapabilities.QueuedDelivery { get { return _inner != null ? _inner.QueuedDelivery : false; } } } } }