context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.WebParts.WebPartZoneBase.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls.WebParts { abstract public partial class WebPartZoneBase : WebZone, System.Web.UI.IPostBackEventHandler { #region Methods and constructors protected virtual new void CloseWebPart (WebPart webPart) { } protected virtual new void ConnectWebPart (WebPart webPart) { } protected internal override void CreateChildControls () { } protected override System.Web.UI.ControlCollection CreateControlCollection () { return default(System.Web.UI.ControlCollection); } protected override System.Web.UI.WebControls.Style CreateControlStyle () { return default(System.Web.UI.WebControls.Style); } protected virtual new WebPartChrome CreateWebPartChrome () { return default(WebPartChrome); } protected virtual new void DeleteWebPart (WebPart webPart) { } protected virtual new void EditWebPart (WebPart webPart) { } public override PartChromeType GetEffectiveChromeType (Part part) { return default(PartChromeType); } protected internal abstract WebPartCollection GetInitialWebParts (); protected override void LoadViewState (Object savedState) { } protected virtual new void MinimizeWebPart (WebPart webPart) { } protected virtual new void OnCreateVerbs (WebPartVerbsEventArgs e) { } protected internal override void OnPreRender (EventArgs e) { } protected virtual new void RaisePostBackEvent (string eventArgument) { } protected internal override void Render (System.Web.UI.HtmlTextWriter writer) { } protected override void RenderBody (System.Web.UI.HtmlTextWriter writer) { } protected virtual new void RenderDropCue (System.Web.UI.HtmlTextWriter writer) { Contract.Requires (writer != null); } protected override void RenderHeader (System.Web.UI.HtmlTextWriter writer) { } protected virtual new void RestoreWebPart (WebPart webPart) { } protected override Object SaveViewState () { return default(Object); } void System.Web.UI.IPostBackEventHandler.RaisePostBackEvent (string eventArgument) { } protected override void TrackViewState () { } protected WebPartZoneBase () { } #endregion #region Properties and indexers public virtual new bool AllowLayoutChange { get { return default(bool); } set { } } public override System.Drawing.Color BorderColor { get { return default(System.Drawing.Color); } set { } } public override System.Web.UI.WebControls.BorderStyle BorderStyle { get { return default(System.Web.UI.WebControls.BorderStyle); } set { } } public override System.Web.UI.WebControls.Unit BorderWidth { get { return default(System.Web.UI.WebControls.Unit); } set { } } public virtual new WebPartVerb CloseVerb { get { return default(WebPartVerb); } } public virtual new WebPartVerb ConnectVerb { get { return default(WebPartVerb); } } public virtual new WebPartVerb DeleteVerb { get { return default(WebPartVerb); } } public virtual new string DisplayTitle { get { return default(string); } } internal protected bool DragDropEnabled { get { return default(bool); } } public virtual new System.Drawing.Color DragHighlightColor { get { return default(System.Drawing.Color); } set { } } public virtual new WebPartVerb EditVerb { get { return default(WebPartVerb); } } public override string EmptyZoneText { get { return default(string); } set { } } public virtual new WebPartVerb ExportVerb { get { return default(WebPartVerb); } } protected override bool HasFooter { get { return default(bool); } } protected override bool HasHeader { get { return default(bool); } } public virtual new WebPartVerb HelpVerb { get { return default(WebPartVerb); } } public virtual new System.Web.UI.WebControls.Orientation LayoutOrientation { get { return default(System.Web.UI.WebControls.Orientation); } set { } } public System.Web.UI.WebControls.Style MenuCheckImageStyle { get { Contract.Ensures (Contract.Result<System.Web.UI.WebControls.Style>() != null); return default(System.Web.UI.WebControls.Style); } } public virtual new string MenuCheckImageUrl { get { return default(string); } set { } } public System.Web.UI.WebControls.Style MenuLabelHoverStyle { get { Contract.Ensures (Contract.Result<System.Web.UI.WebControls.Style>() != null); return default(System.Web.UI.WebControls.Style); } } public System.Web.UI.WebControls.Style MenuLabelStyle { get { Contract.Ensures (Contract.Result<System.Web.UI.WebControls.Style>() != null); return default(System.Web.UI.WebControls.Style); } } public virtual new string MenuLabelText { get { return default(string); } set { } } public virtual new string MenuPopupImageUrl { get { return default(string); } set { } } public WebPartMenuStyle MenuPopupStyle { get { Contract.Ensures (Contract.Result<System.Web.UI.WebControls.WebParts.WebPartMenuStyle>() != null); return default(WebPartMenuStyle); } } public System.Web.UI.WebControls.Style MenuVerbHoverStyle { get { Contract.Ensures (Contract.Result<System.Web.UI.WebControls.Style>() != null); return default(System.Web.UI.WebControls.Style); } } public System.Web.UI.WebControls.Style MenuVerbStyle { get { Contract.Ensures (Contract.Result<System.Web.UI.WebControls.Style>() != null); return default(System.Web.UI.WebControls.Style); } } public virtual new WebPartVerb MinimizeVerb { get { return default(WebPartVerb); } } public virtual new WebPartVerb RestoreVerb { get { return default(WebPartVerb); } } public System.Web.UI.WebControls.Style SelectedPartChromeStyle { get { Contract.Ensures (Contract.Result<System.Web.UI.WebControls.Style>() != null); return default(System.Web.UI.WebControls.Style); } } public virtual new bool ShowTitleIcons { get { return default(bool); } set { } } public virtual new System.Web.UI.WebControls.ButtonType TitleBarVerbButtonType { get { return default(System.Web.UI.WebControls.ButtonType); } set { } } public System.Web.UI.WebControls.Style TitleBarVerbStyle { get { Contract.Ensures (Contract.Result<System.Web.UI.WebControls.Style>() != null); return default(System.Web.UI.WebControls.Style); } } public override System.Web.UI.WebControls.ButtonType VerbButtonType { get { return default(System.Web.UI.WebControls.ButtonType); } set { } } public WebPartChrome WebPartChrome { get { return default(WebPartChrome); } } public WebPartCollection WebParts { get { Contract.Ensures (Contract.Result<System.Web.UI.WebControls.WebParts.WebPartCollection>() != null); return default(WebPartCollection); } } public virtual new WebPartVerbRenderMode WebPartVerbRenderMode { get { return default(WebPartVerbRenderMode); } set { } } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Pidgin { public abstract partial class Parser<TToken, T> { /// <summary> /// Creates a parser which applies the current parser repeatedly, interleaved with a specified parser. /// The resulting parser ignores the return value of the separator parser. /// </summary> /// <typeparam name="U">The return type of the separator parser</typeparam> /// <param name="separator">A parser which parses a separator to be interleaved with the current parser</param> /// <returns>A parser which applies the current parser repeatedly, interleaved by <paramref name="separator"/></returns> public Parser<TToken, IEnumerable<T>> Separated<U>(Parser<TToken, U> separator) { if (separator == null) { throw new ArgumentNullException(nameof(separator)); } return this.SeparatedAtLeastOnce(separator) .Or(ReturnEmptyEnumerable); } /// <summary> /// Creates a parser which applies the current parser at least once, interleaved with a specified parser. /// The resulting parser ignores the return value of the separator parser. /// </summary> /// <typeparam name="U">The return type of the separator parser</typeparam> /// <param name="separator">A parser which parses a separator to be interleaved with the current parser</param> /// <returns>A parser which applies the current parser at least once, interleaved by <paramref name="separator"/></returns> public Parser<TToken, IEnumerable<T>> SeparatedAtLeastOnce<U>(Parser<TToken, U> separator) { if (separator == null) { throw new ArgumentNullException(nameof(separator)); } return new SeparatedAtLeastOnceParser<TToken, T, U>(this, separator); } /// <summary> /// Creates a parser which applies the current parser repeatedly, interleaved and terminated with a specified parser. /// The resulting parser ignores the return value of the separator parser. /// </summary> /// <typeparam name="U">The return type of the separator parser</typeparam> /// <param name="separator">A parser which parses a separator to be interleaved with the current parser</param> /// <returns>A parser which applies the current parser repeatedly, interleaved and terminated by <paramref name="separator"/></returns> public Parser<TToken, IEnumerable<T>> SeparatedAndTerminated<U>(Parser<TToken, U> separator) { if (separator == null) { throw new ArgumentNullException(nameof(separator)); } return this.Before(separator).Many(); } /// <summary> /// Creates a parser which applies the current parser at least once, interleaved and terminated with a specified parser. /// The resulting parser ignores the return value of the separator parser. /// </summary> /// <typeparam name="U">The return type of the separator parser</typeparam> /// <param name="separator">A parser which parses a separator to be interleaved with the current parser</param> /// <returns>A parser which applies the current parser at least once, interleaved and terminated by <paramref name="separator"/></returns> public Parser<TToken, IEnumerable<T>> SeparatedAndTerminatedAtLeastOnce<U>(Parser<TToken, U> separator) { if (separator == null) { throw new ArgumentNullException(nameof(separator)); } return this.Before(separator).AtLeastOnce(); } /// <summary> /// Creates a parser which applies the current parser repeatedly, interleaved and optionally terminated with a specified parser. /// The resulting parser ignores the return value of the separator parser. /// </summary> /// <typeparam name="U">The return type of the separator parser</typeparam> /// <param name="separator">A parser which parses a separator to be interleaved with the current parser</param> /// <returns>A parser which applies the current parser repeatedly, interleaved and optionally terminated by <paramref name="separator"/></returns> public Parser<TToken, IEnumerable<T>> SeparatedAndOptionallyTerminated<U>(Parser<TToken, U> separator) { if (separator == null) { throw new ArgumentNullException(nameof(separator)); } return this.SeparatedAndOptionallyTerminatedAtLeastOnce(separator) .Or(ReturnEmptyEnumerable); } /// <summary> /// Creates a parser which applies the current parser at least once, interleaved and optionally terminated with a specified parser. /// The resulting parser ignores the return value of the separator parser. /// </summary> /// <typeparam name="U">The return type of the separator parser</typeparam> /// <param name="separator">A parser which parses a separator to be interleaved with the current parser</param> /// <returns>A parser which applies the current parser at least once, interleaved and optionally terminated by <paramref name="separator"/></returns> public Parser<TToken, IEnumerable<T>> SeparatedAndOptionallyTerminatedAtLeastOnce<U>(Parser<TToken, U> separator) { if (separator == null) { throw new ArgumentNullException(nameof(separator)); } return new SeparatedAndOptionallyTerminatedAtLeastOnceParser<TToken, T, U>(this, separator); } } internal sealed class SeparatedAtLeastOnceParser<TToken, T, U> : Parser<TToken, IEnumerable<T>> { private readonly Parser<TToken, T> _parser; private readonly Parser<TToken, T> _remainderParser; public SeparatedAtLeastOnceParser(Parser<TToken, T> parser, Parser<TToken, U> separator) { _parser = parser; _remainderParser = separator.Then(parser); } public sealed override bool TryParse(ref ParseState<TToken> state, ref PooledList<Expected<TToken>> expecteds, [MaybeNullWhen(false)] out IEnumerable<T> result) { if (!_parser.TryParse(ref state, ref expecteds, out var result1)) { // state.Error set by _parser result = null; return false; } var list = new List<T> { result1 }; if (!Rest(_remainderParser, ref state, ref expecteds, list)) { result = null; return false; } result = list; return true; } private bool Rest(Parser<TToken, T> parser, ref ParseState<TToken> state, ref PooledList<Expected<TToken>> expecteds, List<T> ts) { var lastStartingLoc = state.Location; var childExpecteds = new PooledList<Expected<TToken>>(state.Configuration.ArrayPoolProvider.GetArrayPool<Expected<TToken>>()); while (parser.TryParse(ref state, ref childExpecteds, out var result)) { var endingLoc = state.Location; childExpecteds.Clear(); if (endingLoc <= lastStartingLoc) { childExpecteds.Dispose(); throw new InvalidOperationException("Many() used with a parser which consumed no input"); } ts.Add(result); lastStartingLoc = endingLoc; } var lastParserConsumedInput = state.Location > lastStartingLoc; if (lastParserConsumedInput) { expecteds.AddRange(childExpecteds.AsSpan()); } childExpecteds.Dispose(); // we fail if the most recent parser failed after consuming input. // it sets state.Error for us return !lastParserConsumedInput; } } internal sealed class SeparatedAndOptionallyTerminatedAtLeastOnceParser<TToken, T, U> : Parser<TToken, IEnumerable<T>> { private readonly Parser<TToken, T> _parser; private readonly Parser<TToken, U> _separator; public SeparatedAndOptionallyTerminatedAtLeastOnceParser(Parser<TToken, T> parser, Parser<TToken, U> separator) { _parser = parser; _separator = separator; } public sealed override bool TryParse(ref ParseState<TToken> state, ref PooledList<Expected<TToken>> expecteds, [MaybeNullWhen(false)] out IEnumerable<T> result) { if (!_parser.TryParse(ref state, ref expecteds, out var result1)) { // state.Error set by _parser result = null; return false; } var ts = new List<T> { result1 }; var childExpecteds = new PooledList<Expected<TToken>>(state.Configuration.ArrayPoolProvider.GetArrayPool<Expected<TToken>>()); while (true) { var sepStartLoc = state.Location; var sepSuccess = _separator.TryParse(ref state, ref childExpecteds, out var _); var sepConsumedInput = state.Location > sepStartLoc; if (!sepSuccess && sepConsumedInput) { expecteds.AddRange(childExpecteds.AsSpan()); } childExpecteds.Clear(); if (!sepSuccess) { childExpecteds.Dispose(); if (sepConsumedInput) { // state.Error set by _separator result = null; return false; } result = ts; return true; } var itemStartLoc = state.Location; var itemSuccess = _parser.TryParse(ref state, ref childExpecteds, out var itemResult); var itemConsumedInput = state.Location > itemStartLoc; if (!itemSuccess && itemConsumedInput) { expecteds.AddRange(childExpecteds.AsSpan()); } childExpecteds.Clear(); if (!itemSuccess) { childExpecteds.Dispose(); if (itemConsumedInput) { // state.Error set by _parser result = null; return false; } result = ts; return true; } ts.Add(itemResult!); } } } }
namespace ContextualTabs { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.kryptonRibbon = new ComponentFactory.Krypton.Ribbon.KryptonRibbon(); this.kryptonContextMenuItem1 = new ComponentFactory.Krypton.Toolkit.KryptonContextMenuItem(); this.contextDefRed = new ComponentFactory.Krypton.Ribbon.KryptonRibbonContext(); this.contextDefGreen = new ComponentFactory.Krypton.Ribbon.KryptonRibbonContext(); this.tabHome = new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab(); this.contextRed = new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab(); this.contextGreen1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab(); this.contextGreen2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab(); this.labelOffice2007Styles = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this.groupOffice2007Styles = new ComponentFactory.Krypton.Toolkit.KryptonGroup(); this.radioSparkleOrange = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioSparklePurple = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioSparkleBlue = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioSystem = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioOffice2003 = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioOffice2007Black = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioOffice2007Silver = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioOffice2007Blue = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.kryptonLabel2 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.groupAddContext = new ComponentFactory.Krypton.Toolkit.KryptonGroup(); this.buttonAddContext = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.panelContextColor = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this.buttonEditColor = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.labelContextColor = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.textBoxContextTitle = new ComponentFactory.Krypton.Toolkit.KryptonTextBox(); this.labelContextTitle = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.labelContextName = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.textBoxContextName = new ComponentFactory.Krypton.Toolkit.KryptonTextBox(); this.kryptonLabel1 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.groupSelectedContexts = new ComponentFactory.Krypton.Toolkit.KryptonGroup(); this.labelSelectedContexts = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.buttonSelectedApply = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.textBoxSelectedContexts = new ComponentFactory.Krypton.Toolkit.KryptonTextBox(); this.labelContextsInstructions = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.colorDialog = new System.Windows.Forms.ColorDialog(); this.kryptonManager = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components); this.radioOffice2010Black = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioOffice2010Silver = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioOffice2010Blue = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); ((System.ComponentModel.ISupportInitialize)(this.kryptonRibbon)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.labelOffice2007Styles)).BeginInit(); this.labelOffice2007Styles.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.groupOffice2007Styles)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.groupOffice2007Styles.Panel)).BeginInit(); this.groupOffice2007Styles.Panel.SuspendLayout(); this.groupOffice2007Styles.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.groupAddContext)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.groupAddContext.Panel)).BeginInit(); this.groupAddContext.Panel.SuspendLayout(); this.groupAddContext.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.panelContextColor)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.groupSelectedContexts)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.groupSelectedContexts.Panel)).BeginInit(); this.groupSelectedContexts.Panel.SuspendLayout(); this.groupSelectedContexts.SuspendLayout(); this.SuspendLayout(); // // kryptonRibbon // this.kryptonRibbon.Name = "kryptonRibbon"; this.kryptonRibbon.RibbonAppButton.AppButtonMenuItems.AddRange(new ComponentFactory.Krypton.Toolkit.KryptonContextMenuItemBase[] { this.kryptonContextMenuItem1}); this.kryptonRibbon.RibbonAppButton.AppButtonShowRecentDocs = false; this.kryptonRibbon.RibbonContexts.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonContext[] { this.contextDefRed, this.contextDefGreen}); this.kryptonRibbon.RibbonTabs.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab[] { this.tabHome, this.contextRed, this.contextGreen1, this.contextGreen2}); this.kryptonRibbon.SelectedContext = "Red,Green"; this.kryptonRibbon.SelectedTab = this.contextGreen1; this.kryptonRibbon.Size = new System.Drawing.Size(594, 114); this.kryptonRibbon.TabIndex = 0; // // kryptonContextMenuItem1 // this.kryptonContextMenuItem1.Image = ((System.Drawing.Image)(resources.GetObject("kryptonContextMenuItem1.Image"))); this.kryptonContextMenuItem1.Text = "E&xit"; this.kryptonContextMenuItem1.Click += new System.EventHandler(this.appMenu_Click); // // contextDefRed // this.contextDefRed.ContextName = "Red"; this.contextDefRed.ContextTitle = "Red"; // // contextDefGreen // this.contextDefGreen.ContextColor = System.Drawing.Color.LimeGreen; this.contextDefGreen.ContextName = "Green"; this.contextDefGreen.ContextTitle = "Green"; // // tabHome // this.tabHome.Text = "Home"; // // contextRed // this.contextRed.ContextName = "Red"; this.contextRed.Text = "Red"; // // contextGreen1 // this.contextGreen1.ContextName = "Green"; this.contextGreen1.Text = "Green1"; // // contextGreen2 // this.contextGreen2.ContextName = "Green"; this.contextGreen2.Text = "Green2"; // // labelOffice2007Styles // this.labelOffice2007Styles.Controls.Add(this.groupOffice2007Styles); this.labelOffice2007Styles.Controls.Add(this.groupAddContext); this.labelOffice2007Styles.Controls.Add(this.groupSelectedContexts); this.labelOffice2007Styles.Dock = System.Windows.Forms.DockStyle.Fill; this.labelOffice2007Styles.Location = new System.Drawing.Point(0, 114); this.labelOffice2007Styles.Name = "labelOffice2007Styles"; this.labelOffice2007Styles.Size = new System.Drawing.Size(594, 374); this.labelOffice2007Styles.TabIndex = 1; // // groupOffice2007Styles // this.groupOffice2007Styles.GroupBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.PanelAlternate; this.groupOffice2007Styles.Location = new System.Drawing.Point(401, 16); this.groupOffice2007Styles.Name = "groupOffice2007Styles"; // // groupOffice2007Styles.Panel // this.groupOffice2007Styles.Panel.Controls.Add(this.radioOffice2010Black); this.groupOffice2007Styles.Panel.Controls.Add(this.radioOffice2010Silver); this.groupOffice2007Styles.Panel.Controls.Add(this.radioOffice2010Blue); this.groupOffice2007Styles.Panel.Controls.Add(this.radioSparkleOrange); this.groupOffice2007Styles.Panel.Controls.Add(this.radioSparklePurple); this.groupOffice2007Styles.Panel.Controls.Add(this.radioSparkleBlue); this.groupOffice2007Styles.Panel.Controls.Add(this.radioSystem); this.groupOffice2007Styles.Panel.Controls.Add(this.radioOffice2003); this.groupOffice2007Styles.Panel.Controls.Add(this.radioOffice2007Black); this.groupOffice2007Styles.Panel.Controls.Add(this.radioOffice2007Silver); this.groupOffice2007Styles.Panel.Controls.Add(this.radioOffice2007Blue); this.groupOffice2007Styles.Panel.Controls.Add(this.kryptonLabel2); this.groupOffice2007Styles.Size = new System.Drawing.Size(180, 305); this.groupOffice2007Styles.TabIndex = 0; // // radioSparkleOrange // this.radioSparkleOrange.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.radioSparkleOrange.Location = new System.Drawing.Point(20, 222); this.radioSparkleOrange.Name = "radioSparkleOrange"; this.radioSparkleOrange.Size = new System.Drawing.Size(110, 19); this.radioSparkleOrange.TabIndex = 9; this.radioSparkleOrange.Values.Text = "Sparkle - Orange"; this.radioSparkleOrange.CheckedChanged += new System.EventHandler(this.radioSparkleOrange_CheckedChanged); // // radioSparklePurple // this.radioSparklePurple.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.radioSparklePurple.Location = new System.Drawing.Point(20, 245); this.radioSparklePurple.Name = "radioSparklePurple"; this.radioSparklePurple.Size = new System.Drawing.Size(104, 19); this.radioSparklePurple.TabIndex = 10; this.radioSparklePurple.Values.Text = "Sparkle - Purple"; this.radioSparklePurple.CheckedChanged += new System.EventHandler(this.radioSparklePurple_CheckedChanged); // // radioSparkleBlue // this.radioSparkleBlue.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.radioSparkleBlue.Location = new System.Drawing.Point(20, 199); this.radioSparkleBlue.Name = "radioSparkleBlue"; this.radioSparkleBlue.Size = new System.Drawing.Size(93, 19); this.radioSparkleBlue.TabIndex = 8; this.radioSparkleBlue.Values.Text = "Sparkle - Blue"; this.radioSparkleBlue.CheckedChanged += new System.EventHandler(this.radioSparkleBlue_CheckedChanged); // // radioSystem // this.radioSystem.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.radioSystem.Location = new System.Drawing.Point(21, 268); this.radioSystem.Name = "radioSystem"; this.radioSystem.Size = new System.Drawing.Size(59, 19); this.radioSystem.TabIndex = 11; this.radioSystem.Values.Text = "System"; this.radioSystem.CheckedChanged += new System.EventHandler(this.radioSystem_CheckedChanged); // // radioOffice2003 // this.radioOffice2003.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.radioOffice2003.Location = new System.Drawing.Point(20, 176); this.radioOffice2003.Name = "radioOffice2003"; this.radioOffice2003.Size = new System.Drawing.Size(81, 19); this.radioOffice2003.TabIndex = 7; this.radioOffice2003.Values.Text = "Office 2003"; this.radioOffice2003.CheckedChanged += new System.EventHandler(this.radioOffice2003_CheckedChanged); // // radioOffice2007Black // this.radioOffice2007Black.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.radioOffice2007Black.Location = new System.Drawing.Point(20, 153); this.radioOffice2007Black.Name = "radioOffice2007Black"; this.radioOffice2007Black.Size = new System.Drawing.Size(119, 19); this.radioOffice2007Black.TabIndex = 6; this.radioOffice2007Black.Values.Text = "Office 2007 - Black"; this.radioOffice2007Black.CheckedChanged += new System.EventHandler(this.radioOffice2007Black_CheckedChanged); // // radioOffice2007Silver // this.radioOffice2007Silver.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.radioOffice2007Silver.Location = new System.Drawing.Point(20, 130); this.radioOffice2007Silver.Name = "radioOffice2007Silver"; this.radioOffice2007Silver.Size = new System.Drawing.Size(120, 19); this.radioOffice2007Silver.TabIndex = 5; this.radioOffice2007Silver.Values.Text = "Office 2007 - Silver"; this.radioOffice2007Silver.CheckedChanged += new System.EventHandler(this.radioOffice2007Silver_CheckedChanged); // // radioOffice2007Blue // this.radioOffice2007Blue.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.radioOffice2007Blue.Location = new System.Drawing.Point(20, 107); this.radioOffice2007Blue.Name = "radioOffice2007Blue"; this.radioOffice2007Blue.Size = new System.Drawing.Size(114, 19); this.radioOffice2007Blue.TabIndex = 4; this.radioOffice2007Blue.Values.Text = "Office 2007 - Blue"; this.radioOffice2007Blue.CheckedChanged += new System.EventHandler(this.radioOffice2007Blue_CheckedChanged); // // kryptonLabel2 // this.kryptonLabel2.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.TitlePanel; this.kryptonLabel2.Location = new System.Drawing.Point(4, 4); this.kryptonLabel2.Name = "kryptonLabel2"; this.kryptonLabel2.Size = new System.Drawing.Size(130, 28); this.kryptonLabel2.TabIndex = 0; this.kryptonLabel2.Values.Text = "Global Palette"; // // groupAddContext // this.groupAddContext.GroupBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.PanelAlternate; this.groupAddContext.Location = new System.Drawing.Point(16, 160); this.groupAddContext.Name = "groupAddContext"; // // groupAddContext.Panel // this.groupAddContext.Panel.Controls.Add(this.buttonAddContext); this.groupAddContext.Panel.Controls.Add(this.panelContextColor); this.groupAddContext.Panel.Controls.Add(this.buttonEditColor); this.groupAddContext.Panel.Controls.Add(this.labelContextColor); this.groupAddContext.Panel.Controls.Add(this.textBoxContextTitle); this.groupAddContext.Panel.Controls.Add(this.labelContextTitle); this.groupAddContext.Panel.Controls.Add(this.labelContextName); this.groupAddContext.Panel.Controls.Add(this.textBoxContextName); this.groupAddContext.Panel.Controls.Add(this.kryptonLabel1); this.groupAddContext.Size = new System.Drawing.Size(371, 161); this.groupAddContext.TabIndex = 5; // // buttonAddContext // this.buttonAddContext.AutoSize = true; this.buttonAddContext.Location = new System.Drawing.Point(97, 123); this.buttonAddContext.Name = "buttonAddContext"; this.buttonAddContext.Size = new System.Drawing.Size(94, 24); this.buttonAddContext.TabIndex = 10; this.buttonAddContext.Values.Text = "Add Context"; this.buttonAddContext.Click += new System.EventHandler(this.buttonAddContext_Click); // // panelContextColor // this.panelContextColor.Location = new System.Drawing.Point(97, 88); this.panelContextColor.Name = "panelContextColor"; this.panelContextColor.Size = new System.Drawing.Size(94, 23); this.panelContextColor.StateCommon.Color1 = System.Drawing.Color.DodgerBlue; this.panelContextColor.TabIndex = 9; // // buttonEditColor // this.buttonEditColor.AutoSize = true; this.buttonEditColor.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.buttonEditColor.Location = new System.Drawing.Point(197, 88); this.buttonEditColor.Name = "buttonEditColor"; this.buttonEditColor.Size = new System.Drawing.Size(75, 23); this.buttonEditColor.TabIndex = 8; this.buttonEditColor.Values.Text = "Define Color"; this.buttonEditColor.Click += new System.EventHandler(this.buttonEditColor_Click); // // labelContextColor // this.labelContextColor.AutoSize = false; this.labelContextColor.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.labelContextColor.Location = new System.Drawing.Point(9, 88); this.labelContextColor.Name = "labelContextColor"; this.labelContextColor.Size = new System.Drawing.Size(82, 22); this.labelContextColor.StateCommon.ShortText.TextH = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Far; this.labelContextColor.TabIndex = 7; this.labelContextColor.Values.Text = "Context Color"; // // textBoxContextTitle // this.textBoxContextTitle.Location = new System.Drawing.Point(97, 62); this.textBoxContextTitle.Name = "textBoxContextTitle"; this.textBoxContextTitle.Size = new System.Drawing.Size(95, 20); this.textBoxContextTitle.TabIndex = 6; this.textBoxContextTitle.Text = "Tools"; // // labelContextTitle // this.labelContextTitle.AutoSize = false; this.labelContextTitle.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.labelContextTitle.Location = new System.Drawing.Point(9, 63); this.labelContextTitle.Name = "labelContextTitle"; this.labelContextTitle.Size = new System.Drawing.Size(82, 22); this.labelContextTitle.StateCommon.ShortText.TextH = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Far; this.labelContextTitle.TabIndex = 5; this.labelContextTitle.Values.Text = "Context Title"; // // labelContextName // this.labelContextName.AutoSize = false; this.labelContextName.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.labelContextName.Location = new System.Drawing.Point(9, 38); this.labelContextName.Name = "labelContextName"; this.labelContextName.Size = new System.Drawing.Size(82, 22); this.labelContextName.StateCommon.ShortText.TextH = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Far; this.labelContextName.TabIndex = 4; this.labelContextName.Values.Text = "Context Name"; // // textBoxContextName // this.textBoxContextName.Location = new System.Drawing.Point(97, 37); this.textBoxContextName.Name = "textBoxContextName"; this.textBoxContextName.Size = new System.Drawing.Size(95, 20); this.textBoxContextName.TabIndex = 3; this.textBoxContextName.Text = "Blue"; // // kryptonLabel1 // this.kryptonLabel1.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.TitlePanel; this.kryptonLabel1.Location = new System.Drawing.Point(4, 4); this.kryptonLabel1.Name = "kryptonLabel1"; this.kryptonLabel1.Size = new System.Drawing.Size(118, 28); this.kryptonLabel1.TabIndex = 2; this.kryptonLabel1.Values.Text = "Add Context"; // // groupSelectedContexts // this.groupSelectedContexts.GroupBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.PanelAlternate; this.groupSelectedContexts.Location = new System.Drawing.Point(16, 16); this.groupSelectedContexts.Name = "groupSelectedContexts"; // // groupSelectedContexts.Panel // this.groupSelectedContexts.Panel.Controls.Add(this.labelSelectedContexts); this.groupSelectedContexts.Panel.Controls.Add(this.buttonSelectedApply); this.groupSelectedContexts.Panel.Controls.Add(this.textBoxSelectedContexts); this.groupSelectedContexts.Panel.Controls.Add(this.labelContextsInstructions); this.groupSelectedContexts.Size = new System.Drawing.Size(371, 129); this.groupSelectedContexts.TabIndex = 4; // // labelSelectedContexts // this.labelSelectedContexts.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.TitlePanel; this.labelSelectedContexts.Location = new System.Drawing.Point(4, 4); this.labelSelectedContexts.Name = "labelSelectedContexts"; this.labelSelectedContexts.Size = new System.Drawing.Size(162, 28); this.labelSelectedContexts.TabIndex = 1; this.labelSelectedContexts.Values.Text = "Selected Contexts"; // // buttonSelectedApply // this.buttonSelectedApply.AutoSize = true; this.buttonSelectedApply.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.buttonSelectedApply.Location = new System.Drawing.Point(311, 35); this.buttonSelectedApply.Name = "buttonSelectedApply"; this.buttonSelectedApply.Size = new System.Drawing.Size(40, 23); this.buttonSelectedApply.TabIndex = 3; this.buttonSelectedApply.Values.Text = "Apply"; this.buttonSelectedApply.Click += new System.EventHandler(this.buttonSelectedApply_Click); // // textBoxSelectedContexts // this.textBoxSelectedContexts.Location = new System.Drawing.Point(9, 36); this.textBoxSelectedContexts.Name = "textBoxSelectedContexts"; this.textBoxSelectedContexts.Size = new System.Drawing.Size(296, 20); this.textBoxSelectedContexts.TabIndex = 0; this.textBoxSelectedContexts.Text = "Red,Green"; this.textBoxSelectedContexts.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBoxSelectedContexts_KeyDown); // // labelContextsInstructions // this.labelContextsInstructions.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.labelContextsInstructions.Location = new System.Drawing.Point(5, 64); this.labelContextsInstructions.Name = "labelContextsInstructions"; this.labelContextsInstructions.Size = new System.Drawing.Size(300, 49); this.labelContextsInstructions.TabIndex = 2; this.labelContextsInstructions.Values.Text = "Use a common separated list of context names and then\r\npress the \'Apply\' button. " + "To remove all contextual tabs\r\njust remove all the text and press \'Apply\'."; // // colorDialog // this.colorDialog.AnyColor = true; this.colorDialog.Color = System.Drawing.Color.DodgerBlue; this.colorDialog.FullOpen = true; this.colorDialog.SolidColorOnly = true; // // radioOffice2010Black // this.radioOffice2010Black.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.radioOffice2010Black.Location = new System.Drawing.Point(20, 84); this.radioOffice2010Black.Name = "radioOffice2010Black"; this.radioOffice2010Black.Size = new System.Drawing.Size(119, 19); this.radioOffice2010Black.TabIndex = 3; this.radioOffice2010Black.Values.Text = "Office 2010 - Black"; this.radioOffice2010Black.CheckedChanged += new System.EventHandler(this.radioOffice2010Black_CheckedChanged); // // radioOffice2010Silver // this.radioOffice2010Silver.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.radioOffice2010Silver.Location = new System.Drawing.Point(20, 61); this.radioOffice2010Silver.Name = "radioOffice2010Silver"; this.radioOffice2010Silver.Size = new System.Drawing.Size(120, 19); this.radioOffice2010Silver.TabIndex = 2; this.radioOffice2010Silver.Values.Text = "Office 2010 - Silver"; this.radioOffice2010Silver.CheckedChanged += new System.EventHandler(this.radioOffice2010Silver_CheckedChanged); // // radioOffice2010Blue // this.radioOffice2010Blue.Checked = true; this.radioOffice2010Blue.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.radioOffice2010Blue.Location = new System.Drawing.Point(20, 38); this.radioOffice2010Blue.Name = "radioOffice2010Blue"; this.radioOffice2010Blue.Size = new System.Drawing.Size(114, 19); this.radioOffice2010Blue.TabIndex = 1; this.radioOffice2010Blue.Values.Text = "Office 2010 - Blue"; this.radioOffice2010Blue.CheckedChanged += new System.EventHandler(this.radioOffice2010Blue_CheckedChanged); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(594, 488); this.Controls.Add(this.labelOffice2007Styles); this.Controls.Add(this.kryptonRibbon); this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(602, 511); this.Name = "Form1"; this.StateCommon.Header.Content.LongText.TextH = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Center; this.StateCommon.Header.Content.ShortText.TextH = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Center; this.Text = "Contextual Tabs"; ((System.ComponentModel.ISupportInitialize)(this.kryptonRibbon)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.labelOffice2007Styles)).EndInit(); this.labelOffice2007Styles.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.groupOffice2007Styles.Panel)).EndInit(); this.groupOffice2007Styles.Panel.ResumeLayout(false); this.groupOffice2007Styles.Panel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.groupOffice2007Styles)).EndInit(); this.groupOffice2007Styles.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.groupAddContext.Panel)).EndInit(); this.groupAddContext.Panel.ResumeLayout(false); this.groupAddContext.Panel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.groupAddContext)).EndInit(); this.groupAddContext.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.panelContextColor)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.groupSelectedContexts.Panel)).EndInit(); this.groupSelectedContexts.Panel.ResumeLayout(false); this.groupSelectedContexts.Panel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.groupSelectedContexts)).EndInit(); this.groupSelectedContexts.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBoxSelectedContexts; private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBoxContextTitle; private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBoxContextName; private ComponentFactory.Krypton.Ribbon.KryptonRibbon kryptonRibbon; private ComponentFactory.Krypton.Ribbon.KryptonRibbonContext contextDefRed; private ComponentFactory.Krypton.Ribbon.KryptonRibbonContext contextDefGreen; private ComponentFactory.Krypton.Ribbon.KryptonRibbonTab tabHome; private ComponentFactory.Krypton.Ribbon.KryptonRibbonTab contextRed; private ComponentFactory.Krypton.Ribbon.KryptonRibbonTab contextGreen1; private ComponentFactory.Krypton.Toolkit.KryptonPanel labelOffice2007Styles; private ComponentFactory.Krypton.Toolkit.KryptonLabel labelSelectedContexts; private ComponentFactory.Krypton.Toolkit.KryptonButton buttonSelectedApply; private ComponentFactory.Krypton.Toolkit.KryptonLabel labelContextsInstructions; private ComponentFactory.Krypton.Toolkit.KryptonGroup groupAddContext; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel1; private ComponentFactory.Krypton.Toolkit.KryptonGroup groupSelectedContexts; private ComponentFactory.Krypton.Toolkit.KryptonLabel labelContextColor; private ComponentFactory.Krypton.Toolkit.KryptonLabel labelContextTitle; private ComponentFactory.Krypton.Toolkit.KryptonLabel labelContextName; private ComponentFactory.Krypton.Toolkit.KryptonPanel panelContextColor; private ComponentFactory.Krypton.Toolkit.KryptonButton buttonEditColor; private ComponentFactory.Krypton.Toolkit.KryptonButton buttonAddContext; private ComponentFactory.Krypton.Ribbon.KryptonRibbonTab contextGreen2; private ComponentFactory.Krypton.Toolkit.KryptonGroup groupOffice2007Styles; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel2; private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager; private System.Windows.Forms.ColorDialog colorDialog; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioSystem; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2003; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2007Black; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2007Silver; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2007Blue; private ComponentFactory.Krypton.Toolkit.KryptonContextMenuItem kryptonContextMenuItem1; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioSparkleBlue; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioSparkleOrange; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioSparklePurple; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2010Black; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2010Silver; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2010Blue; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.AttributeStringLiteralsShouldParseCorrectlyAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.AttributeStringLiteralsShouldParseCorrectlyAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests { public class AttributeStringLiteralsShouldParseCorrectlyTests { [Fact] public async Task CA2243_BadAttributeStringLiterals_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public sealed class BadAttributeStringLiterals { private sealed class MyLiteralsAttribute : Attribute { private string m_url; private string m_version; private string m_guid; public MyLiteralsAttribute() { } public MyLiteralsAttribute(string url) { m_url = url; } public MyLiteralsAttribute(string url, int dummy1, string thisIsAVersion, int dummy2) { m_url = url; m_version = thisIsAVersion; if (dummy1 > dummy2) // just random stuff to use these arguments m_version = """"; } public string Url { get { return m_url; } set { m_url = value; } } public string Version { get { return m_version; } set { m_version = value; } } public string GUID { get { return m_guid; } set { m_guid = value; } } } [MyLiterals(GUID = ""bad-guid"")] private int x; public BadAttributeStringLiterals() { DoNothing(1); } [MyLiterals(Url = ""bad url"", Version = ""helloworld"")] private void DoNothing( [MyLiterals(""bad url"")] int y) { if (x > 0) DoNothing2(y); } [MyLiterals(""good/url"", 5, ""1.0.bad"", 5)] private void DoNothing2(int y) { this.x = y; } }", CA2243CSharpDefaultResultAt(25, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "BadAttributeStringLiterals.MyLiteralsAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(29, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "BadAttributeStringLiterals.MyLiteralsAttribute.Url", "bad url", "Uri"), CA2243CSharpDefaultResultAt(31, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "url", "bad url", "Uri")); } [Fact] public async Task CA2243_BadGuids_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [GuidAttribute(GUID = ""bad-guid"")] public class ClassWithBadlyFormattedNamedArgumentGuid { } [GuidAttribute(GUID = ""59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF"")] public class ClassWithTooManyDashesNamedArgumentGuid { } [GuidAttribute(GUID = ""{0xCA761232, 0xED421111111, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x11}}"")] public class ClassWithOverflowNamedArgumentGuid { } [GuidAttribute(GUID = """")] public class ClassWithEmptyNamedArgumentGuid { } [GuidAttribute(""bad-guid"")] public class ClassWithBadlyFormattedRequiredArgumentGuid { } [GuidAttribute(""59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF"")] public class ClassWithTooManyDashesRequiredArgumentGuid { } [GuidAttribute(""{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x99999}}"")] public class ClassWithOverflowRequiredArgumentGuid { } [GuidAttribute("""")] public class ClassWithEmptyRequiredArgumentGuid { } [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public sealed class GuidAttribute : Attribute { private string m_guid; public GuidAttribute() { } public GuidAttribute(string ThisIsAGuid) { m_guid = ThisIsAGuid; } public string GUID { get { return m_guid; } set { m_guid = value; } } } ", CA2243CSharpDefaultResultAt(4, 2, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(9, 2, "GuidAttribute", "GuidAttribute.GUID", "59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF", "Guid"), CA2243CSharpDefaultResultAt(14, 2, "GuidAttribute", "GuidAttribute.GUID", "{0xCA761232, 0xED421111111, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x11}}", "Guid"), CA2243CSharpEmptyResultAt(19, 2, "GuidAttribute", "GuidAttribute.GUID", "Guid"), CA2243CSharpDefaultResultAt(24, 2, "GuidAttribute", "ThisIsAGuid", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(29, 2, "GuidAttribute", "ThisIsAGuid", "59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF", "Guid"), CA2243CSharpDefaultResultAt(34, 2, "GuidAttribute", "ThisIsAGuid", "{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x99999}}", "Guid"), CA2243CSharpEmptyResultAt(39, 2, "GuidAttribute", "ThisIsAGuid", "Guid")); } [Fact] public async Task CA2243_MiscSymbolsWithBadGuid_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [assembly: GuidAttribute(GUID = ""bad-guid"")] public delegate void MiscDelegate([GuidAttribute(GUID = ""bad-guid"")] int p); public class MiscClass<[GuidAttribute(GUID = ""bad-guid"")] U> { public MiscClass<U> this[[GuidAttribute(GUID = ""bad-guid"")] int index] { get { return null; } set { } } public void M<[GuidAttribute(GUID = ""bad-guid"")] T>() { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public sealed class GuidAttribute : Attribute { private string m_guid; public GuidAttribute() { } public GuidAttribute(string ThisIsAGuid) { m_guid = ThisIsAGuid; } public string GUID { get { return m_guid; } set { m_guid = value; } } } ", CA2243CSharpDefaultResultAt(4, 12, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(6, 36, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(8, 25, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(10, 31, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243CSharpDefaultResultAt(21, 20, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid")); } [Fact] public async Task CA2243_NoDiagnostics_CSharpAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public sealed class GoodAttributeStringLiterals { private sealed class MyLiteralsAttribute : Attribute { private string m_url; private string m_version; private string m_guid; private int m_notAVersion; public MyLiteralsAttribute() { } public MyLiteralsAttribute(string url) { m_url = url; } public MyLiteralsAttribute(string url, int dummy1, string thisIsAVersion, int notAVersion) { m_url = url; m_version = thisIsAVersion; m_notAVersion = notAVersion + dummy1; } public string Url { get { return m_url; } set { m_url = value; } } public string Version { get { return m_version; } set { m_version = value; } } public string GUID { get { return m_guid; } set { m_guid = value; } } public int NotAVersion { get { return m_notAVersion; } set { m_notAVersion = value; } } } [MyLiterals(""good/relative/url"", GUID = ""8fcd093bc1058acf8fcd093bc1058acf"", Version = ""1.4.325.12"")] private int x; public GoodAttributeStringLiterals() { DoNothing(1); } [MyLiterals(GUID = ""{8fcd093b-c105-8acf-8fcd-093bc1058acf}"", Url = ""http://good/absolute/url.htm"")] private void DoNothing( [MyLiterals(""goodurl/"", NotAVersion = 12)] int y) { if (x > 0) DoNothing2(y); } [MyLiterals(""http://good/url"", 5, ""1.0.50823.98"", 5)] private void DoNothing2(int y) { this.x = y; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public sealed class UriTemplateAttribute : Attribute { private string m_uriTemplate; public UriTemplateAttribute() { } public UriTemplateAttribute(string uriTemplate) { m_uriTemplate = uriTemplate; } public string UriTemplate { get { return m_uriTemplate; } set { m_uriTemplate = value; } } } public static class ClassWithExceptionForUri { [UriTemplate(UriTemplate=""{0}"")] public static void MethodWithInvalidUriNamedArgumentThatShouldBeIgnored() { } [UriTemplate(UriTemplate = """")] public static void MethodWithEmptyUriNamedArgumentThatShouldBeIgnored() { } [UriTemplate(""{0}"")] public static void MethodWithInvalidUriRequiredArgumentThatShouldBeIgnored() { } [UriTemplate("""")] public static void MethodWithEmptyUriRequiredArgumentThatShouldBeIgnored() { } }"); } [Fact] public async Task CA2243_BadAttributeStringLiterals_BasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Public NotInheritable Class BadAttributeStringLiterals <MyLiterals(GUID:=""bad-guid"")> Private x As Integer Public Sub New() DoNothing(1) End Sub <MyLiterals(Url:=""bad url"", Version:=""helloworld"")> Private Sub DoNothing(<MyLiterals(""bad url"")> y As Integer) If x > 0 Then DoNothing2(y) End If End Sub <MyLiterals(""good/url"", 5, ""1.0.bad"", 5)> Private Sub DoNothing2(y As Integer) Me.x = y End Sub Private NotInheritable Class MyLiteralsAttribute Inherits Attribute Private m_url As String Private m_version As String Private m_guid As String Public Sub New() End Sub Public Sub New(url As String) m_url = url End Sub Public Sub New(url As String, dummy1 As Integer, thisIsAVersion As String, dummy2 As Integer) m_url = url m_version = thisIsAVersion If dummy1 > dummy2 Then ' just random stuff to use these arguments m_version = """" End If End Sub Public Property Url() As String Get Return m_url End Get Set m_url = value End Set End Property Public Property Version() As String Get Return m_version End Get Set m_version = value End Set End Property Public Property GUID() As String Get Return m_guid End Get Set m_guid = value End Set End Property End Class End Class", CA2243BasicDefaultResultAt(5, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "BadAttributeStringLiterals.MyLiteralsAttribute.GUID", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(11, 6, "BadAttributeStringLiterals.MyLiteralsAttribute", "BadAttributeStringLiterals.MyLiteralsAttribute.Url", "bad url", "Uri"), CA2243BasicDefaultResultAt(12, 28, "BadAttributeStringLiterals.MyLiteralsAttribute", "url", "bad url", "Uri")); } [Fact] public async Task CA2243_BadGuids_BasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System <GuidAttribute(GUID := ""bad-guid"")> _ Public Class ClassWithBadlyFormattedNamedArgumentGuid End Class <GuidAttribute(GUID := ""59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF"")> _ Public Class ClassWithTooManyDashesNamedArgumentGuid End Class <GuidAttribute(GUID := ""{0xCA761232, 0xED421111111, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x11}}"")> _ Public Class ClassWithOverflowNamedArgumentGuid End Class <GuidAttribute(GUID := """")> _ Public Class ClassWithEmptyNamedArgumentGuid End Class <GuidAttribute(""bad-guid"")> _ Public Class ClassWithBadlyFormattedRequiredArgumentGuid End Class <GuidAttribute(""59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF"")> _ Public Class ClassWithTooManyDashesRequiredArgumentGuid End Class <GuidAttribute(""{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x99999}}"")> _ Public Class ClassWithOverflowRequiredArgumentGuid End Class <GuidAttribute("""")> _ Public Class ClassWithEmptyRequiredArgumentGuid End Class <AttributeUsage(AttributeTargets.All, AllowMultiple := False)> _ Public NotInheritable Class GuidAttribute Inherits Attribute Private m_guid As String Public Sub New() End Sub Public Sub New(ThisIsAGuid As String) m_guid = ThisIsAGuid End Sub Public Property GUID() As String Get Return m_guid End Get Set m_guid = value End Set End Property End Class ", CA2243BasicDefaultResultAt(4, 2, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(8, 2, "GuidAttribute", "GuidAttribute.GUID", "59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF", "Guid"), CA2243BasicDefaultResultAt(12, 2, "GuidAttribute", "GuidAttribute.GUID", "{0xCA761232, 0xED421111111, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x11}}", "Guid"), CA2243BasicEmptyResultAt(16, 2, "GuidAttribute", "GuidAttribute.GUID", "Guid"), CA2243BasicDefaultResultAt(20, 2, "GuidAttribute", "ThisIsAGuid", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(24, 2, "GuidAttribute", "ThisIsAGuid", "59C91206-1BE9-4c54-A7EC-1941387E32DC-AFDF", "Guid"), CA2243BasicDefaultResultAt(28, 2, "GuidAttribute", "ThisIsAGuid", "{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x99999}}", "Guid"), CA2243BasicEmptyResultAt(32, 2, "GuidAttribute", "ThisIsAGuid", "Guid")); } [Fact] public async Task CA2243_MiscSymbolsWithBadGuid_BasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System <Assembly: GuidAttribute(GUID := ""bad-guid"")> Public Delegate Sub MiscDelegate(<GuidAttribute(GUID := ""bad-guid"")> p As Integer) Public Class MiscClass Public Default Property Item(<GuidAttribute(GUID := ""bad-guid"")> index As Integer) As MiscClass Get Return Nothing End Get Set End Set End Property End Class <AttributeUsage(AttributeTargets.All, AllowMultiple := True)> _ Public NotInheritable Class GuidAttribute Inherits Attribute Private m_guid As String Public Sub New() End Sub Public Sub New(ThisIsAGuid As String) m_guid = ThisIsAGuid End Sub Public Property GUID() As String Get Return m_guid End Get Set m_guid = value End Set End Property End Class ", CA2243BasicDefaultResultAt(4, 2, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(6, 35, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid"), CA2243BasicDefaultResultAt(9, 35, "GuidAttribute", "GuidAttribute.GUID", "bad-guid", "Guid")); } [Fact] public async Task CA2243_NoDiagnostics_BasicAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Public NotInheritable Class GoodAttributeStringLiterals Private NotInheritable Class MyLiteralsAttribute Inherits Attribute Private m_url As String Private m_version As String Private m_guid As String Private m_notAVersion As Integer Public Sub New() End Sub Public Sub New(url As String) m_url = url End Sub Public Sub New(url As String, dummy1 As Integer, thisIsAVersion As String, notAVersion As Integer) m_url = url m_version = thisIsAVersion m_notAVersion = notAVersion + dummy1 End Sub Public Property Url() As String Get Return m_url End Get Set m_url = Value End Set End Property Public Property Version() As String Get Return m_version End Get Set m_version = Value End Set End Property Public Property GUID() As String Get Return m_guid End Get Set m_guid = Value End Set End Property Public Property NotAVersion() As Integer Get Return m_notAVersion End Get Set m_notAVersion = Value End Set End Property End Class <MyLiterals(""good/relative/url"", GUID:=""8fcd093bc1058acf8fcd093bc1058acf"", Version:=""1.4.325.12"")> Private x As Integer Public Sub New() DoNothing(1) End Sub <MyLiterals(GUID:=""{8fcd093b-c105-8acf-8fcd-093bc1058acf}"", Url:=""http://good/absolute/url.htm"")> Private Sub DoNothing(<MyLiterals(""goodurl/"", NotAVersion:=12)> y As Integer) If x > 0 Then DoNothing2(y) End If End Sub <MyLiterals(""http://good/url"", 5, ""1.0.50823.98"", 5)> Private Sub DoNothing2(y As Integer) Me.x = y End Sub End Class <AttributeUsage(AttributeTargets.All, AllowMultiple:=False)> Public NotInheritable Class UriTemplateAttribute Inherits Attribute Private m_uriTemplate As String Public Sub New() End Sub Public Sub New(uriTemplate As String) m_uriTemplate = uriTemplate End Sub Public Property UriTemplate() As String Get Return m_uriTemplate End Get Set m_uriTemplate = Value End Set End Property End Class Public NotInheritable Class ClassWithExceptionForUri Private Sub New() End Sub <UriTemplate(UriTemplate:=""{0}"")> Public Shared Sub MethodWithInvalidUriNamedArgumentThatShouldBeIgnored() End Sub <UriTemplate(UriTemplate:="""")> Public Shared Sub MethodWithEmptyUriNamedArgumentThatShouldBeIgnored() End Sub <UriTemplate(""{0}"")> Public Shared Sub MethodWithInvalidUriRequiredArgumentThatShouldBeIgnored() End Sub <UriTemplate("""")> Public Shared Sub MethodWithEmptyUriRequiredArgumentThatShouldBeIgnored() End Sub End Class "); } [Fact, WorkItem(3635, "https://github.com/dotnet/roslyn-analyzers/issues/3635")] public async Task ObsoleteAttributeUrlFormat_NoDiagnosticAsync() { await VerifyCS.VerifyAnalyzerAsync(@" namespace System { [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public class ObsoleteAttribute : Attribute { public string UrlFormat { get; set; } } } namespace Something { using System; public class C { [Obsolete(UrlFormat = """")] public void M1() {} [Obsolete(UrlFormat = ""{0}"")] public void M2() {} } }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Namespace System <AttributeUsage(AttributeTargets.All, AllowMultiple:=False)> Public Class ObsoleteAttribute Inherits Attribute Public Property UrlFormat As String End Class End Namespace Namespace Something Public Class C <Obsolete(UrlFormat:="""")> Public Sub M1() End Sub <Obsolete(UrlFormat:=""{0}"")> Public Sub M2() End Sub End Class End Namespace"); } private DiagnosticResult CA2243CSharpDefaultResultAt(int line, int column, params string[] arguments) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(AttributeStringLiteralsShouldParseCorrectlyAnalyzer.DefaultRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(arguments); private DiagnosticResult CA2243BasicDefaultResultAt(int line, int column, params string[] arguments) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(AttributeStringLiteralsShouldParseCorrectlyAnalyzer.DefaultRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(arguments); private DiagnosticResult CA2243CSharpEmptyResultAt(int line, int column, params string[] arguments) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(AttributeStringLiteralsShouldParseCorrectlyAnalyzer.EmptyRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(arguments); private DiagnosticResult CA2243BasicEmptyResultAt(int line, int column, params string[] arguments) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(AttributeStringLiteralsShouldParseCorrectlyAnalyzer.EmptyRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(arguments); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using PylonC.NETSupportLibrary; using PylonC.NET; namespace PylonC.NETSupportLibrary { /* Displays a slider bar, the name of the node, minimum, maximum, and current value. */ public partial class SliderUserControl : UserControl { private string name = "ValueName"; /* The name of the node. */ private ImageProvider m_imageProvider = null; /* The image provider providing the node handle and status events. */ private NODE_HANDLE m_hNode = new NODE_HANDLE(); /* The handle of the node. */ private NODE_CALLBACK_HANDLE m_hCallbackHandle = new NODE_CALLBACK_HANDLE(); /* The handle of the node callback. */ private NodeCallbackHandler m_nodeCallbackHandler = new NodeCallbackHandler(); /* The callback handler. */ /* Used for connecting an image provider providing the node handle and status events. */ public ImageProvider MyImageProvider { set { m_imageProvider = value; /* Image provider has been connected. */ if (m_imageProvider != null) { /* Register for the events of the image provider needed for proper operation. */ m_imageProvider.DeviceOpenedEvent += new ImageProvider.DeviceOpenedEventHandler(DeviceOpenedEventHandler); m_imageProvider.DeviceClosingEvent += new ImageProvider.DeviceClosingEventHandler(DeviceClosingEventHandler); /* Update the control values. */ UpdateValues(); } else /* Image provider has been disconnected. */ { Reset(); } } } [Description("The GenICam node name representing an integer, e.g. GainRaw. The pylon Viewer tool feature tree can be used to get the name and the type of a node.")] public string NodeName { get { return name; } set { name = value; labelName.Text = name + ":"; } } /* A device has been opened. Update the control. */ private void DeviceOpenedEventHandler() { if (InvokeRequired) { /* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */ BeginInvoke(new ImageProvider.DeviceOpenedEventHandler(DeviceOpenedEventHandler)); return; } try { /* Get the node. */ m_hNode = m_imageProvider.GetNodeFromDevice(name); /* Features, like 'Gain', are named according to the GenICam Standard Feature Naming Convention (SFNC). The SFNC defines a common set of features, their behavior, and the related parameter names. This ensures the interoperability of cameras from different camera vendors. Some cameras, e.g. cameras compliant to the USB3 Vision standard, use a later SFNC version than previous Basler GigE and Firewire cameras. Accordingly, the behavior of these cameras and some parameters names will be different. */ if (!m_hNode.IsValid /* No node has been found using the provided name. */ && (name == "GainRaw" || name == "ExposureTimeRaw")) /* This means probably that the camera is compliant to a later SFNC version. */ { /* Check to see if a compatible node exists. The SFNC 2.0, implemented by Basler USB Cameras for instance, defines Gain and ExposureTime as features of type Float.*/ if (name=="GainRaw" ) { m_hNode = m_imageProvider.GetNodeFromDevice("Gain"); } else if (name == "ExposureTimeRaw") { m_hNode = m_imageProvider.GetNodeFromDevice("ExposureTime"); } /* Update the displayed name. */ labelName.Text = GenApi.NodeGetDisplayName(m_hNode) + ":"; /* The underlying integer representation of Gain and ExposureTime can be accessed using the so called alias node. The alias is another representation of the original parameter. Since this slider control can only be used with Integer nodes we have to use the alias node here to display and modify Gain and ExposureTime. */ m_hNode = GenApi.NodeGetAlias(m_hNode); /* Register for changes. */ m_hCallbackHandle = GenApi.NodeRegisterCallback(m_hNode, m_nodeCallbackHandler); } else { /* Update the displayed name. */ labelName.Text = GenApi.NodeGetDisplayName(m_hNode) + ":"; /* Register for changes. */ m_hCallbackHandle = GenApi.NodeRegisterCallback(m_hNode, m_nodeCallbackHandler); } /* Update the control values. */ UpdateValues(); } catch { /* If errors occurred disable the control. */ Reset(); } } /* The device has been closed. Update the control. */ private void DeviceClosingEventHandler() { if (InvokeRequired) { /* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */ BeginInvoke(new ImageProvider.DeviceRemovedEventHandler(DeviceClosingEventHandler)); return; } Reset(); } /* The node state has changed. Update the control. */ private void NodeCallbackEventHandler(NODE_HANDLE handle) { if (InvokeRequired) { /* If called from a different thread, we must use the Invoke method to marshal the call to the proper thread. */ BeginInvoke(new NodeCallbackHandler.NodeCallback(NodeCallbackEventHandler), handle); return; } if (handle.Equals(m_hNode)) { /* Update the control values. */ UpdateValues(); } } /* Deactivate the control and deregister the callback. */ private void Reset() { if (m_hNode.IsValid && m_hCallbackHandle.IsValid) { try { GenApi.NodeDeregisterCallback(m_hNode, m_hCallbackHandle); } catch { /* Ignore. The control is about to be disabled. */ } } m_hNode.SetInvalid(); m_hCallbackHandle.SetInvalid(); slider.Enabled = false; labelMin.Enabled = false; labelMax.Enabled = false; labelName.Enabled = false; labelCurrentValue.Enabled = false; } /* Get the current values from the node and display them. */ private void UpdateValues() { try { if (m_hNode.IsValid) { if (GenApi.NodeGetType(m_hNode) == EGenApiNodeType.IntegerNode) /* Check if proper node type. */ { /* Get the values. */ bool writable = GenApi.NodeIsWritable(m_hNode); int min = checked((int)GenApi.IntegerGetMin(m_hNode)); int max = checked((int)GenApi.IntegerGetMax(m_hNode)); int val = checked((int)GenApi.IntegerGetValue(m_hNode)); int inc = checked((int)GenApi.IntegerGetInc(m_hNode)); /* Update the slider. */ slider.Minimum = min; slider.Maximum = max; slider.Value = val; slider.SmallChange = inc; slider.TickFrequency = (max - min + 5) / 10; /* Update the values. */ labelMin.Text = "" + min; labelMax.Text = "" + max; labelCurrentValue.Text = "" + val; /* Update accessibility. */ slider.Enabled = writable; labelMin.Enabled = writable; labelMax.Enabled = writable; labelName.Enabled = writable; labelCurrentValue.Enabled = writable; return; } } } catch { /* If errors occurred disable the control. */ } Reset(); } /* Set up the initial state. */ public SliderUserControl() { InitializeComponent(); m_nodeCallbackHandler.CallbackEvent += new NodeCallbackHandler.NodeCallback(NodeCallbackEventHandler); Reset(); } /* Handle slider position changes. */ private void slider_Scroll(object sender, EventArgs e) { if (m_hNode.IsValid) { try { if (GenApi.NodeIsWritable(m_hNode)) { /* Correct the increment of the new value. */ int value = slider.Value - ((slider.Value - slider.Minimum) % slider.SmallChange); /* Set the value. */ GenApi.IntegerSetValue(m_hNode, value); } } catch { /* Ignore any errors here. */ } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Linq; using Xunit; namespace System.IO.FileSystem.Tests { public class Directory_CreateDirectory : FileSystemTest { #region Utilities public virtual DirectoryInfo Create(string path) { return Directory.CreateDirectory(path); } #endregion #region UniversalTests [Fact] public void NullAsPath_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => Create(null)); } [Fact] public void EmptyAsPath_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Create(string.Empty)); } [Fact] public void PathWithInvalidCharactersAsPath_ThrowsArgumentException() { var paths = IOInputs.GetPathsWithInvalidCharacters(); Assert.All(paths, (path) => { Assert.Throws<ArgumentException>(() => Create(path)); }); } [Fact] public void PathAlreadyExistsAsFile() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.Throws<IOException>(() => Create(path)); Assert.Throws<IOException>(() => Create(IOServices.AddTrailingSlashIfNeeded(path))); Assert.Throws<IOException>(() => Create(IOServices.RemoveTrailingSlash(path))); } [Theory] [InlineData(FileAttributes.Hidden)] [InlineData(FileAttributes.ReadOnly)] [InlineData(FileAttributes.Normal)] public void PathAlreadyExistsAsDirectory(FileAttributes attributes) { DirectoryInfo testDir = Create(GetTestFilePath()); testDir.Attributes = attributes; Assert.Equal(testDir.FullName, Create(testDir.FullName).FullName); } [Fact] public void RootPath() { string dirName = Path.GetPathRoot(Directory.GetCurrentDirectory()); DirectoryInfo dir = Create(dirName); Assert.Equal(dir.FullName, dirName); } [Fact] public void DotIsCurrentDirectory() { string path = GetTestFilePath(); DirectoryInfo result = Create(Path.Combine(path, ".")); Assert.Equal(IOServices.RemoveTrailingSlash(path), result.FullName); result = Create(Path.Combine(path, ".") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(path), result.FullName); } [Fact] public void CreateCurrentDirectory() { DirectoryInfo result = Create(Directory.GetCurrentDirectory()); Assert.Equal(Directory.GetCurrentDirectory(), result.FullName); } [Fact] public void DotDotIsParentDirectory() { DirectoryInfo result = Create(Path.Combine(GetTestFilePath(), "..")); Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName); result = Create(Path.Combine(GetTestFilePath(), "..") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName); } [Fact] public void ValidPathWithTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetValidPathComponentNames(); Assert.All(components, (component) => { string path = IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component)); DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(result.Exists); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void ValidExtendedPathWithTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetValidPathComponentNames(); Assert.All(components, (component) => { string path = @"\\?\" + IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component)); DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(result.Exists); }); } [Fact] public void ValidPathWithoutTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetValidPathComponentNames(); Assert.All(components, (component) => { string path = testDir.FullName + Path.DirectorySeparatorChar + component; DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] public void ValidPathWithMultipleSubdirectories() { string dirName = Path.Combine(GetTestFilePath(), "Test", "Test", "Test"); DirectoryInfo dir = Create(dirName); Assert.Equal(dir.FullName, dirName); } [Fact] public void AllowedSymbols() { string dirName = Path.Combine(TestDirectory, Path.GetRandomFileName() + "!@#$%^&"); DirectoryInfo dir = Create(dirName); Assert.Equal(dir.FullName, dirName); } [Fact] public void DirectoryEqualToMaxDirectory_CanBeCreated() { DirectoryInfo testDir = Create(GetTestFilePath()); PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, IOInputs.MaxComponent); Assert.All(path.SubPaths, (subpath) => { DirectoryInfo result = Create(subpath); Assert.Equal(subpath, result.FullName); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] public void DirectoryEqualToMaxDirectory_CanBeCreatedAllAtOnce() { DirectoryInfo testDir = Create(GetTestFilePath()); PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, maxComponent: 10); DirectoryInfo result = Create(path.FullPath); Assert.Equal(path.FullPath, result.FullName); Assert.True(Directory.Exists(result.FullName)); } [Fact] public void DirectoryWithComponentLongerThanMaxComponentAsPath_ThrowsPathTooLongException() { // While paths themselves can be up to 260 characters including trailing null, file systems // limit each components of the path to a total of 255 characters. var paths = IOInputs.GetPathsWithComponentLongerThanMaxComponent(); Assert.All(paths, (path) => { Assert.Throws<PathTooLongException>(() => Create(path)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void DirectoryLongerThanMaxPathAsPath_ThrowsPathTooLongException() { var paths = IOInputs.GetPathsLongerThanMaxPath(); Assert.All(paths, (path) => { Assert.Throws<PathTooLongException>(() => Create(path)); }); } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(PlatformID.Windows)] public void DirectoryLongerThanMaxDirectoryAsPath_ThrowsPathTooLongException() { var paths = IOInputs.GetPathsLongerThanMaxDirectory(); Assert.All(paths, (path) => { Assert.Throws<PathTooLongException>(() => Create(path)); }); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] [ActiveIssue(645)] public void UnixPathLongerThan256_Allowed() { DirectoryInfo testDir = Create(GetTestFilePath()); PathInfo path = IOServices.GetPath(testDir.FullName, 257, IOInputs.MaxComponent); DirectoryInfo result = Create(path.FullPath); Assert.Equal(path.FullPath, result.FullName); Assert.True(Directory.Exists(result.FullName)); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixPathLongerThan256_Throws() { DirectoryInfo testDir = Create(GetTestFilePath()); PathInfo path = IOServices.GetPath(testDir.FullName, 257, IOInputs.MaxComponent); Assert.Throws<PathTooLongException>(() => Create(path.FullPath)); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsWhiteSpaceAsPath_ThrowsArgumentException() { var paths = IOInputs.GetWhiteSpace(); Assert.All(paths, (path) => { Assert.Throws<ArgumentException>(() => Create(path)); }); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixWhiteSpaceAsPath_Allowed() { var paths = IOInputs.GetWhiteSpace(); Assert.All(paths, (path) => { Create(Path.Combine(TestDirectory, path)); Assert.True(Directory.Exists(Path.Combine(TestDirectory, path))); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsTrailingWhiteSpace() { // Windows will remove all nonsignificant whitespace in a path DirectoryInfo testDir = Create(GetTestFilePath()); var components = IOInputs.GetWhiteSpace(); Assert.All(components, (component) => { string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component; DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsExtendedSyntaxWhiteSpace() { var paths = IOInputs.GetSimpleWhiteSpace(); using (TemporaryDirectory directory = new TemporaryDirectory()) { foreach (var path in paths) { string extendedPath = Path.Combine(@"\\?\" + directory.Path, path); Directory.CreateDirectory(extendedPath); Assert.True(Directory.Exists(extendedPath)); } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixNonSignificantTrailingWhiteSpace() { // Unix treats trailing/prename whitespace as significant and a part of the name. DirectoryInfo testDir = Create(GetTestFilePath()); var components = IOInputs.GetWhiteSpace(); Assert.All(components, (component) => { string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component; DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // alternate data streams public void PathWithAlternateDataStreams_ThrowsNotSupportedException() { var paths = IOInputs.GetPathsWithAlternativeDataStreams(); Assert.All(paths, (path) => { Assert.Throws<NotSupportedException>(() => Create(path)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // device name prefixes public void PathWithReservedDeviceNameAsPath_ThrowsDirectoryNotFoundException() { // Throws DirectoryNotFoundException, when the behavior really should be an invalid path var paths = IOInputs.GetPathsWithReservedDeviceNames(); Assert.All(paths, (path) => { Assert.Throws<DirectoryNotFoundException>(() => Create(path)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // UNC shares public void UncPathWithoutShareNameAsPath_ThrowsArgumentException() { var paths = IOInputs.GetUncPathsWithoutShareName(); foreach (var path in paths) { Assert.Throws<ArgumentException>(() => Create(path)); } } [Fact] [PlatformSpecific(PlatformID.Windows)] // drive labels public void CDriveCase() { DirectoryInfo dir = Create("c:\\"); DirectoryInfo dir2 = Create("C:\\"); Assert.NotEqual(dir.FullName, dir2.FullName); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void DriveLetter_Windows() { // On Windows, DirectoryInfo will replace "<DriveLetter>:" with "." var driveLetter = Create(Directory.GetCurrentDirectory()[0] + ":"); var current = Create("."); Assert.Equal(current.Name, driveLetter.Name); Assert.Equal(current.FullName, driveLetter.FullName); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] [ActiveIssue(2459)] public void DriveLetter_Unix() { // On Unix, there's no special casing for drive letters, which are valid file names var driveLetter = Create("C:"); var current = Create("."); Assert.Equal("C:", driveLetter.Name); Assert.Equal(Path.Combine(current.FullName, "C:"), driveLetter.FullName); Directory.Delete("C:"); } [Fact] [PlatformSpecific(PlatformID.Windows)] // testing drive labels public void NonExistentDriveAsPath_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => { Create(IOServices.GetNonExistentDrive()); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // testing drive labels public void SubdirectoryOnNonExistentDriveAsPath_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => { Create(Path.Combine(IOServices.GetNonExistentDrive(), "Subdirectory")); }); } [Fact] [ActiveIssue(1221)] [PlatformSpecific(PlatformID.Windows)] // testing drive labels public void NotReadyDriveAsPath_ThrowsDirectoryNotFoundException() { // Behavior is suspect, should really have thrown IOException similar to the SubDirectory case var drive = IOServices.GetNotReadyDrive(); if (drive == null) { Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted."); return; } Assert.Throws<DirectoryNotFoundException>(() => { Create(drive); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // testing drive labels [ActiveIssue(1221)] public void SubdirectoryOnNotReadyDriveAsPath_ThrowsIOException() { var drive = IOServices.GetNotReadyDrive(); if (drive == null) { Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted."); return; } // 'Device is not ready' Assert.Throws<IOException>(() => { Create(Path.Combine(drive, "Subdirectory")); }); } #if !TEST_WINRT // Cannot set current directory to root from appcontainer with it's default ACL /* [Fact] [ActiveIssue(1220)] // SetCurrentDirectory public void DotDotAsPath_WhenCurrentDirectoryIsRoot_DoesNotThrow() { string root = Path.GetPathRoot(Directory.GetCurrentDirectory()); using (CurrentDirectoryContext context = new CurrentDirectoryContext(root)) { DirectoryInfo result = Create(".."); Assert.True(Directory.Exists(result.FullName)); Assert.Equal(root, result.FullName); } } */ #endif #endregion } }
// // ObjTableVC.cs // // Author: // Alexander Matsibarov (macasun) <amatsibarov@gmail.com> // // Copyright (c) 2013 Alexander Matsibarov // // 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 3 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, see <http://www.gnu.org/licenses/>. // using System; using System.Drawing; using System.Collections.Generic; using MonoTouch.Foundation; using MonoTouch.UIKit; using FileExplorerMobile.Core; using FileExplorerMobile.Core.Data.Objects; using FileExplorerMobile.Core.Data.Enums; namespace FileExplorerMobile.mTouch.Views { public class FileEntryTableVC : UITableViewController { #region Fields /// <summary> /// The opened file entry. /// </summary> private FileEntry _OpenedFileEntry; /// <summary> /// The set editing mode button. /// </summary> private UIBarButtonItem _SetEditingModeButton; #endregion #region Initialization public FileEntryTableVC(FileEntry fileEntry) : base(null, null) { _OpenedFileEntry = fileEntry; } #endregion #region UI Logic public override void ViewDidLoad() { base.ViewDidLoad(); Title = _OpenedFileEntry == null ? "Root" : _OpenedFileEntry.Name; _SetEditingModeButton = new UIBarButtonItem(UIImage.FromFile("Content/Images/NavBar/edit20.png"), UIBarButtonItemStyle.Plain, (s, e) => _SetEditingMode()); NavigationItem.RightBarButtonItems = new UIBarButtonItem[] { _SetEditingModeButton }; var children = MgrAccessor.FileEntryMgr.GetChildren(_OpenedFileEntry); TableView.Source = new TableSource(this, children); TableView.RowHeight = 64; } public override bool ShouldAutorotateToInterfaceOrientation(UIInterfaceOrientation toInterfaceOrientation) { return true; } #endregion #region Logic /// <summary> /// Deletes the file entry. /// </summary> private void _SetEditingMode() { bool isEditingMode = _SetEditingModeButton.Style == UIBarButtonItemStyle.Done; if (!isEditingMode) { _SetEditingModeButton.Style = UIBarButtonItemStyle.Done; } else { _SetEditingModeButton.Style = UIBarButtonItemStyle.Plain; } isEditingMode = !isEditingMode; TableView.SetEditing(isEditingMode, true); } #endregion #region TableSource private class TableSource : UITableViewSource { #region Fields /// <summary> /// The cell identifier for the folder. /// </summary> private const string FolderCellIdentifier = "FolderCellIdentifier"; /// <summary> /// The cell identifier for the file. /// </summary> private const string FileCellIdentifier = "FileCellIdentifier"; /// <summary> /// The table view controller. /// </summary> private FileEntryTableVC _Controller; /// <summary> /// The file entries. /// </summary> private List<FileEntry> _FileEntries; #endregion #region Initialization /// <summary> /// Working constructor. /// </summary> public TableSource(FileEntryTableVC controller, List<FileEntry> fileEntries) { _Controller = controller; _FileEntries = fileEntries; } #endregion #region Logic /// <summary> /// Opens the file entry. /// </summary> private void _OpenFileEntry(UITableView tableView, NSIndexPath indexPath) { var fileEntry = _FileEntries[indexPath.Row]; if (fileEntry.FeType == FileEntryTypes.Folder) { var tableVC = new FileEntryTableVC(fileEntry); _Controller.NavigationController.PushViewController(tableVC, true); } } /// <summary> /// Deletes the file entry. /// </summary> private void _DeleteFileEntry(UITableView tableView, NSIndexPath indexPath) { var fileEntry = _FileEntries[indexPath.Row]; if (MgrAccessor.FileEntryMgr.Delete(fileEntry)) { _FileEntries.Remove(fileEntry); tableView.DeleteRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); } } #endregion #region UITableViewSource public override UITableViewCellEditingStyle EditingStyleForRow(UITableView tableView, NSIndexPath indexPath) { return UITableViewCellEditingStyle.Delete; } public override void CommitEditingStyle(UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) { _DeleteFileEntry(tableView, indexPath); } public override string TitleForDeleteConfirmation(UITableView tableView, NSIndexPath indexPath) { return "Delete"; } public override int RowsInSection(UITableView tableview, int section) { return _FileEntries.Count; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { var fileEntry = _FileEntries[indexPath.Row]; var cellIdentifier = fileEntry.FeType == FileEntryTypes.Folder ? FolderCellIdentifier : FileCellIdentifier; var cell = tableView.DequeueReusableCell(cellIdentifier); if (cell == null) { cell = new UITableViewCell(UITableViewCellStyle.Subtitle, cellIdentifier); } cell.TextLabel.Text = fileEntry.Name; if (fileEntry.FeType != FileEntryTypes.Folder) { cell.DetailTextLabel.Text = string.Format("Size: {0}b", fileEntry.Size); } else { cell.Accessory = UITableViewCellAccessory.DetailDisclosureButton; } cell.ImageView.Image = MgrAccessor.CommonUtils.GetTypeImage(fileEntry.FeType); return cell; } public override void AccessoryButtonTapped(UITableView tableView, NSIndexPath indexPath) { _OpenFileEntry(tableView, indexPath); } #endregion } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Linq.Expressions.Interpreter { internal abstract class EqualInstruction : Instruction { // Perf: EqualityComparer<T> but is 3/2 to 2 times slower. private static Instruction s_reference, s_boolean, s_SByte, s_int16, s_char, s_int32, s_int64, s_byte, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; private static Instruction s_referenceLiftedToNull, s_booleanLiftedToNull, s_SByteLiftedToNull, s_int16LiftedToNull, s_charLiftedToNull, s_int32LiftedToNull, s_int64LiftedToNull, s_byteLiftedToNull, s_UInt16LiftedToNull, s_UInt32LiftedToNull, s_UInt64LiftedToNull, s_singleLiftedToNull, s_doubleLiftedToNull; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "Equal"; } } private EqualInstruction() { } internal sealed class EqualBoolean : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.False); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Boolean)left) == ((Boolean)right))); } return +1; } } internal sealed class EqualSByte : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.False); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((SByte)left) == ((SByte)right))); } return +1; } } internal sealed class EqualInt16 : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.False); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int16)left) == ((Int16)right))); } return +1; } } internal sealed class EqualChar : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.False); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Char)left) == ((Char)right))); } return +1; } } internal sealed class EqualInt32 : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.False); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int32)left) == ((Int32)right))); } return +1; } } internal sealed class EqualInt64 : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.False); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int64)left) == ((Int64)right))); } return +1; } } internal sealed class EqualByte : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.False); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Byte)left) == ((Byte)right))); } return +1; } } internal sealed class EqualUInt16 : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.False); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt16)left) == ((UInt16)right))); } return +1; } } internal sealed class EqualUInt32 : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.False); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt32)left) == ((UInt32)right))); } return +1; } } internal sealed class EqualUInt64 : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.False); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt64)left) == ((UInt64)right))); } return +1; } } internal sealed class EqualSingle : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.False); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Single)left) == ((Single)right))); } return +1; } } internal sealed class EqualDouble : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(right == null)); } else if (right == null) { frame.Push(ScriptingRuntimeHelpers.False); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Double)left) == ((Double)right))); } return +1; } } internal sealed class EqualReference : EqualInstruction { public override int Run(InterpretedFrame frame) { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(frame.Pop() == frame.Pop())); return +1; } } internal sealed class EqualBooleanLiftedToNull : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Boolean)left) == ((Boolean)right))); } return +1; } } internal sealed class EqualSByteLiftedToNull : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((SByte)left) == ((SByte)right))); } return +1; } } internal sealed class EqualInt16LiftedToNull : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int16)left) == ((Int16)right))); } return +1; } } internal sealed class EqualCharLiftedToNull : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Char)left) == ((Char)right))); } return +1; } } internal sealed class EqualInt32LiftedToNull : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int32)left) == ((Int32)right))); } return +1; } } internal sealed class EqualInt64LiftedToNull : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Int64)left) == ((Int64)right))); } return +1; } } internal sealed class EqualByteLiftedToNull : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Byte)left) == ((Byte)right))); } return +1; } } internal sealed class EqualUInt16LiftedToNull : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt16)left) == ((UInt16)right))); } return +1; } } internal sealed class EqualUInt32LiftedToNull : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt32)left) == ((UInt32)right))); } return +1; } } internal sealed class EqualUInt64LiftedToNull : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((UInt64)left) == ((UInt64)right))); } return +1; } } internal sealed class EqualSingleLiftedToNull : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Single)left) == ((Single)right))); } return +1; } } internal sealed class EqualDoubleLiftedToNull : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(((Double)left) == ((Double)right))); } return +1; } } internal sealed class EqualReferenceLiftedToNull : EqualInstruction { public override int Run(InterpretedFrame frame) { var right = frame.Pop(); var left = frame.Pop(); if (left == null || right == null) { frame.Push(null); } else { frame.Push(ScriptingRuntimeHelpers.BooleanToObject(left == right)); } return +1; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] public static Instruction Create(Type type, bool liftedToNull) { // Boxed enums can be unboxed as their underlying types: if (liftedToNull) { switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(type.GetTypeInfo().IsEnum ? Enum.GetUnderlyingType(type) : TypeUtils.GetNonNullableType(type))) { case TypeCode.Boolean: return s_booleanLiftedToNull ?? (s_booleanLiftedToNull = new EqualBooleanLiftedToNull()); case TypeCode.SByte: return s_SByteLiftedToNull ?? (s_SByteLiftedToNull = new EqualSByteLiftedToNull()); case TypeCode.Byte: return s_byteLiftedToNull ?? (s_byteLiftedToNull = new EqualByteLiftedToNull()); case TypeCode.Char: return s_charLiftedToNull ?? (s_charLiftedToNull = new EqualCharLiftedToNull()); case TypeCode.Int16: return s_int16LiftedToNull ?? (s_int16LiftedToNull = new EqualInt16LiftedToNull()); case TypeCode.Int32: return s_int32LiftedToNull ?? (s_int32LiftedToNull = new EqualInt32LiftedToNull()); case TypeCode.Int64: return s_int64LiftedToNull ?? (s_int64LiftedToNull = new EqualInt64LiftedToNull()); case TypeCode.UInt16: return s_UInt16LiftedToNull ?? (s_UInt16LiftedToNull = new EqualUInt16LiftedToNull()); case TypeCode.UInt32: return s_UInt32LiftedToNull ?? (s_UInt32LiftedToNull = new EqualUInt32LiftedToNull()); case TypeCode.UInt64: return s_UInt64LiftedToNull ?? (s_UInt64LiftedToNull = new EqualUInt64LiftedToNull()); case TypeCode.Single: return s_singleLiftedToNull ?? (s_singleLiftedToNull = new EqualSingleLiftedToNull()); case TypeCode.Double: return s_doubleLiftedToNull ?? (s_doubleLiftedToNull = new EqualDoubleLiftedToNull()); case TypeCode.String: case TypeCode.Object: if (!type.GetTypeInfo().IsValueType) { return s_referenceLiftedToNull ?? (s_referenceLiftedToNull = new EqualReferenceLiftedToNull()); } // TODO: Nullable<T> throw Error.ExpressionNotSupportedForNullableType("Equal", type); default: throw Error.ExpressionNotSupportedForType("Equal", type); } } else { switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(type.GetTypeInfo().IsEnum ? Enum.GetUnderlyingType(type) : TypeUtils.GetNonNullableType(type))) { case TypeCode.Boolean: return s_boolean ?? (s_boolean = new EqualBoolean()); case TypeCode.SByte: return s_SByte ?? (s_SByte = new EqualSByte()); case TypeCode.Byte: return s_byte ?? (s_byte = new EqualByte()); case TypeCode.Char: return s_char ?? (s_char = new EqualChar()); case TypeCode.Int16: return s_int16 ?? (s_int16 = new EqualInt16()); case TypeCode.Int32: return s_int32 ?? (s_int32 = new EqualInt32()); case TypeCode.Int64: return s_int64 ?? (s_int64 = new EqualInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new EqualUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new EqualUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new EqualUInt64()); case TypeCode.Single: return s_single ?? (s_single = new EqualSingle()); case TypeCode.Double: return s_double ?? (s_double = new EqualDouble()); case TypeCode.String: case TypeCode.Object: if (!type.GetTypeInfo().IsValueType) { return s_reference ?? (s_reference = new EqualReference()); } // TODO: Nullable<T> throw Error.ExpressionNotSupportedForNullableType("Equal", type); default: throw Error.ExpressionNotSupportedForType("Equal", type); } } } public override string ToString() { return "Equal()"; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore; using osu.Framework.Bindables; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Database; using osu.Game.IO.Archives; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Rulesets; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring.Legacy; namespace osu.Game.Scoring { public class ScoreManager : DownloadableArchiveModelManager<ScoreInfo, ScoreFileInfo> { public override IEnumerable<string> HandledExtensions => new[] { ".osr" }; protected override string[] HashableFileTypes => new[] { ".osr" }; protected override string ImportFromStablePath => Path.Combine("Data", "r"); private readonly RulesetStore rulesets; private readonly Func<BeatmapManager> beatmaps; [CanBeNull] private readonly Func<BeatmapDifficultyCache> difficulties; [CanBeNull] private readonly OsuConfigManager configManager; public ScoreManager(RulesetStore rulesets, Func<BeatmapManager> beatmaps, Storage storage, IAPIProvider api, IDatabaseContextFactory contextFactory, IIpcHost importHost = null, Func<BeatmapDifficultyCache> difficulties = null, OsuConfigManager configManager = null) : base(storage, contextFactory, api, new ScoreStore(contextFactory, storage), importHost) { this.rulesets = rulesets; this.beatmaps = beatmaps; this.difficulties = difficulties; this.configManager = configManager; } protected override ScoreInfo CreateModel(ArchiveReader archive) { if (archive == null) return null; using (var stream = archive.GetStream(archive.Filenames.First(f => f.EndsWith(".osr", StringComparison.OrdinalIgnoreCase)))) { try { return new DatabasedLegacyScoreDecoder(rulesets, beatmaps()).Parse(stream).ScoreInfo; } catch (LegacyScoreDecoder.BeatmapNotFoundException e) { Logger.Log(e.Message, LoggingTarget.Information, LogLevel.Error); return null; } } } protected override Task Populate(ScoreInfo model, ArchiveReader archive, CancellationToken cancellationToken = default) => Task.CompletedTask; protected override void ExportModelTo(ScoreInfo model, Stream outputStream) { var file = model.Files.SingleOrDefault(); if (file == null) return; using (var inputStream = Files.Storage.GetStream(file.FileInfo.StoragePath)) inputStream.CopyTo(outputStream); } protected override IEnumerable<string> GetStableImportPaths(Storage storage) => storage.GetFiles(ImportFromStablePath).Where(p => HandledExtensions.Any(ext => Path.GetExtension(p)?.Equals(ext, StringComparison.OrdinalIgnoreCase) ?? false)) .Select(path => storage.GetFullPath(path)); public Score GetScore(ScoreInfo score) => new LegacyDatabasedScore(score, rulesets, beatmaps(), Files.Store); public List<ScoreInfo> GetAllUsableScores() => ModelStore.ConsumableItems.Where(s => !s.DeletePending).ToList(); public IEnumerable<ScoreInfo> QueryScores(Expression<Func<ScoreInfo, bool>> query) => ModelStore.ConsumableItems.AsNoTracking().Where(query); public ScoreInfo Query(Expression<Func<ScoreInfo, bool>> query) => ModelStore.ConsumableItems.AsNoTracking().FirstOrDefault(query); protected override ArchiveDownloadRequest<ScoreInfo> CreateDownloadRequest(ScoreInfo score, bool minimiseDownload) => new DownloadReplayRequest(score); protected override bool CheckLocalAvailability(ScoreInfo model, IQueryable<ScoreInfo> items) => base.CheckLocalAvailability(model, items) || (model.OnlineScoreID != null && items.Any(i => i.OnlineScoreID == model.OnlineScoreID)); /// <summary> /// Retrieves a bindable that represents the total score of a <see cref="ScoreInfo"/>. /// </summary> /// <remarks> /// Responds to changes in the currently-selected <see cref="ScoringMode"/>. /// </remarks> /// <param name="score">The <see cref="ScoreInfo"/> to retrieve the bindable for.</param> /// <returns>The bindable containing the total score.</returns> public Bindable<long> GetBindableTotalScore(ScoreInfo score) { var bindable = new TotalScoreBindable(score, difficulties); configManager?.BindWith(OsuSetting.ScoreDisplayMode, bindable.ScoringMode); return bindable; } /// <summary> /// Retrieves a bindable that represents the formatted total score string of a <see cref="ScoreInfo"/>. /// </summary> /// <remarks> /// Responds to changes in the currently-selected <see cref="ScoringMode"/>. /// </remarks> /// <param name="score">The <see cref="ScoreInfo"/> to retrieve the bindable for.</param> /// <returns>The bindable containing the formatted total score string.</returns> public Bindable<string> GetBindableTotalScoreString(ScoreInfo score) => new TotalScoreStringBindable(GetBindableTotalScore(score)); /// <summary> /// Provides the total score of a <see cref="ScoreInfo"/>. Responds to changes in the currently-selected <see cref="ScoringMode"/>. /// </summary> private class TotalScoreBindable : Bindable<long> { public readonly Bindable<ScoringMode> ScoringMode = new Bindable<ScoringMode>(); private readonly ScoreInfo score; private readonly Func<BeatmapDifficultyCache> difficulties; /// <summary> /// Creates a new <see cref="TotalScoreBindable"/>. /// </summary> /// <param name="score">The <see cref="ScoreInfo"/> to provide the total score of.</param> /// <param name="difficulties">A function to retrieve the <see cref="BeatmapDifficultyCache"/>.</param> public TotalScoreBindable(ScoreInfo score, Func<BeatmapDifficultyCache> difficulties) { this.score = score; this.difficulties = difficulties; ScoringMode.BindValueChanged(onScoringModeChanged, true); } private IBindable<StarDifficulty?> difficultyBindable; private CancellationTokenSource difficultyCancellationSource; private void onScoringModeChanged(ValueChangedEvent<ScoringMode> mode) { difficultyCancellationSource?.Cancel(); difficultyCancellationSource = null; if (score.Beatmap == null) { Value = score.TotalScore; return; } int beatmapMaxCombo; double accuracy = score.Accuracy; if (score.IsLegacyScore) { if (score.RulesetID == 3) { // In osu!stable, a full-GREAT score has 100% accuracy in mania. Along with a full combo, the score becomes indistinguishable from a full-PERFECT score. // To get around this, recalculate accuracy based on the hit statistics. // Note: This cannot be applied universally to all legacy scores, as some rulesets (e.g. catch) group multiple judgements together. double maxBaseScore = score.Statistics.Select(kvp => kvp.Value).Sum() * Judgement.ToNumericResult(HitResult.Perfect); double baseScore = score.Statistics.Select(kvp => Judgement.ToNumericResult(kvp.Key) * kvp.Value).Sum(); if (maxBaseScore > 0) accuracy = baseScore / maxBaseScore; } // This score is guaranteed to be an osu!stable score. // The combo must be determined through either the beatmap's max combo value or the difficulty calculator, as lazer's scoring has changed and the score statistics cannot be used. if (score.Beatmap.MaxCombo == null) { if (score.Beatmap.ID == 0 || difficulties == null) { // We don't have enough information (max combo) to compute the score, so use the provided score. Value = score.TotalScore; return; } // We can compute the max combo locally after the async beatmap difficulty computation. difficultyBindable = difficulties().GetBindableDifficulty(score.Beatmap, score.Ruleset, score.Mods, (difficultyCancellationSource = new CancellationTokenSource()).Token); difficultyBindable.BindValueChanged(d => { if (d.NewValue is StarDifficulty diff) updateScore(diff.MaxCombo, accuracy); }, true); return; } beatmapMaxCombo = score.Beatmap.MaxCombo.Value; } else { // This is guaranteed to be a non-legacy score. // The combo must be determined through the score's statistics, as both the beatmap's max combo and the difficulty calculator will provide osu!stable combo values. beatmapMaxCombo = Enum.GetValues(typeof(HitResult)).OfType<HitResult>().Where(r => r.AffectsCombo()).Select(r => score.Statistics.GetValueOrDefault(r)).Sum(); } updateScore(beatmapMaxCombo, accuracy); } private void updateScore(int beatmapMaxCombo, double accuracy) { if (beatmapMaxCombo == 0) { Value = 0; return; } var ruleset = score.Ruleset.CreateInstance(); var scoreProcessor = ruleset.CreateScoreProcessor(); scoreProcessor.Mods.Value = score.Mods; Value = (long)Math.Round(scoreProcessor.GetScore(ScoringMode.Value, beatmapMaxCombo, accuracy, (double)score.MaxCombo / beatmapMaxCombo, score.Statistics)); } } /// <summary> /// Provides the total score of a <see cref="ScoreInfo"/> as a formatted string. Responds to changes in the currently-selected <see cref="ScoringMode"/>. /// </summary> private class TotalScoreStringBindable : Bindable<string> { // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable (need to hold a reference) private readonly IBindable<long> totalScore; public TotalScoreStringBindable(IBindable<long> totalScore) { this.totalScore = totalScore; this.totalScore.BindValueChanged(v => Value = v.NewValue.ToString("N0"), true); } } } }
/* * Vericred API * * Vericred's API allows you to search for Health Plans that a specific doctor accepts. ## Getting Started Visit our [Developer Portal](https://developers.vericred.com) to create an account. Once you have created an account, you can create one Application for Production and another for our Sandbox (select the appropriate Plan when you create the Application). ## SDKs Our API follows standard REST conventions, so you can use any HTTP client to integrate with us. You will likely find it easier to use one of our [autogenerated SDKs](https://github.com/vericred/?query=vericred-), which we make available for several common programming languages. ## Authentication To authenticate, pass the API Key you created in the Developer Portal as a `Vericred-Api-Key` header. `curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Versioning Vericred's API default to the latest version. However, if you need a specific version, you can request it with an `Accept-Version` header. The current version is `v3`. Previous versions are `v1` and `v2`. `curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Pagination Endpoints that accept `page` and `per_page` parameters are paginated. They expose four additional fields that contain data about your position in the response, namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988). For example, to display 5 results per page and view the second page of a `GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`. ## Sideloading When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s we sideload the associated data. In this example, we would provide an Array of `State`s and a `state_id` for each provider. This is done primarily to reduce the payload size since many of the `Provider`s will share a `State` ``` { providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }], states: [{ id: 1, code: 'NY' }] } ``` If you need the second level of the object graph, you can just match the corresponding id. ## Selecting specific data All endpoints allow you to specify which fields you would like to return. This allows you to limit the response to contain only the data you need. For example, let's take a request that returns the following JSON by default ``` { provider: { id: 1, name: 'John', phone: '1234567890', field_we_dont_care_about: 'value_we_dont_care_about' }, states: [{ id: 1, name: 'New York', code: 'NY', field_we_dont_care_about: 'value_we_dont_care_about' }] } ``` To limit our results to only return the fields we care about, we specify the `select` query string parameter for the corresponding fields in the JSON document. In this case, we want to select `name` and `phone` from the `provider` key, so we would add the parameters `select=provider.name,provider.phone`. We also want the `name` and `code` from the `states` key, so we would add the parameters `select=states.name,staes.code`. The id field of each document is always returned whether or not it is requested. Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code` The response would be ``` { provider: { id: 1, name: 'John', phone: '1234567890' }, states: [{ id: 1, name: 'New York', code: 'NY' }] } ``` ## Benefits summary format Benefit cost-share strings are formatted to capture: * Network tiers * Compound or conditional cost-share * Limits on the cost-share * Benefit-specific maximum out-of-pocket costs **Example #1** As an example, we would represent [this Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as: * **Hospital stay facility fees**: - Network Provider: `$400 copay/admit plus 20% coinsurance` - Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance` - Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible` * **Rehabilitation services:** - Network Provider: `20% coinsurance` - Out-of-Network Provider: `50% coinsurance` - Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.` - Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period` **Example #2** In [this other Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies. * **Specialty drugs:** - Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply` - Out-of-Network Provider `Not covered` - Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%` **BNF** Here's a description of the benefits summary string, represented as a context-free grammar: ``` <cost-share> ::= <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> <tier-limit> "/" <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> "|" <benefit-limit> <tier> ::= "In-Network:" | "In-Network-Tier-2:" | "Out-of-Network:" <opt-num-prefix> ::= "first" <num> <unit> | "" <unit> ::= "day(s)" | "visit(s)" | "exam(s)" | "item(s)" <value> ::= <ddct_moop> | <copay> | <coinsurance> | <compound> | "unknown" | "Not Applicable" <compound> ::= <copay> <deductible> "then" <coinsurance> <deductible> | <copay> <deductible> "then" <copay> <deductible> | <coinsurance> <deductible> "then" <coinsurance> <deductible> <copay> ::= "$" <num> <coinsurace> ::= <num> "%" <ddct_moop> ::= <copay> | "Included in Medical" | "Unlimited" <opt-per-unit> ::= "per day" | "per visit" | "per stay" | "" <deductible> ::= "before deductible" | "after deductible" | "" <tier-limit> ::= ", " <limit> | "" <benefit-limit> ::= <limit> | "" ``` * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace IO.Vericred.Model { /// <summary> /// RequestPlanFindApplicant /// </summary> [DataContract] public partial class RequestPlanFindApplicant : IEquatable<RequestPlanFindApplicant> { /// <summary> /// Initializes a new instance of the <see cref="RequestPlanFindApplicant" /> class. /// </summary> /// <param name="Age">Age of applicant to search for.</param> /// <param name="Child">Is this applicant a child?.</param> /// <param name="Smoker">Does this applicant smoke?.</param> public RequestPlanFindApplicant(int? Age = null, bool? Child = null, bool? Smoker = null) { this.Age = Age; this.Child = Child; this.Smoker = Smoker; } /// <summary> /// Age of applicant to search for /// </summary> /// <value>Age of applicant to search for</value> [DataMember(Name="age", EmitDefaultValue=false)] public int? Age { get; set; } /// <summary> /// Is this applicant a child? /// </summary> /// <value>Is this applicant a child?</value> [DataMember(Name="child", EmitDefaultValue=false)] public bool? Child { get; set; } /// <summary> /// Does this applicant smoke? /// </summary> /// <value>Does this applicant smoke?</value> [DataMember(Name="smoker", EmitDefaultValue=false)] public bool? Smoker { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class RequestPlanFindApplicant {\n"); sb.Append(" Age: ").Append(Age).Append("\n"); sb.Append(" Child: ").Append(Child).Append("\n"); sb.Append(" Smoker: ").Append(Smoker).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as RequestPlanFindApplicant); } /// <summary> /// Returns true if RequestPlanFindApplicant instances are equal /// </summary> /// <param name="other">Instance of RequestPlanFindApplicant to be compared</param> /// <returns>Boolean</returns> public bool Equals(RequestPlanFindApplicant other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Age == other.Age || this.Age != null && this.Age.Equals(other.Age) ) && ( this.Child == other.Child || this.Child != null && this.Child.Equals(other.Child) ) && ( this.Smoker == other.Smoker || this.Smoker != null && this.Smoker.Equals(other.Smoker) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Age != null) hash = hash * 59 + this.Age.GetHashCode(); if (this.Child != null) hash = hash * 59 + this.Child.GetHashCode(); if (this.Smoker != null) hash = hash * 59 + this.Smoker.GetHashCode(); return hash; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; 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] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class List<T> : IList<T>, IList, IReadOnlyList<T> { private const int DefaultCapacity = 4; private T[] _items; // Do not rename (binary serialization) private int _size; // Do not rename (binary serialization) private int _version; // Do not rename (binary serialization) 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) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); 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) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); if (collection is ICollection<T> c) { 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; 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 { return _items.Length; } set { if (value < _size) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity); } if (value != _items.Length) { if (value > 0) { T[] newItems = new T[value]; if (_size > 0) { Array.Copy(_items, 0, newItems, 0, _size); } _items = newItems; } else { _items = s_emptyArray; } } } } // Read-only property describing how many elements are in the List. public int Count => _size; bool IList.IsFixedSize => false; // Is this List read-only? bool ICollection<T>.IsReadOnly => false; bool IList.IsReadOnly => false; // Is this List synchronized (thread-safe)? bool ICollection.IsSynchronized => false; // Synchronization root for this object. object ICollection.SyncRoot => this; // 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) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return _items[index]; } set { if ((uint)index >= (uint)_size) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } _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)); // default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) } object? IList.this[int index] { get { return this[index]; } set { ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); try { this[index] = (T)value!; } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T)); } } } // 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. // [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T item) { _version++; T[] array = _items; int size = _size; if ((uint)size < (uint)array.Length) { _size = size + 1; array[size] = item; } else { AddWithResize(item); } } // Non-inline from List.Add to improve its code quality as uncommon path [MethodImpl(MethodImplOptions.NoInlining)] private void AddWithResize(T item) { int size = _size; EnsureCapacity(size + 1); _size = size + 1; _items[size] = item; } int IList.Add(object? item) { ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item); try { Add((T)item!); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T)); } 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) => InsertRange(_size, collection); public ReadOnlyCollection<T> AsReadOnly() => 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) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (count < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); return Array.BinarySearch<T>(_items, index, count, item, comparer); } public int BinarySearch(T item) => BinarySearch(0, Count, item, null); public int BinarySearch(T item, IComparer<T>? comparer) => BinarySearch(0, Count, item, comparer); // Clears the contents of List. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { _version++; if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { int size = _size; _size = 0; if (size > 0) { Array.Clear(_items, 0, size); // Clear the elements so that the gc can reclaim the references. } } else { _size = 0; } } // 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 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) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter); } 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 ICollection.CopyTo(Array array, int arrayIndex) { if ((array != null) && (array.Rank != 1)) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } try { // Array.Copy will check for NULL. Array.Copy(_items, 0, array!, arrayIndex, _size); } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } // 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) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } // 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) => FindIndex(match) != -1; [return: MaybeNull] public T Find(Predicate<T> match) { if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } for (int i = 0; i < _size; i++) { if (match!(_items[i])) { return _items[i]; } } return default!; } public List<T> FindAll(Predicate<T> match) { if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } 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) => FindIndex(0, _size, match); public int FindIndex(int startIndex, Predicate<T> match) => FindIndex(startIndex, _size - startIndex, match); public int FindIndex(int startIndex, int count, Predicate<T> match) { if ((uint)startIndex > (uint)_size) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (count < 0 || startIndex > _size - count) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) { if (match!(_items[i])) return i; } return -1; } [return: MaybeNull] public T FindLast(Predicate<T> match) { if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } for (int i = _size - 1; i >= 0; i--) { if (match!(_items[i])) { return _items[i]; } } return default!; } public int FindLastIndex(Predicate<T> match) => FindLastIndex(_size - 1, _size, match); public int FindLastIndex(int startIndex, Predicate<T> match) => FindLastIndex(startIndex, startIndex + 1, match); public int FindLastIndex(int startIndex, int count, Predicate<T> match) { if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } if (_size == 0) { // Special case for 0 length List if (startIndex != -1) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } } else { // Make sure we're not out of range if ((uint)startIndex >= (uint)_size) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_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) { ThrowHelper.ThrowCountArgumentOutOfRange_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) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } int version = _version; for (int i = 0; i < _size; i++) { if (version != _version) { break; } action!(_items[i]); } if (version != _version) ThrowHelper.ThrowInvalidOperationException_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() => new Enumerator(this); IEnumerator<T> IEnumerable<T>.GetEnumerator() => new Enumerator(this); IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this); public List<T> GetRange(int index, int count) { if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } 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) => Array.IndexOf(_items, item, 0, _size); int 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) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); 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) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); if (count < 0 || index > _size - count) ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); 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) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert); } 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 IList.Insert(int index, object? item) { ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item); try { Insert(index, (T)item!); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T)); } } // 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) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } if ((uint)index > (uint)_size) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } if (collection is ICollection<T> c) { 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) { 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) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); 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)) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if ((Count != 0) && (count < 0)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size == 0) { // Special case for empty list return -1; } if (index >= _size) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection); } if (count > index + 1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection); } 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 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) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } 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++]; } } if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { Array.Clear(_items, freeIndex, _size - freeIndex); // Clear the elements so that the gc can reclaim the references. } 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) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } _size--; if (index < _size) { Array.Copy(_items, index + 1, _items, index, _size - index); } if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { _items[_size] = default!; } _version++; } // Removes a range of elements from this list. public void RemoveRange(int index, int count) { if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (count > 0) { _size -= count; if (index < _size) { Array.Copy(_items, index + count, _items, index, _size - index); } _version++; if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { Array.Clear(_items, _size, count); } } } // 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) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (count > 1) { Array.Reverse(_items, index, count); } _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) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (count > 1) { Array.Sort<T>(_items, index, count, comparer); } _version++; } public void Sort(Comparison<T> comparison) { if (comparison == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } if (_size > 1) { ArraySortHelper<T>.Sort(_items, 0, _size, comparison); } _version++; } // ToArray returns an array containing the contents of the List. // This requires copying the List, which is an O(n) operation. public T[] ToArray() { 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) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } for (int i = 0; i < _size; i++) { if (!match!(_items[i])) { return false; } } return true; } public struct Enumerator : IEnumerator<T>, IEnumerator { private readonly List<T> _list; private int _index; private readonly int _version; [AllowNull, MaybeNull] private T _current; internal Enumerator(List<T> list) { _list = list; _index = 0; _version = list._version; _current = default; } 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) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = _list._size + 1; _current = default; return false; } public T Current => _current!; object? IEnumerator.Current { get { if (_index == 0 || _index == _list._size + 1) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return Current; } } void IEnumerator.Reset() { if (_version != _list._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = 0; _current = default; } } } }
using Csla.Core; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using static Csla.Analyzers.Extensions.IMethodSymbolExtensions; namespace Csla.Analyzers.Tests.Extensions { [TestClass] public sealed class IMethodSymbolExtensionsTests { private const string AMethodName = "AMethod"; private const string DataPortalOperationCode = @"namespace Csla.Analyzers.Tests.Targets.IMethodSymbolExtensionsTests { public class DataPortalOperations { public void AMethod() { } public void DataPortal_Create() { } public void DataPortal_Fetch() { } public void DataPortal_Insert() { } public void DataPortal_Update() { } public void DataPortal_Delete() { } public void DataPortal_DeleteSelf() { } public void DataPortal_Execute() { } public void Child_Create() { } public void Child_Fetch() { } public void Child_Insert() { } public void Child_Update() { } public void Child_DeleteSelf() { } } }"; private const string PropertyInfoManagementCode = @"namespace Csla.Analyzers.Tests.Targets.IMethodSymbolExtensionsTests { public class PropertyInfoManagementMethods : BusinessBase<PropertyInfoManagementMethods> { public void AMethod() { this.GetProperty(null); this.GetPropertyConvert<string, string>(null, null); this.SetProperty(null, null); this.SetPropertyConvert<string, string>(null, null); this.LoadProperty(null, null); this.LoadPropertyAsync<string>(null, null); this.LoadPropertyConvert<string, string>(null, null); this.LoadPropertyMarkDirty(null, null); this.ReadProperty(null); this.ReadPropertyConvert<string, string>(null); this.LazyGetProperty<string>(null, null); this.LazyGetPropertyAsync<string>(null, null); this.LazyReadProperty<string>(null, null); this.LazyReadPropertyAsync<string>(null, null); this.Something(); } private void Something() { } } }"; [TestMethod] public void IsPropertyInfoManagementMethodWhenSymbolIsNull() { Assert.IsFalse((null as IMethodSymbol).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForMethodThatIsNotAPropertyInfoManagementMethod() { Assert.IsFalse((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, "Something", typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForSetProperty() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.SetProperty, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForSetPropertyConvert() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.SetPropertyConvert, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForGetProperty() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.GetProperty, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.GetProperty, typeof(ReadOnlyBase<>))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForGetPropertyConvert() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.GetPropertyConvert, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.GetPropertyConvert, typeof(ReadOnlyBase<>))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForLazyGetProperty() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyGetProperty, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyGetProperty, typeof(ReadOnlyBase<>))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForLazyGetPropertyAsync() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyGetPropertyAsync, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyGetPropertyAsync, typeof(ReadOnlyBase<>))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForLazyReadProperty() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyReadProperty, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyReadProperty, typeof(ReadOnlyBase<>))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForLazyReadPropertyAsync() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyReadPropertyAsync, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyReadPropertyAsync, typeof(ReadOnlyBase<>))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForLoadPropertyAsync() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyAsync, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyAsync, typeof(ReadOnlyBase<>))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForLoadPropertyMarkDirty() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyMarkDirty, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyMarkDirty, typeof(ManagedObjectBase))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForReadProperty() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.ReadProperty, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.ReadProperty, typeof(ReadOnlyBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.ReadProperty, typeof(ManagedObjectBase))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForReadPropertyConvert() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.ReadPropertyConvert, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.ReadPropertyConvert, typeof(ReadOnlyBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.ReadPropertyConvert, typeof(ManagedObjectBase))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForLoadProperty() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadProperty, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadProperty, typeof(ReadOnlyBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadProperty, typeof(ManagedObjectBase))).IsPropertyInfoManagementMethod()); } [TestMethod] public async Task IsPropertyInfoManagementMethodForLoadPropertyConvert() { Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyConvert, typeof(BusinessBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyConvert, typeof(ReadOnlyBase<>))).IsPropertyInfoManagementMethod()); Assert.IsTrue((await GetMethodReferenceSymbolAsync( PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyConvert, typeof(ManagedObjectBase))).IsPropertyInfoManagementMethod()); } [TestMethod] public void IsDataPortalOperationWhenSymbolIsNull() => Assert.IsFalse((null as IMethodSymbol).IsDataPortalOperation()); [TestMethod] public void IsRootDataPortalOperationWhenSymbolIsNull() => Assert.IsFalse((null as IMethodSymbol).IsRootDataPortalOperation()); [TestMethod] public void IsChildDataPortalOperationWhenSymbolIsNull() => Assert.IsFalse((null as IMethodSymbol).IsChildDataPortalOperation()); [TestMethod] public async Task IsDataPortalOperationForMethodThatIsNotADataPortalOperation() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, AMethodName)).IsDataPortalOperation()); [TestMethod] public async Task IsRootDataPortalOperationForMethodThatIsNotADataPortalOperation() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, AMethodName)).IsRootDataPortalOperation()); [TestMethod] public async Task IsChildDataPortalOperationForMethodThatIsNotADataPortalOperation() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, AMethodName)).IsChildDataPortalOperation()); [TestMethod] public async Task IsDataPortalOperationForDataPortalCreate() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalCreate)).IsDataPortalOperation()); [TestMethod] public async Task IsRootDataPortalOperationForDataPortalCreate() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalCreate)).IsRootDataPortalOperation()); [TestMethod] public async Task IsChildDataPortalOperationForDataPortalCreate() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalCreate)).IsChildDataPortalOperation()); [TestMethod] public async Task IsDataPortalOperationForDataPortalFetch() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalFetch)).IsDataPortalOperation()); [TestMethod] public async Task IsRootDataPortalOperationForDataPortalFetch() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalFetch)).IsRootDataPortalOperation()); [TestMethod] public async Task IsChildDataPortalOperationForDataPortalFetch() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalFetch)).IsChildDataPortalOperation()); [TestMethod] public async Task IsDataPortalOperationForDataPortalInsert() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalInsert)).IsDataPortalOperation()); [TestMethod] public async Task IsRootDataPortalOperationForDataPortalInsert() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalInsert)).IsRootDataPortalOperation()); [TestMethod] public async Task IsChildDataPortalOperationForDataPortalInsert() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalInsert)).IsChildDataPortalOperation()); [TestMethod] public async Task IsDataPortalOperationForDataPortalUpdate() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalUpdate)).IsDataPortalOperation()); [TestMethod] public async Task IsRootDataPortalOperationForDataPortalUpdate() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalUpdate)).IsRootDataPortalOperation()); [TestMethod] public async Task IsChildDataPortalOperationForDataPortalUpdate() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalUpdate)).IsChildDataPortalOperation()); [TestMethod] public async Task IsDataPortalOperationForDataPortalDelete() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalDelete)).IsDataPortalOperation()); [TestMethod] public async Task IsRootDataPortalOperationForDataPortalDelete() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalDelete)).IsRootDataPortalOperation()); [TestMethod] public async Task IsChildDataPortalOperationForDataPortalDelete() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalDelete)).IsChildDataPortalOperation()); [TestMethod] public async Task IsDataPortalOperationForDataPortalDeleteSelf() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalDeleteSelf)).IsDataPortalOperation()); [TestMethod] public async Task IsRootDataPortalOperationForDataPortalDeleteSelf() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalDeleteSelf)).IsRootDataPortalOperation()); [TestMethod] public async Task IsChildDataPortalOperationForDataPortalDeleteSelf() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalDeleteSelf)).IsChildDataPortalOperation()); [TestMethod] public async Task IsDataPortalOperationForDataPortalExecute() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalExecute)).IsDataPortalOperation()); [TestMethod] public async Task IsRootDataPortalOperationForDataPortalExecute() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalExecute)).IsRootDataPortalOperation()); [TestMethod] public async Task IsChildDataPortalOperationForDataPortalExecute() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalExecute)).IsChildDataPortalOperation()); [TestMethod] public async Task IsDataPortalOperationForChildCreate() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildCreate)).IsDataPortalOperation()); [TestMethod] public async Task IsRootDataPortalOperationForChildCreate() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildCreate)).IsRootDataPortalOperation()); [TestMethod] public async Task IsChildDataPortalOperationForChildCreate() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildCreate)).IsChildDataPortalOperation()); [TestMethod] public async Task IsDataPortalOperationForChildFetch() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildFetch)).IsDataPortalOperation()); [TestMethod] public async Task IsRootDataPortalOperationForChildFetch() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildFetch)).IsRootDataPortalOperation()); [TestMethod] public async Task IsChildDataPortalOperationForChildFetch() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildFetch)).IsChildDataPortalOperation()); [TestMethod] public async Task IsDataPortalOperationForChildInsert() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildInsert)).IsDataPortalOperation()); [TestMethod] public async Task IsRootDataPortalOperationForChildInsert() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildInsert)).IsRootDataPortalOperation()); [TestMethod] public async Task IsChildDataPortalOperationForChildInsert() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildInsert)).IsChildDataPortalOperation()); [TestMethod] public async Task IsDataPortalOperationForChildUpdate() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildUpdate)).IsDataPortalOperation()); [TestMethod] public async Task IsRootDataPortalOperationForChildUpdate() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildUpdate)).IsRootDataPortalOperation()); [TestMethod] public async Task IsChildDataPortalOperationForChildUpdate() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildUpdate)).IsChildDataPortalOperation()); [TestMethod] public async Task IsDataPortalOperationForChildDeleteSelf() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildDeleteSelf)).IsDataPortalOperation()); [TestMethod] public async Task IsRootDataPortalOperationForChildDeleteSelf() => Assert.IsFalse((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildDeleteSelf)).IsRootDataPortalOperation()); [TestMethod] public async Task IsChildDataPortalOperationForChildDeleteSelf() => Assert.IsTrue((await GetMethodSymbolAsync( DataPortalOperationCode, CslaMemberConstants.Operations.ChildDeleteSelf)).IsChildDataPortalOperation()); private static async Task<(SemanticModel, SyntaxNode)> ParseFileAsync(string code, params PortableExecutableReference[] references) { var tree = CSharpSyntaxTree.ParseText(code); var refs = new List<PortableExecutableReference> { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) }; refs.AddRange(references); var compilation = CSharpCompilation.Create( Guid.NewGuid().ToString("N"), syntaxTrees: new[] { tree }, references: refs); var model = compilation.GetSemanticModel(tree); return (compilation.GetSemanticModel(tree), await tree.GetRootAsync().ConfigureAwait(false)); } private async Task<IMethodSymbol> GetMethodSymbolAsync(string code, string name) { var (model, root) = await ParseFileAsync(code); foreach (var method in root.DescendantNodes().OfType<MethodDeclarationSyntax>()) { if (model.GetDeclaredSymbol(method) is IMethodSymbol methodNode && methodNode.Name == name) { return methodNode; } } return null; } private async Task<IMethodSymbol> GetMethodReferenceSymbolAsync(string code, string name, Type type) { var (model, root) = await ParseFileAsync( code, MetadataReference.CreateFromFile(type.Assembly.Location)); foreach (var invocation in root.DescendantNodes().OfType<InvocationExpressionSyntax>()) { var symbol = model.GetSymbolInfo(invocation); var methodSymbol = symbol.Symbol as IMethodSymbol; if (methodSymbol?.Name == name) { return methodSymbol; } } return 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.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Errors; 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_FIRST = 0, PM_ARRAY_GETLENGTH, PM_DECIMAL_OPDECREMENT, PM_DECIMAL_OPDIVISION, PM_DECIMAL_OPEQUALITY, PM_DECIMAL_OPGREATERTHAN, PM_DECIMAL_OPGREATERTHANOREQUAL, PM_DECIMAL_OPINCREMENT, PM_DECIMAL_OPINEQUALITY, PM_DECIMAL_OPLESSTHAN, PM_DECIMAL_OPLESSTHANOREQUAL, PM_DECIMAL_OPMINUS, PM_DECIMAL_OPMODULUS, PM_DECIMAL_OPMULTIPLY, PM_DECIMAL_OPPLUS, PM_DECIMAL_OPUNARYMINUS, PM_DECIMAL_OPUNARYPLUS, 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_CONDITION, 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_MEMBERS, PM_EXPRESSION_NEW_TYPE, PM_EXPRESSION_QUOTE, PM_EXPRESSION_ARRAYLENGTH, PM_EXPRESSION_NOT, PM_EXPRESSION_NOT_USER_DEFINED, PM_EXPRESSION_NEWARRAYINIT, PM_EXPRESSION_PROPERTY, PM_EXPRESSION_INVOKE, PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT, PM_G_OPTIONAL_CTOR, PM_G_OPTIONAL_GETHASVALUE, PM_G_OPTIONAL_GETVALUE, PM_G_OPTIONAL_GET_VALUE_OR_DEF, PM_STRING_CONCAT_OBJECT_1, // NOTE: these 3 must be sequential. See RealizeConcats PM_STRING_CONCAT_OBJECT_2, PM_STRING_CONCAT_OBJECT_3, PM_STRING_CONCAT_STRING_1, // NOTE: these 4 must be sequential. See RealizeConcats PM_STRING_CONCAT_STRING_2, PM_STRING_CONCAT_STRING_3, PM_STRING_CONCAT_STRING_4, PM_STRING_CONCAT_SZ_OBJECT, PM_STRING_CONCAT_SZ_STRING, PM_STRING_GETCHARS, PM_STRING_GETLENGTH, 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_FIRST = 0, PP_ARRAY_LENGTH, PP_G_OPTIONAL_VALUE, PP_COUNT, }; internal enum MethodRequiredEnum { Required, Optional } 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 SIG_REF, // must be followed by signature of ref type SIG_OUT, // must be followed by signature of out type } // 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, MethodRequiredEnum required, 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 PREDEFMETH setter; public PredefinedPropertyInfo(PREDEFPROP property, MethodRequiredEnum required, PredefinedName name, PREDEFMETH getter, PREDEFMETH setter) { this.property = property; this.name = name; this.getter = getter; this.setter = setter; } }; // Loads and caches predefined members. // Also finds constructors on delegate types. internal sealed class PredefinedMembers { private static void RETAILVERIFY(bool f) { if (!f) Debug.Assert(false, "panic!"); } private readonly SymbolLoader _loader; internal SymbolTable RuntimeBinderSymbolTable; private readonly MethodSymbol[] _methods = new MethodSymbol[(int)PREDEFMETH.PM_COUNT]; private readonly PropertySymbol[] _properties = new PropertySymbol[(int)PREDEFPROP.PP_COUNT]; private Name GetMethName(PREDEFMETH method) { return GetPredefName(GetMethPredefName(method)); } private AggregateSymbol GetMethParent(PREDEFMETH method) { return GetOptPredefAgg(GetMethPredefType(method)); } // delegate specific helpers private MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType, int[] signature) { Debug.Assert(delegateType != null && delegateType.IsDelegate()); Debug.Assert(signature != null); return LoadMethod( delegateType, signature, 0, // meth ty vars GetPredefName(PredefinedName.PN_CTOR), ACCESS.ACC_PUBLIC, false, // MethodCallingConventionEnum.Static false); // MethodCallingConventionEnum.Virtual } private MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType) { Debug.Assert(delegateType != null && delegateType.IsDelegate()); MethodSymbol ctor = FindDelegateConstructor(delegateType, s_DelegateCtorSignature1); if (ctor == null) { ctor = FindDelegateConstructor(delegateType, s_DelegateCtorSignature2); } return ctor; } public MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType, bool fReportErrors) { MethodSymbol ctor = FindDelegateConstructor(delegateType); if (ctor == null && fReportErrors) { GetErrorContext().Error(ErrorCode.ERR_BadDelegateConstructor, delegateType); } return ctor; } // property specific helpers private PropertySymbol EnsureProperty(PREDEFPROP property) { RETAILVERIFY((int)property > (int)PREDEFMETH.PM_FIRST && (int)property < (int)PREDEFMETH.PM_COUNT); if (_properties[(int)property] == null) { _properties[(int)property] = LoadProperty(property); } return _properties[(int)property]; } private PropertySymbol LoadProperty(PREDEFPROP property) { return LoadProperty( property, GetPropName(property), GetPropGetter(property), GetPropSetter(property)); } private Name GetPropName(PREDEFPROP property) { return GetPredefName(GetPropPredefName(property)); } private PropertySymbol LoadProperty( PREDEFPROP predefProp, Name propertyName, PREDEFMETH propertyGetter, PREDEFMETH propertySetter) { Debug.Assert(propertyName != null); Debug.Assert(propertyGetter > PREDEFMETH.PM_FIRST && propertyGetter < PREDEFMETH.PM_COUNT); Debug.Assert(propertySetter > PREDEFMETH.PM_FIRST && propertySetter <= PREDEFMETH.PM_COUNT); MethodSymbol getter = GetOptionalMethod(propertyGetter); MethodSymbol setter = null; if (propertySetter != PREDEFMETH.PM_COUNT) { setter = GetOptionalMethod(propertySetter); } if (getter == null && setter == null) { RuntimeBinderSymbolTable.AddPredefinedPropertyToSymbolTable(GetOptPredefAgg(GetPropPredefType(predefProp)), propertyName); getter = GetOptionalMethod(propertyGetter); if (propertySetter != PREDEFMETH.PM_COUNT) { setter = GetOptionalMethod(propertySetter); } } setter?.SetMethKind(MethodKindEnum.PropAccessor); PropertySymbol property = null; if (getter != null) { getter.SetMethKind(MethodKindEnum.PropAccessor); property = getter.getProperty(); // Didn't find it, so load it. if (property == null) { RuntimeBinderSymbolTable.AddPredefinedPropertyToSymbolTable(GetOptPredefAgg(GetPropPredefType(predefProp)), propertyName); } property = getter.getProperty(); Debug.Assert(property != null); if (property.name != propertyName || (propertySetter != PREDEFMETH.PM_COUNT && (setter == null || !setter.isPropertyAccessor() || setter.getProperty() != property)) || property.getBogus()) { property = null; } } return property; } private SymbolLoader GetSymbolLoader() { Debug.Assert(_loader != null); return _loader; } private ErrorHandling GetErrorContext() { return GetSymbolLoader().GetErrorContext(); } private TypeManager GetTypeManager() { return GetSymbolLoader().GetTypeManager(); } private BSYMMGR getBSymmgr() { return GetSymbolLoader().getBSymmgr(); } private Name GetPredefName(PredefinedName pn) { return NameManager.GetPredefinedName(pn); } private AggregateSymbol GetOptPredefAgg(PredefinedType pt) { return GetSymbolLoader().GetOptPredefAgg(pt); } private CType LoadTypeFromSignature(int[] signature, ref int indexIntoSignatures, TypeArray classTyVars) { Debug.Assert(signature != null); MethodSignatureEnum current = (MethodSignatureEnum)signature[indexIntoSignatures]; indexIntoSignatures++; switch (current) { case MethodSignatureEnum.SIG_REF: { CType refType = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (refType == null) { return null; } return GetTypeManager().GetParameterModifier(refType, false); } case MethodSignatureEnum.SIG_OUT: { CType outType = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (outType == null) { return null; } return GetTypeManager().GetParameterModifier(outType, true); } case MethodSignatureEnum.SIG_SZ_ARRAY: { CType elementType = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (elementType == null) { return null; } return GetTypeManager().GetArray(elementType, 1, true); } case MethodSignatureEnum.SIG_METH_TYVAR: { int index = signature[indexIntoSignatures]; indexIntoSignatures++; return GetTypeManager().GetStdMethTypeVar(index); } case MethodSignatureEnum.SIG_CLASS_TYVAR: { int index = signature[indexIntoSignatures]; indexIntoSignatures++; return classTyVars[index]; } case (MethodSignatureEnum)PredefinedType.PT_VOID: return GetTypeManager().GetVoid(); default: { Debug.Assert(current >= 0 && (int)current < (int)PredefinedType.PT_COUNT); AggregateSymbol agg = GetOptPredefAgg((PredefinedType)current); if (agg != null) { CType[] typeArgs = new CType[agg.GetTypeVars().Count]; for (int iTypeArg = 0; iTypeArg < agg.GetTypeVars().Count; iTypeArg++) { typeArgs[iTypeArg] = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (typeArgs[iTypeArg] == null) { return null; } } AggregateType type = GetTypeManager().GetAggregate(agg, getBSymmgr().AllocParams(agg.GetTypeVars().Count, typeArgs)); if (type.isPredefType(PredefinedType.PT_G_OPTIONAL)) { return GetTypeManager().GetNubFromNullable(type); } return type; } } break; } return null; } private 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 < count; i++) { ptypes[i] = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (ptypes[i] == null) { return null; } } return getBSymmgr().AllocParams(count, ptypes); } public PredefinedMembers(SymbolLoader loader) { _loader = loader; Debug.Assert(_loader != null); _methods = new MethodSymbol[(int)PREDEFMETH.PM_COUNT]; _properties = new PropertySymbol[(int)PREDEFPROP.PP_COUNT]; #if DEBUG // validate the tables for (int i = (int)PREDEFMETH.PM_FIRST + 1; i < (int)PREDEFMETH.PM_COUNT; i++) { Debug.Assert((int)GetMethInfo((PREDEFMETH)i).method == i); } for (int i = (int)PREDEFPROP.PP_FIRST + 1; i < (int)PREDEFPROP.PP_COUNT; i++) { Debug.Assert((int)GetPropInfo((PREDEFPROP)i).property == i); } #endif } public PropertySymbol GetProperty(PREDEFPROP property) // Reports an error if the property is not found. { PropertySymbol result = EnsureProperty(property); if (result == null) { ReportError(property); } return result; } public MethodSymbol GetMethod(PREDEFMETH method) { MethodSymbol result = EnsureMethod(method); if (result == null) { ReportError(method); } return result; } private MethodSymbol GetOptionalMethod(PREDEFMETH method) { return EnsureMethod(method); } private MethodSymbol EnsureMethod(PREDEFMETH method) { RETAILVERIFY(method > PREDEFMETH.PM_FIRST && method < PREDEFMETH.PM_COUNT); if (_methods[(int)method] == null) { _methods[(int)method] = LoadMethod(method); } return _methods[(int)method]; } private 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); if (type == null) { return null; } TypeArray classTyVars = type.GetTypeVarsAll(); int index = 0; CType returnType = LoadTypeFromSignature(signature, ref index, classTyVars); if (returnType == null) { return null; } TypeArray argumentTypes = LoadTypeArrayFromSignature(signature, ref index, classTyVars); if (argumentTypes == null) { return null; } TypeArray standardMethodTyVars = GetTypeManager().GetStdMethTyVarArray(cMethodTyVars); MethodSymbol ret = LookupMethodWhileLoading(type, cMethodTyVars, methodName, methodAccess, isStatic, isVirtual, returnType, argumentTypes); if (ret == null) { RuntimeBinderSymbolTable.AddPredefinedMethodToSymbolTable(type, methodName); ret = LookupMethodWhileLoading(type, cMethodTyVars, methodName, methodAccess, isStatic, isVirtual, returnType, argumentTypes); } return ret; } private MethodSymbol LookupMethodWhileLoading(AggregateSymbol type, int cMethodTyVars, Name methodName, ACCESS methodAccess, bool isStatic, bool isVirtual, CType returnType, TypeArray argumentTypes) { for (Symbol sym = GetSymbolLoader().LookupAggMember(methodName, type, symbmask_t.MASK_ALL); sym != null; sym = GetSymbolLoader().LookupNextSym(sym, type, symbmask_t.MASK_ALL)) { if (sym.IsMethodSymbol()) { MethodSymbol methsym = sym.AsMethodSymbol(); if ((methsym.GetAccess() == methodAccess || methodAccess == ACCESS.ACC_UNKNOWN) && methsym.isStatic == isStatic && methsym.isVirtual == isVirtual && methsym.typeVars.Count == cMethodTyVars && GetTypeManager().SubstEqualTypes(methsym.RetType, returnType, null, methsym.typeVars, SubstTypeFlags.DenormMeth) && GetTypeManager().SubstEqualTypeArrays(methsym.Params, argumentTypes, (TypeArray)null, methsym.typeVars, SubstTypeFlags.DenormMeth) && !methsym.getBogus()) { return methsym; } } } return null; } private MethodSymbol LoadMethod(PREDEFMETH method) { return LoadMethod( GetMethParent(method), GetMethSignature(method), GetMethTyVars(method), GetMethName(method), GetMethAccess(method), IsMethStatic(method), IsMethVirtual(method)); } private void ReportError(PREDEFMETH method) { ReportError(GetMethPredefType(method), GetMethPredefName(method)); } private void ReportError(PredefinedType type, PredefinedName name) { GetErrorContext().Error(ErrorCode.ERR_MissingPredefinedMember, PredefinedTypes.GetFullName(type), GetPredefName(name)); } private static readonly int[] s_DelegateCtorSignature1 = { (int)PredefinedType.PT_VOID, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_INTPTR }; private static readonly int[] s_DelegateCtorSignature2 = { (int)PredefinedType.PT_VOID, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_UINTPTR }; private static PredefinedName GetPropPredefName(PREDEFPROP property) { return GetPropInfo(property).name; } private static PREDEFMETH GetPropGetter(PREDEFPROP property) { PREDEFMETH result = GetPropInfo(property).getter; // getters are MethodRequiredEnum.Required Debug.Assert(result > PREDEFMETH.PM_FIRST && result < PREDEFMETH.PM_COUNT); return result; } private static PredefinedType GetPropPredefType(PREDEFPROP property) { return GetMethInfo(GetPropGetter(property)).type; } private static PREDEFMETH GetPropSetter(PREDEFPROP property) { PREDEFMETH result = GetPropInfo(property).setter; // setters are not MethodRequiredEnum.Required Debug.Assert(result > PREDEFMETH.PM_FIRST && result <= PREDEFMETH.PM_COUNT); return GetPropInfo(property).setter; } private void ReportError(PREDEFPROP property) { ReportError(GetPropPredefType(property), GetPropPredefName(property)); } // 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_FIRST, MethodRequiredEnum.Optional, PredefinedName.PN_COUNT, PREDEFMETH.PM_COUNT, PREDEFMETH.PM_COUNT ), new PredefinedPropertyInfo( PREDEFPROP.PP_ARRAY_LENGTH, MethodRequiredEnum.Optional, PredefinedName.PN_LENGTH, PREDEFMETH.PM_ARRAY_GETLENGTH, PREDEFMETH.PM_COUNT ), new PredefinedPropertyInfo( PREDEFPROP.PP_G_OPTIONAL_VALUE, MethodRequiredEnum.Optional, PredefinedName.PN_CAP_VALUE, PREDEFMETH.PM_G_OPTIONAL_GETVALUE, PREDEFMETH.PM_COUNT ), }; private static PredefinedPropertyInfo GetPropInfo(PREDEFPROP property) { RETAILVERIFY(property > PREDEFPROP.PP_FIRST && property < PREDEFPROP.PP_COUNT); RETAILVERIFY(s_predefinedProperties[(int)property].property == property); return s_predefinedProperties[(int)property]; } private static PredefinedMethodInfo GetMethInfo(PREDEFMETH method) { RETAILVERIFY(method > PREDEFMETH.PM_FIRST && method < PREDEFMETH.PM_COUNT); RETAILVERIFY(s_predefinedMethods[(int)method].method == method); return s_predefinedMethods[(int)method]; } private static PredefinedName GetMethPredefName(PREDEFMETH method) { return GetMethInfo(method).name; } private static PredefinedType GetMethPredefType(PREDEFMETH method) { return GetMethInfo(method).type; } private static bool IsMethStatic(PREDEFMETH method) { return GetMethInfo(method).callingConvention == MethodCallingConventionEnum.Static; } private static bool IsMethVirtual(PREDEFMETH method) { return GetMethInfo(method).callingConvention == MethodCallingConventionEnum.Virtual; } private static ACCESS GetMethAccess(PREDEFMETH method) { return GetMethInfo(method).access; } private static int GetMethTyVars(PREDEFMETH method) { return GetMethInfo(method).cTypeVars; } private static int[] GetMethSignature(PREDEFMETH method) { return GetMethInfo(method).signature; } // 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_FIRST, MethodRequiredEnum.Optional, PredefinedType.PT_COUNT, PredefinedName.PN_COUNT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_VOID, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_ARRAY_GETLENGTH, MethodRequiredEnum.Optional, PredefinedType.PT_ARRAY, PredefinedName.PN_GETLENGTH, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INT, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPDECREMENT, MethodRequiredEnum.Optional, 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_OPDIVISION, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPDIVISION, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPGREATERTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPGREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPGREATERTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPGREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPINCREMENT, MethodRequiredEnum.Optional, 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_OPINEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPLESSTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPLESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPLESSTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPLESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMINUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMINUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMODULUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMODULUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMULTIPLY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPPLUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPPLUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPUNARYMINUS, MethodRequiredEnum.Optional, 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_DECIMAL_OPUNARYPLUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPUNARYPLUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_COMBINE, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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_CONDITION, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONDITION, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CONDITIONALEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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_MEMBERS, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 3, (int)PredefinedType.PT_CONSTRUCTORINFO, (int)PredefinedType.PT_G_IENUMERABLE, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_MEMBERINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW_TYPE, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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_ARRAYLENGTH, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYLENGTH, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOT, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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_METHODINFO_CREATEDELEGATE_TYPE_OBJECT, MethodRequiredEnum.Optional, PredefinedType.PT_METHODINFO, PredefinedName.PN_CREATEDELEGATE, MethodCallingConventionEnum.Virtual, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_OBJECT}), new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_CTOR, MethodRequiredEnum.Optional, 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_GETHASVALUE, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GETHASVALUE, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GETVALUE, MethodRequiredEnum.Optional, 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_G_OPTIONAL_GET_VALUE_OR_DEF, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GET_VALUE_OR_DEF, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_1, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)PredefinedType.PT_OBJECT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_2, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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_1, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_2, MethodRequiredEnum.Optional, 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_CONCAT_STRING_3, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 3, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_4, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 4, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_SZ_OBJECT, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_OBJECT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_SZ_STRING, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_GETCHARS, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_GETCHARS, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CHAR, 1, (int)PredefinedType.PT_INT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_GETLENGTH, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_GETLENGTH, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INT, 0, }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_OPEQUALITY, MethodRequiredEnum.Optional, 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, MethodRequiredEnum.Optional, 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 }), }; } }
using System; using System.Collections.Generic; using System.Linq; using Glimpse.Agent.Internal.Inspectors.Mvc.Proxies; using Glimpse.Agent.Messages; using Glimpse.Internal; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DiagnosticAdapter; using Microsoft.Extensions.Logging; namespace Glimpse.Agent.Internal.Inspectors { public partial class WebDiagnosticsInspector { partial void MvcOnCreated() { _proxyAdapter.Register("Microsoft.AspNetCore.Mvc.ViewResult"); _proxyAdapter.Register("Microsoft.AspNetCore.Mvc.ContentResult"); _proxyAdapter.Register("Microsoft.AspNetCore.Mvc.ObjectResult"); _proxyAdapter.Register("Microsoft.AspNetCore.Routing.Route"); _proxyAdapter.Register("Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor"); _proxyAdapter.Register("Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor"); _proxyAdapter.Register("Microsoft.AspNetCore.Mvc.FileResult"); } // NOTE: This event is the start of the action pipeline. The action has been selected, the route // has been selected but no filters have run and model binding hasn't occured. [DiagnosticName("Microsoft.AspNetCore.Mvc.BeforeAction")] public void OnBeforeAction(object actionDescriptor, HttpContext httpContext, IRouteData routeData) { var startDateTime = DateTime.UtcNow; var typedActionDescriptor = ConvertActionDescriptor(actionDescriptor); var message = new BeforeActionMessage { ActionId = typedActionDescriptor.Id, ActionDisplayName = typedActionDescriptor.DisplayName, ActionName = typedActionDescriptor.ActionName, ActionControllerName = typedActionDescriptor.ControllerName, ActionStartTime = startDateTime, RouteData = routeData.Values?.ToDictionary(x => x.Key, x => x.Value?.ToString()) }; // NOTE: Template data is only available in the TemplateRoute, so we need to try and // promote that type into something we can use var router = routeData.Routers[routeData.Routers.Count - 2]; if (router.GetType().FullName == "Microsoft.AspNetCore.Routing.Route") { var templateRoute = _proxyAdapter.Process<IRouter>("Microsoft.AspNetCore.Routing.Route", router); message.RouteName = templateRoute.Name; message.RoutePattern = templateRoute.RouteTemplate; message.RouteConfiguration = templateRoute.ParsedTemplate?.Parameters?.ToDictionary(x => x.Name, x => new RouteConfigurationData { Default = x.DefaultValue?.ToString(), Optional = x.IsOptional }); } _broker.BeginLogicalOperation(message, startDateTime); _broker.SendMessage(message); } [DiagnosticName("Microsoft.AspNetCore.Mvc.AfterAction")] public void OnAfterAction(object actionDescriptor, HttpContext httpContext) { var timing = _broker.EndLogicalOperation<BeforeActionMessage>(); if (timing != null) { var typedActionDescriptor = ConvertActionDescriptor(actionDescriptor); var message = new AfterActionMessage() { ActionId = typedActionDescriptor.Id, ActionName = typedActionDescriptor.ActionName, ActionControllerName = typedActionDescriptor.ControllerName, ActionEndTime = timing.End, ActionDuration = timing.Elapsed, ActionOffset = timing.Offset }; _broker.SendMessage(message); } else { _logger.LogCritical("OnAfterAction: Couldn't publish `AfterActionMessage` as `BeforeActionMessage` wasn't found in stack"); } } // NOTE: This event is the start of the action execution. The action has been selected, the route // has been selected, filters have run and model binding has occured. [DiagnosticName("Microsoft.AspNetCore.Mvc.BeforeActionMethod")] public void OnBeforeActionMethod( IActionContext actionContext, IDictionary<string, object> arguments) { var startDateTime = DateTime.UtcNow; var actionDescriptor = ConvertActionDescriptor(actionContext.ActionDescriptor); var message = new BeforeActionInvokedMessage { ActionId = actionDescriptor.Id, ActionDisplayName = actionDescriptor.DisplayName, ActionName = actionDescriptor.ActionName, ActionControllerName = actionDescriptor.ControllerName, ActionTargetClass = actionDescriptor.ControllerTypeInfo.Name, ActionTargetMethod = actionDescriptor.MethodInfo.Name, ActionInvokedStartTime = startDateTime, Binding = arguments?.Select(x => new BindingData { Type = TypeNameHelper.GetTypeDisplayName(x.Value, false), TypeFullName = TypeNameHelper.GetTypeDisplayName(x.Value), Name = x.Key, Value = SanitizeUserObjectsHelper.GetSafeObject(x.Value) }).ToList() }; _broker.BeginLogicalOperation(message, startDateTime); _broker.SendMessage(message); } [DiagnosticName("Microsoft.AspNetCore.Mvc.AfterActionMethod")] public void OnAfterActionMethod( IActionContext actionContext) { var timing = _broker.EndLogicalOperation<BeforeActionInvokedMessage>(); if (timing != null) { var actionDescriptor = ConvertActionDescriptor(actionContext.ActionDescriptor); var message = new AfterActionInvokedMessage() { ActionId = actionDescriptor.Id, ActionName = actionDescriptor.ActionName, ActionControllerName = actionDescriptor.ControllerName, ActionInvokedEndTime = timing.End, ActionInvokedDuration = timing.Elapsed, ActionInvokedOffset = timing.Offset }; _broker.SendMessage(message); } else { _logger.LogCritical("OnAfterActionMethod: Couldn't publish `AfterActionInvokedMessage` as `BeforeActionInvokedMessage` wasn't found in stack"); } } // NOTE: This event is the start of the result pipeline. The action has been executed, but // we haven't yet determined which view (if any) will handle the request [DiagnosticName("Microsoft.AspNetCore.Mvc.BeforeActionResult")] public void OnBeforeActionResult( IActionContext actionContext, object result) { var startDateTime = DateTime.UtcNow; var actionDescriptor = ConvertActionDescriptor(actionContext.ActionDescriptor); // TODO: Need to work off the inheritence chain //var inheritancHierarchy = result.GetType().GetInheritancHierarchy().ToList(); // TODO: currently looking to see if this switch code and ProxyAdapter can be // consumed by Microsoft.Extensions.DiagnosticAdapter var message = (BeforeActionResultMessage)null; switch (result.GetType().FullName) { case "Microsoft.AspNetCore.Mvc.ViewResult": var viewResult = _proxyAdapter.Process<ActionResultTypes.IViewResult>("Microsoft.AspNetCore.Mvc.ViewResult", result); message = new BeforeActionViewResultMessage { ViewName = viewResult.ViewName, StatusCode = viewResult.StatusCode, ContentType = viewResult.ContentType?.ToString() }; break; case "Microsoft.AspNetCore.Mvc.ContentResult": var contentResult = _proxyAdapter.Process<ActionResultTypes.IContentResult>("Microsoft.AspNetCore.Mvc.ContentResult", result); message = new BeforeActionContentResultMessage { StatusCode = contentResult.StatusCode, Content = contentResult.Content, ContentType = contentResult.ContentType?.ToString() }; break; case "Microsoft.AspNetCore.Mvc.ObjectResult": var objectResult = _proxyAdapter.Process<ActionResultTypes.IObjectResult>("Microsoft.AspNetCore.Mvc.ContentResult", result); message = new BeforeActionObjectResultMessage { StatusCode = objectResult.StatusCode, //Value = objectResult.Value, //Formatters = objectResult.Formatters?.Select(x => x.GetType()).ToList(), //ContentTypes = objectResult.ContentTypes?.Select(x => x.ToString()).ToList() }; break; /* case "Microsoft.AspNetCore.Mvc.FileResult": case "Microsoft.AspNetCore.Mvc.FileContentResult": case "Microsoft.AspNetCore.Mvc.FileStreamResult": var fileResult = _proxyAdapter.Process<ActionResultTypes.IFileResult>("Microsoft.AspNetCore.Mvc.FileResult", result); message = new BeforeActionFileResultMessage { FileDownloadName = fileResult.FileDownloadName, ContentType = fileResult.ContentType }; break;*/ default: message = new BeforeActionResultMessage(); break; } // TODO: Need to implement the following // https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Formatters.Json/JsonResult.cs // https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/RedirectResult.cs // https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/RedirectToRouteResult.cs // https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/HttpStatusCodeResult.cs message.ActionId = actionDescriptor.Id; message.ActionDisplayName = actionDescriptor.DisplayName; message.ActionName = actionDescriptor.ActionName; message.ActionControllerName = actionDescriptor.ControllerName; message.ActionResultStartTime = startDateTime; _broker.BeginLogicalOperation(message, startDateTime); _broker.SendMessage(message); } [DiagnosticName("Microsoft.AspNetCore.Mvc.AfterActionResult")] public void OnAfterActionResult( IActionContext actionContext, IActionResult result) { var timing = _broker.EndLogicalOperation<BeforeActionResultMessage>(); if (timing != null) { var actionDescriptor = ConvertActionDescriptor(actionContext.ActionDescriptor); var message = new AfterActionResultMessage() { ActionId = actionDescriptor.Id, ActionName = actionDescriptor.ActionName, ActionControllerName = actionDescriptor.ControllerName, ActionResultEndTime = timing.End, ActionResultDuration = timing.Elapsed, ActionResultOffset = timing.Offset }; _broker.SendMessage(message); } else { _logger.LogCritical("OnAfterActionResult: Couldn't publish `AfterActionResultMessage` as `BeforeActionResultMessage` wasn't found in stack"); } } // NOTE: This event is only fired when we dont find any matches at all. This executes // at the end of the matching process. You will never get a ViewResultViewNotFound // and ViewResultViewFound event firing for the same view resolution. [DiagnosticName("Microsoft.AspNetCore.Mvc.ViewNotFound")] public void OnViewResultViewNotFound( IActionContext actionContext, ActionResultTypes.IViewResult result, string viewName, IReadOnlyList<string> searchedLocations) { var actionDescriptor = ConvertActionDescriptor(actionContext.ActionDescriptor); var message = new ActionViewNotFoundMessage() { ActionId = actionDescriptor.Id, ActionName = actionDescriptor.ActionName, ActionControllerName = actionDescriptor.ControllerName, ViewName = viewName, ViewSearchedLocations = searchedLocations, ViewDidFind = false, ViewSearchedTime = DateTime.UtcNow }; _broker.SendMessage(message); } // NOTE: This event is only fired when we do find a match. This executes at the end of // the matching process. You will never get a ViewResultViewNotFound and // ViewResultViewFound event firing for the same view resolution. [DiagnosticName("Microsoft.AspNetCore.Mvc.ViewFound")] public void OnViewResultViewFound( IActionContext actionContext, object result, string viewName, IView view) { var actionDescriptor = ConvertActionDescriptor(actionContext.ActionDescriptor); var message = new ActionViewDidFoundMessage { ActionId = actionDescriptor.Id, ActionName = actionDescriptor.ActionName, ActionControllerName = actionDescriptor.ControllerName, ViewName = viewName, ViewPath = view.Path, ViewDidFind = true, ViewSearchedTime = DateTime.UtcNow }; _broker.SendMessage(message); } [DiagnosticName("Microsoft.AspNetCore.Mvc.BeforeView")] public void OnBeforeView(IView view, IViewContext viewContext) { var startDateTime = DateTime.UtcNow; var actionDescriptor = ConvertActionDescriptor(viewContext.ActionDescriptor); var message = new BeforeActionViewInvokedMessage { ActionId = actionDescriptor.Id, ActionName = actionDescriptor.ActionName, ActionControllerName = actionDescriptor.ControllerName, ViewPath = view.Path, //ViewData = new ViewResult { // TODO: because we switch threads, we need to make sure we get // ViewData = result.ViewData, // what we need off the thread before publishing // TempData = result.TempData //}, ViewStartTime = startDateTime }; _broker.BeginLogicalOperation(message, startDateTime); _broker.SendMessage(message); } [DiagnosticName("Microsoft.AspNetCore.Mvc.AfterView")] public void OnAfterView(IView view, IViewContext viewContext) { var timing = _broker.EndLogicalOperation<BeforeActionViewInvokedMessage>(); if (timing != null) { var actionDescriptor = ConvertActionDescriptor(viewContext.ActionDescriptor); var message = new AfterActionViewInvokedMessage { ActionId = actionDescriptor.Id, ActionName = actionDescriptor.ActionName, ActionControllerName = actionDescriptor.ControllerName, ViewEndTime = timing.End, ViewDuration = timing.Elapsed, ViewOffset = timing.Offset }; _broker.SendMessage(message); } else { _logger.LogCritical("OnAfterView: Couldn't publish `AfterActionViewInvokedMessage` as `BeforeActionViewInvokedMessage` wasn't found in stack"); } } [DiagnosticName("Microsoft.AspNetCore.Mvc.BeforeViewComponent")] public void OnBeforeViewComponent(IViewComponentContext viewComponentContext) { var startDateTime = DateTime.UtcNow; var message = new BeforeViewComponentMessage { ComponentId = viewComponentContext.ViewComponentDescriptor.Id, ComponentDisplayName = viewComponentContext.ViewComponentDescriptor.FullName, ComponentName = viewComponentContext.ViewComponentDescriptor.ShortName, ComponentStartTime = startDateTime, Arguments = viewComponentContext.Arguments?.Select(x => new ArgumentData { Type = TypeNameHelper.GetTypeDisplayName(x, false), TypeFullName = TypeNameHelper.GetTypeDisplayName(x), Name = null, Value = SanitizeUserObjectsHelper.GetSafeObject(x) }).ToList() }; _broker.BeginLogicalOperation(message, startDateTime); _broker.SendMessage(message); } [DiagnosticName("Microsoft.AspNetCore.Mvc.AfterViewComponent")] public void OnAfterViewComponent(IViewComponentContext viewComponentContext) { var timing = _broker.EndLogicalOperation<BeforeViewComponentMessage>(); if (timing != null) { var message = new AfterViewComponentMessage { ComponentId = viewComponentContext.ViewComponentDescriptor.Id, ComponentName = viewComponentContext.ViewComponentDescriptor.ShortName, ComponentEndTime = timing.End, ComponentDuration = timing.Elapsed, ComponentOffset = timing.Offset }; _broker.SendMessage(message); } else { _logger.LogCritical("OnAfterViewComponent: Couldn't publish `AfterViewComponentMessage` as `BeforeViewComponentMessage` wasn't found in stack"); } } private IActionDescriptor ConvertActionDescriptor(object actionDescriptor) { var typedActionDescriptor = (IActionDescriptor)null; // NOTE: ActionDescriptor is usually ControllerActionDescriptor but the compile time type is // ActionDescriptor. This is a problem because we are misisng the ControllerName which // we use a lot. switch (actionDescriptor.GetType().FullName) { case "Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor": typedActionDescriptor = _proxyAdapter.Process<IActionDescriptor>("Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor", actionDescriptor); break; case "Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor": typedActionDescriptor = _proxyAdapter.Process<IActionDescriptor>("Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor", actionDescriptor); break; } return typedActionDescriptor; } } }
// 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 Infrastructure.Common; using System; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Security; using Xunit; using System.Collections.Generic; using System.Text; public class Tcp_ClientCredentialTypeCertificateCanonicalNameTests : ConditionalWcfTest { // We set up three endpoints on the WCF service (server) side, each with a different certificate: // Tcp_ClientCredentialType_Certificate_With_CanonicalName_Localhost_Address - is bound to a cert where CN=localhost // Tcp_ClientCredentialType_Certificate_With_CanonicalName_DomainName_Address - is bound to a cert where CN=domainname // Tcp_ClientCredentialType_Certificate_With_CanonicalName_Fqdn_Address - is bound to a cert with a fqdn, e.g., CN=domainname.example.com // // When tests are run, a /p:ServiceHost=<name> is specified; if none is specified, then "localhost" is used // Hence, we are only able to determine at runtime whether a particular endpoint presented by the WCF Service is going // to pass a variation or fail a variation. [WcfFact] [Condition(nameof(Root_Certificate_Installed))] [OuterLoop] public static void Certificate_With_CanonicalName_Localhost_Address_EchoString() { var localhostEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_Localhost_Address); var endpointAddress = new EndpointAddress(localhostEndpointUri); bool shouldCallSucceed = string.Compare(localhostEndpointUri.Host, "localhost", StringComparison.OrdinalIgnoreCase) == 0; string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; factory = new ChannelFactory<IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust; serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have failed but succeeded. ", localhostEndpointUri.Host); errorBuilder.AppendFormat("This means that the certificate validation passed when it should have failed. "); errorBuilder.AppendFormat("Check the certificate returned by the endpoint at '{0}' ", localhostEndpointUri); errorBuilder.AppendFormat("to see that it is correct; if it is, there is likely an issue with the identity checking logic."); Assert.True(shouldCallSucceed, errorBuilder.ToString()); } catch (Exception exception) when (exception is CommunicationException || exception is MessageSecurityException) { if ((exception is MessageSecurityException) || (exception is CommunicationException) && !string.Equals(exception.InnerException.GetType().ToString(), "System.ServiceModel.Security.MessageSecurityException")) { // If there's a MessageSecurityException, we assume that the cert validation failed. Unfortunately checking for the // message is really brittle and we can't account for loc and how .NET Native will display the exceptions // The exception message should look like: // // System.ServiceModel.Security.MessageSecurityException : Identity check failed for outgoing message. The expected // DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'example.com'.If this // is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'example.com' as // the Identity property of EndpointAddress when creating channel proxy. var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have been successful but failed with a MessageSecurityException. ", localhostEndpointUri.Host); errorBuilder.AppendFormat("This usually means that the certificate validation failed when it should have passed. "); errorBuilder.AppendFormat("When connecting to host '{0}', the expectation is that the DNSClaim will be for the same hostname. ", localhostEndpointUri.Host); errorBuilder.AppendFormat("Exception message: {0}{1}", Environment.NewLine, exception.Message); Assert.True(!shouldCallSucceed, errorBuilder.ToString()); } } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Root_Certificate_Installed))] [OuterLoop] public static void Certificate_With_CanonicalName_DomainName_Address_EchoString() { var domainNameEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_DomainName_Address); var endpointAddress = new EndpointAddress(domainNameEndpointUri); // We check that: // 1. The WCF service's reported hostname does not contain a '.' (which means we're hitting the FQDN) // 2. The WCF service's reported hostname is not "localhost" (which means we're hitting localhost) // If both these conditions are true, expect the test to pass. Otherwise, it should fail bool shouldCallSucceed = domainNameEndpointUri.Host.IndexOf('.') == -1 && string.Compare(domainNameEndpointUri.Host, "localhost", StringComparison.OrdinalIgnoreCase) != 0; string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; factory = new ChannelFactory<IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust; serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have failed but succeeded. ", domainNameEndpointUri.Host); errorBuilder.AppendFormat("This means that the certificate validation passed when it should have failed. "); errorBuilder.AppendFormat("Check the certificate returned by the endpoint at '{0}' ", domainNameEndpointUri); errorBuilder.AppendFormat("to see that it is correct; if it is, there is likely an issue with the identity checking logic."); Assert.True(shouldCallSucceed, errorBuilder.ToString()); } catch (Exception exception) when (exception is CommunicationException || exception is MessageSecurityException) { if ((exception is MessageSecurityException) || (exception is CommunicationException) && !string.Equals(exception.InnerException.GetType().ToString(), "System.ServiceModel.Security.MessageSecurityException")) { // If there's a MessageSecurityException, we assume that the cert validation failed. Unfortunately checking for the // message is really brittle and we can't account for loc and how .NET Native will display the exceptions // The exception message should look like: // // System.ServiceModel.Security.MessageSecurityException : Identity check failed for outgoing message. The expected // DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'example.com'.If this // is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'example.com' as // the Identity property of EndpointAddress when creating channel proxy. var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have been successful but failed with a MessageSecurityException. ", domainNameEndpointUri.Host); errorBuilder.AppendFormat("This usually means that the certificate validation failed when it should have passed. "); errorBuilder.AppendFormat("When connecting to host '{0}', the expectation is that the DNSClaim will be for the same hostname. ", domainNameEndpointUri.Host); errorBuilder.AppendFormat("Exception message: {0}{1}", Environment.NewLine, exception.Message); Assert.True(!shouldCallSucceed, errorBuilder.ToString()); } } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Root_Certificate_Installed))] [OuterLoop] public static void Certificate_With_CanonicalName_Fqdn_Address_EchoString() { bool shouldCallSucceed = false; var domainNameEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_DomainName_Address); // Get just the hostname part of the domainName Uri var domainNameHost = domainNameEndpointUri.Host.Split('.')[0]; var fqdnEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_Fqdn_Address); var endpointAddress = new EndpointAddress(fqdnEndpointUri); // If the WCF service's reported FQDN is the same as the services's reported hostname, // it means that there the WCF service is set up on a network where FQDNs aren't used, only hostnames. // Since our pass/fail detection logic on whether or not this is an FQDN depends on whether the host name has a '.', we don't test this case if (string.Compare(domainNameHost, fqdnEndpointUri.Host, StringComparison.OrdinalIgnoreCase) != 0) { shouldCallSucceed = fqdnEndpointUri.Host.IndexOf('.') > -1; } string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; factory = new ChannelFactory<IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust; serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have failed but succeeded. ", fqdnEndpointUri.Host); errorBuilder.AppendFormat("This means that the certificate validation passed when it should have failed. "); errorBuilder.AppendFormat("Check the certificate returned by the endpoint at '{0}' ", fqdnEndpointUri); errorBuilder.AppendFormat("to see that it is correct; if it is, there is likely an issue with the identity checking logic."); Assert.True(shouldCallSucceed, errorBuilder.ToString()); } catch (MessageSecurityException exception) { // If there's a MessageSecurityException, we assume that the cert validation failed. Unfortunately checking for the // message is really brittle and we can't account for loc and how .NET Native will display the exceptions // The exception message should look like: // // System.ServiceModel.Security.MessageSecurityException : Identity check failed for outgoing message. The expected // DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'example.com'.If this // is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'example.com' as // the Identity property of EndpointAddress when creating channel proxy. var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have been successful but failed with a MessageSecurityException. ", fqdnEndpointUri.Host); errorBuilder.AppendFormat("This usually means that the certificate validation failed when it should have passed. "); errorBuilder.AppendFormat("When connecting to host '{0}', the expectation is that the DNSClaim will be for the same hostname. ", fqdnEndpointUri.Host); errorBuilder.AppendFormat("Exception message: {0}{1}", Environment.NewLine, exception.Message); Assert.True(!shouldCallSucceed, errorBuilder.ToString()); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } }
using System; using System.IO; namespace StegoPrint { public class WaveStream : Stream, IDisposable { private Stream m_Stream; private long m_DataPos; private int m_Length; private WaveFormat m_Format; public WaveFormat Format { get { return m_Format; } } private string ReadChunk (BinaryReader reader) { byte[] ch = new byte[4]; reader.Read (ch, 0, ch.Length); return System.Text.Encoding.ASCII.GetString (ch); } private void ReadHeader () { BinaryReader Reader = new BinaryReader (m_Stream); if (ReadChunk (Reader) != "RIFF") throw new Exception ("Invalid file format"); Reader.ReadInt32 (); // File length minus first 8 bytes of RIFF description, we don't use it if (ReadChunk (Reader) != "WAVE") throw new Exception ("Invalid file format"); if (ReadChunk (Reader) != "fmt ") throw new Exception ("Invalid file format"); int len = Reader.ReadInt32 (); if (len < 16) // bad format chunk length throw new Exception ("Invalid file format"); m_Format = new WaveFormat (22050, 16, 2); // initialize to any format m_Format.wFormatTag = Reader.ReadInt16 (); m_Format.nChannels = Reader.ReadInt16 (); m_Format.nSamplesPerSec = Reader.ReadInt32 (); m_Format.nAvgBytesPerSec = Reader.ReadInt32 (); m_Format.nBlockAlign = Reader.ReadInt16 (); m_Format.wBitsPerSample = Reader.ReadInt16 (); // advance in the stream to skip the wave format block len -= 16; // minimum format size while (len > 0) { Reader.ReadByte (); len--; } // assume the data chunk is aligned while (m_Stream.Position < m_Stream.Length && ReadChunk (Reader) != "data") ; if (m_Stream.Position >= m_Stream.Length) throw new Exception ("Invalid file format"); m_Length = Reader.ReadInt32 (); m_DataPos = m_Stream.Position; Position = 0; } /// <summary>ReadChunk(reader) - Changed to CopyChunk(reader, writer)</summary> /// <param name="reader">source stream</param> /// <returns>four characters</returns> private string CopyChunk (BinaryReader reader, BinaryWriter writer) { byte[] ch = new byte[4]; reader.Read (ch, 0, ch.Length); //copy the chunk writer.Write (ch); return System.Text.Encoding.ASCII.GetString (ch); } /// <summary>ReadHeader() - Changed to CopyHeader(destination)</summary> private void CopyHeader (Stream destinationStream) { BinaryReader reader = new BinaryReader (m_Stream); BinaryWriter writer = new BinaryWriter (destinationStream); if (CopyChunk (reader, writer) != "RIFF") throw new Exception ("Invalid file format"); writer.Write (reader.ReadInt32 ()); // File length minus first 8 bytes of RIFF description if (CopyChunk (reader, writer) != "WAVE") throw new Exception ("Invalid file format"); if (CopyChunk (reader, writer) != "fmt ") throw new Exception ("Invalid file format"); int len = reader.ReadInt32 (); if (len < 16) { // bad format chunk length throw new Exception ("Invalid file format"); } else { writer.Write (len); } m_Format = new WaveFormat (22050, 16, 2); // initialize to any format m_Format.wFormatTag = reader.ReadInt16 (); m_Format.nChannels = reader.ReadInt16 (); m_Format.nSamplesPerSec = reader.ReadInt32 (); m_Format.nAvgBytesPerSec = reader.ReadInt32 (); m_Format.nBlockAlign = reader.ReadInt16 (); m_Format.wBitsPerSample = reader.ReadInt16 (); //copy format information writer.Write (m_Format.wFormatTag); writer.Write (m_Format.nChannels); writer.Write (m_Format.nSamplesPerSec); writer.Write (m_Format.nAvgBytesPerSec); writer.Write (m_Format.nBlockAlign); writer.Write (m_Format.wBitsPerSample); // advance in the stream to skip the wave format block len -= 16; // minimum format size writer.Write (reader.ReadBytes (len)); len = 0; /*while (len > 0) { reader.ReadByte(); len--; }*/ // assume the data chunk is aligned while (m_Stream.Position < m_Stream.Length && CopyChunk (reader, writer) != "data") ; if (m_Stream.Position >= m_Stream.Length) throw new Exception ("Invalid file format"); m_Length = reader.ReadInt32 (); writer.Write (m_Length); m_DataPos = m_Stream.Position; Position = 0; } /// <summary>Write a new header</summary> public static Stream CreateStream (Stream waveData, WaveFormat format) { MemoryStream stream = new MemoryStream (); BinaryWriter writer = new BinaryWriter (stream); writer.Write (System.Text.Encoding.ASCII.GetBytes ("RIFF".ToCharArray ())); writer.Write ((Int32) (waveData.Length + 36)); //File length minus first 8 bytes of RIFF description writer.Write (System.Text.Encoding.ASCII.GetBytes ("WAVEfmt ".ToCharArray ())); writer.Write ((Int32) 16); //length of following chunk: 16 writer.Write ((Int16) format.wFormatTag); writer.Write ((Int16) format.nChannels); writer.Write ((Int32) format.nSamplesPerSec); writer.Write ((Int32) format.nAvgBytesPerSec); writer.Write ((Int16) format.nBlockAlign); writer.Write ((Int16) format.wBitsPerSample); writer.Write (System.Text.Encoding.ASCII.GetBytes ("data".ToCharArray ())); writer.Write ((Int32) waveData.Length); waveData.Seek (0, SeekOrigin.Begin); byte[] b = new byte[waveData.Length]; waveData.Read (b, 0, (int) waveData.Length); writer.Write (b); writer.Seek (0, SeekOrigin.Begin); return stream; } public WaveStream (Stream sourceStream, Stream destinationStream) { m_Stream = sourceStream; CopyHeader (destinationStream); } public WaveStream (Stream sourceStream) { m_Stream = sourceStream; ReadHeader (); } ~WaveStream () { Dispose (); } public new void Dispose () { base.Dispose (); GC.SuppressFinalize (this); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return false; } } public override long Length { get { return m_Length; } } /// <summary>Length of the data (in samples)</summary> public long CountSamples { get { return (long) ((m_Length - m_DataPos) / (m_Format.wBitsPerSample / 8)); } } public override long Position { get { return m_Stream.Position - m_DataPos; } set { Seek (value, SeekOrigin.Begin); } } public override void Flush () { } public override void SetLength (long len) { throw new InvalidOperationException (); } public override long Seek (long pos, SeekOrigin o) { switch (o) { case SeekOrigin.Begin: m_Stream.Position = pos + m_DataPos; break; case SeekOrigin.Current: m_Stream.Seek (pos, SeekOrigin.Current); break; case SeekOrigin.End: m_Stream.Position = m_DataPos + m_Length - pos; break; } return this.Position; } public override int Read (byte[] buf, int ofs, int count) { int toread = (int) Math.Min (count, m_Length - Position); return m_Stream.Read (buf, ofs, toread); } /// <summary>Read - Changed to Copy</summary> /// <param name="buf">Buffer to receive the data</param> /// <param name="ofs">Offset</param> /// <param name="count">Count of bytes to read</param> /// <param name="destination">Where to copy the buffer</param> /// <returns>Count of bytes actually read</returns> public int Copy (byte[] buf, int ofs, int count, Stream destination) { int toread = (int) Math.Min (count, m_Length - Position); int read = m_Stream.Read (buf, ofs, toread); destination.Write (buf, ofs, read); if (m_Stream.Position != destination.Position) { Console.WriteLine (); } return read; } public override void Write (byte[] buf, int ofs, int count) { throw new InvalidOperationException (); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Storage { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// StorageAccountsOperations operations. /// </summary> public partial interface IStorageAccountsOperations { /// <summary> /// Checks that account name is valid and is not in use. /// </summary> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<CheckNameAvailabilityResult>> CheckNameAvailabilityWithHttpMessagesAsync(StorageAccountCheckNameAvailabilityParameters accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Asynchronously creates a new storage account with the specified /// parameters. Existing accounts cannot be updated with this API and /// should instead use the Update Storage Account API. If an account is /// already created and subsequent PUT request is issued with exact /// same set of properties, then HTTP 200 would be returned. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccount>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the properties for the specified storage account including /// but not limited to name, account type, location, and account /// status. The ListKeys operation should be used to retrieve storage /// keys. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccount>> GetPropertiesWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates the account type or tags for a storage account. It can also /// be used to add a custom domain (note that custom domains cannot be /// added via the Create operation). Only one custom domain is /// supported per storage account. In order to replace a custom domain, /// the old value must be cleared before a new value may be set. To /// clear a custom domain, simply update the custom domain with empty /// string. Then call update again with the new cutsom domain name. The /// update API can only be used to update one of tags, accountType, or /// customDomain per call. To update multiple of these properties, call /// the API multiple times with one change per call. This call does not /// change the storage keys for the account. If you want to change /// storage account keys, use the RegenerateKey operation. The location /// and name of the storage account cannot be changed after creation. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to update on the account. Note that only one /// property can be changed at a time using this API. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the storage account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccountKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the storage accounts available under the subscription. /// Note that storage keys are not returned; use the ListKeys operation /// for this. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<StorageAccount>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the storage accounts available under the given resource /// group. Note that storage keys are not returned; use the ListKeys /// operation for this. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<StorageAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the access keys for the specified storage account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='regenerateKey'> /// Specifies name of the key which should be regenerated. key1 or key2 /// for the default keys /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccountKeys>> RegenerateKeyWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Asynchronously creates a new storage account with the specified /// parameters. Existing accounts cannot be updated with this API and /// should instead use the Update Storage Account API. If an account is /// already created and subsequent PUT request is issued with exact /// same set of properties, then HTTP 200 would be returned. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccount>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ActionConstraints; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.Extensions.Options; using Xunit; namespace Microsoft.AspNetCore.Mvc.ApplicationModels { public class DefaultApplicationModelProviderTest { private readonly TestApplicationModelProvider Provider = new TestApplicationModelProvider(); [Fact] public void OnProvidersExecuting_AddsGlobalFilters() { // Arrange var options = new MvcOptions() { Filters = { new MyFilterAttribute(), }, }; var builder = new TestApplicationModelProvider(options, TestModelMetadataProvider.CreateDefaultProvider()); var context = new ApplicationModelProviderContext(Array.Empty<TypeInfo>()); // Act builder.OnProvidersExecuting(context); // Assert Assert.Equal(options.Filters.ToArray(), context.Result.Filters); } [Fact] public void OnProvidersExecuting_IncludesAllControllers() { // Arrange var builder = new TestApplicationModelProvider(); var context = new ApplicationModelProviderContext(new[] { typeof(ModelBinderController).GetTypeInfo(), typeof(ConventionallyRoutedController).GetTypeInfo() }); // Act builder.OnProvidersExecuting(context); // Assert Assert.Collection( context.Result.Controllers.OrderBy(c => c.ControllerType.Name), c => Assert.Equal(typeof(ConventionallyRoutedController).GetTypeInfo(), c.ControllerType), c => Assert.Equal(typeof(ModelBinderController).GetTypeInfo(), c.ControllerType)); } [Fact] public void OnProvidersExecuting_AddsControllerProperties() { // Arrange var builder = new TestApplicationModelProvider( new MvcOptions(), TestModelMetadataProvider.CreateDefaultProvider()); var typeInfo = typeof(ModelBinderController).GetTypeInfo(); var context = new ApplicationModelProviderContext(new[] { typeInfo }); // Act builder.OnProvidersExecuting(context); // Assert var controllerModel = Assert.Single(context.Result.Controllers); Assert.Collection( controllerModel.ControllerProperties.OrderBy(p => p.PropertyName), property => { Assert.Equal(nameof(ModelBinderController.Bound), property.PropertyName); Assert.Equal(BindingSource.Query, property.BindingInfo.BindingSource); Assert.Same(controllerModel, property.Controller); var attribute = Assert.Single(property.Attributes); Assert.IsType<FromQueryAttribute>(attribute); }, property => { Assert.Equal(nameof(ModelBinderController.FormFile), property.PropertyName); Assert.Equal(BindingSource.FormFile, property.BindingInfo.BindingSource); Assert.Same(controllerModel, property.Controller); Assert.Empty(property.Attributes); }, property => { Assert.Equal(nameof(ModelBinderController.Unbound), property.PropertyName); Assert.Null(property.BindingInfo); Assert.Same(controllerModel, property.Controller); }); } [Fact] public void OnProvidersExecuting_ReadsBindingSourceForPropertiesFromModelMetadata() { // Arrange var detailsProvider = new BindingSourceMetadataProvider(typeof(string), BindingSource.Services); var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider(new[] { detailsProvider }); var typeInfo = typeof(ModelBinderController).GetTypeInfo(); var provider = new TestApplicationModelProvider(new MvcOptions(), modelMetadataProvider); var context = new ApplicationModelProviderContext(new[] { typeInfo }); // Act provider.OnProvidersExecuting(context); // Assert var controllerModel = Assert.Single(context.Result.Controllers); Assert.Collection( controllerModel.ControllerProperties.OrderBy(p => p.PropertyName), property => { Assert.Equal(nameof(ModelBinderController.Bound), property.PropertyName); Assert.Equal(BindingSource.Query, property.BindingInfo.BindingSource); Assert.Same(controllerModel, property.Controller); var attribute = Assert.Single(property.Attributes); Assert.IsType<FromQueryAttribute>(attribute); }, property => { Assert.Equal(nameof(ModelBinderController.FormFile), property.PropertyName); Assert.Equal(BindingSource.FormFile, property.BindingInfo.BindingSource); Assert.Same(controllerModel, property.Controller); Assert.Empty(property.Attributes); }, property => { Assert.Equal(nameof(ModelBinderController.Unbound), property.PropertyName); Assert.Equal(BindingSource.Services, property.BindingInfo.BindingSource); Assert.Same(controllerModel, property.Controller); }); } [Fact] public void OnProvidersExecuting_AddsBindingSources_ForActionParameters() { // Arrange var builder = new TestApplicationModelProvider( new MvcOptions(), TestModelMetadataProvider.CreateDefaultProvider()); var typeInfo = typeof(ModelBinderController).GetTypeInfo(); var context = new ApplicationModelProviderContext(new[] { typeInfo }); // Act builder.OnProvidersExecuting(context); // Assert var controllerModel = Assert.Single(context.Result.Controllers); var action = Assert.Single(controllerModel.Actions, a => a.ActionMethod.Name == nameof(ModelBinderController.PostAction)); Assert.Collection( action.Parameters, parameter => { Assert.Equal("fromQuery", parameter.ParameterName); Assert.Equal(BindingSource.Query, parameter.BindingInfo.BindingSource); Assert.Same(action, parameter.Action); var attribute = Assert.Single(parameter.Attributes); Assert.IsType<FromQueryAttribute>(attribute); }, parameter => { Assert.Equal("formFileCollection", parameter.ParameterName); Assert.Equal(BindingSource.FormFile, parameter.BindingInfo.BindingSource); Assert.Same(action, parameter.Action); Assert.Empty(parameter.Attributes); }, parameter => { Assert.Equal("unbound", parameter.ParameterName); Assert.Null(parameter.BindingInfo); Assert.Same(action, parameter.Action); }); } [Fact] public void OnProvidersExecuting_InfersFormFileSourceForTypesAssignableFromIEnumerableOfFormFiles() { // Arrange var builder = new TestApplicationModelProvider( new MvcOptions(), TestModelMetadataProvider.CreateDefaultProvider()); var typeInfo = typeof(ModelBinderController).GetTypeInfo(); var context = new ApplicationModelProviderContext(new[] { typeInfo }); // Act builder.OnProvidersExecuting(context); // Assert var controllerModel = Assert.Single(context.Result.Controllers); var action = Assert.Single(controllerModel.Actions, a => a.ActionMethod.Name == nameof(ModelBinderController.FormFilesSequences)); Assert.Collection( action.Parameters, parameter => { Assert.Equal("formFileEnumerable", parameter.ParameterName); Assert.Equal(BindingSource.FormFile, parameter.BindingInfo.BindingSource); }, parameter => { Assert.Equal("formFileCollection", parameter.ParameterName); Assert.Equal(BindingSource.FormFile, parameter.BindingInfo.BindingSource); }, parameter => { Assert.Equal("formFileIList", parameter.ParameterName); Assert.Equal(BindingSource.FormFile, parameter.BindingInfo.BindingSource); }, parameter => { Assert.Equal("formFileList", parameter.ParameterName); Assert.Equal(BindingSource.FormFile, parameter.BindingInfo.BindingSource); }, parameter => { Assert.Equal("formFileArray", parameter.ParameterName); Assert.Equal(BindingSource.FormFile, parameter.BindingInfo.BindingSource); }); } [Fact] public void OnProvidersExecuting_AddsBindingSources_ForActionParameters_ReadFromModelMetadata() { // Arrange var options = new MvcOptions(); var detailsProvider = new BindingSourceMetadataProvider(typeof(Guid), BindingSource.Special); var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider(new[] { detailsProvider }); var provider = new TestApplicationModelProvider(options, modelMetadataProvider); var typeInfo = typeof(ModelBinderController).GetTypeInfo(); var context = new ApplicationModelProviderContext(new[] { typeInfo }); // Act provider.OnProvidersExecuting(context); // Assert var controllerModel = Assert.Single(context.Result.Controllers); var action = Assert.Single(controllerModel.Actions, a => a.ActionName == nameof(ModelBinderController.PostAction1)); Assert.Collection( action.Parameters, parameter => { Assert.Equal("guid", parameter.ParameterName); Assert.Equal(BindingSource.Special, parameter.BindingInfo.BindingSource); }); } [Fact] public void OnProvidersExecuting_UsesBindingSourceSpecifiedOnParameter() { // Arrange var options = new MvcOptions(); var detailsProvider = new BindingSourceMetadataProvider(typeof(Guid), BindingSource.Special); var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider(new[] { detailsProvider }); var provider = new TestApplicationModelProvider(options, modelMetadataProvider); var typeInfo = typeof(ModelBinderController).GetTypeInfo(); var context = new ApplicationModelProviderContext(new[] { typeInfo }); // Act provider.OnProvidersExecuting(context); // Assert var controllerModel = Assert.Single(context.Result.Controllers); var action = Assert.Single(controllerModel.Actions, a => a.ActionName == nameof(ModelBinderController.PostAction2)); Assert.Collection( action.Parameters, parameter => { Assert.Equal("fromQuery", parameter.ParameterName); Assert.Equal(BindingSource.Query, parameter.BindingInfo.BindingSource); }); } [Fact] public void OnProvidersExecuting_RemovesAsyncSuffix_WhenOptionIsSet() { // Arrange var options = new MvcOptions(); var provider = new TestApplicationModelProvider(options, new EmptyModelMetadataProvider()); var typeInfo = typeof(AsyncActionController).GetTypeInfo(); var methodInfo = typeInfo.GetMethod(nameof(AsyncActionController.GetPersonAsync)); var context = new ApplicationModelProviderContext(new[] { typeInfo }); // Act provider.OnProvidersExecuting(context); // Assert var controllerModel = Assert.Single(context.Result.Controllers); var action = Assert.Single(controllerModel.Actions, a => a.ActionMethod == methodInfo); Assert.Equal("GetPerson", action.ActionName); } [Fact] public void OnProvidersExecuting_DoesNotRemoveAsyncSuffix_WhenOptionIsDisabled() { // Arrange var options = new MvcOptions { SuppressAsyncSuffixInActionNames = false }; var provider = new TestApplicationModelProvider(options, new EmptyModelMetadataProvider()); var typeInfo = typeof(AsyncActionController).GetTypeInfo(); var methodInfo = typeInfo.GetMethod(nameof(AsyncActionController.GetPersonAsync)); var context = new ApplicationModelProviderContext(new[] { typeInfo }); // Act provider.OnProvidersExecuting(context); // Assert var controllerModel = Assert.Single(context.Result.Controllers); var action = Assert.Single(controllerModel.Actions, a => a.ActionMethod == methodInfo); Assert.Equal(nameof(AsyncActionController.GetPersonAsync), action.ActionName); } [Fact] public void OnProvidersExecuting_DoesNotRemoveAsyncSuffix_WhenActionNameIsSpecifiedUsingActionNameAttribute() { // Arrange var options = new MvcOptions(); var provider = new TestApplicationModelProvider(options, new EmptyModelMetadataProvider()); var typeInfo = typeof(AsyncActionController).GetTypeInfo(); var methodInfo = typeInfo.GetMethod(nameof(AsyncActionController.GetAddressAsync)); var context = new ApplicationModelProviderContext(new[] { typeInfo }); // Act provider.OnProvidersExecuting(context); // Assert var controllerModel = Assert.Single(context.Result.Controllers); var action = Assert.Single(controllerModel.Actions, a => a.ActionMethod == methodInfo); Assert.Equal("GetRealAddressAsync", action.ActionName); } [Fact] public void CreateControllerModel_DerivedFromControllerClass_HasFilter() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(StoreController).GetTypeInfo(); // Act var model = builder.CreateControllerModel(typeInfo); // Assert var filter = Assert.Single(model.Filters); Assert.IsType<ControllerActionFilter>(filter); } // This class has a filter attribute, but doesn't implement any filter interfaces, // so ControllerFilter is not present. [Fact] public void CreateControllerModel_ClassWithoutFilterInterfaces_HasNoControllerFilter() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(NoFiltersController).GetTypeInfo(); // Act var model = builder.CreateControllerModel(typeInfo); // Assert var filter = Assert.Single(model.Filters); Assert.IsType<MyFilterAttribute>(filter); } [Fact] public void CreateControllerModel_ClassWithFilterInterfaces_HasFilter() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(SomeFiltersController).GetTypeInfo(); // Act var model = builder.CreateControllerModel(typeInfo); // Assert Assert.Single(model.Filters, f => f is ControllerActionFilter); Assert.Single(model.Filters, f => f is ControllerResultFilter); } [Fact] public void CreateControllerModel_ClassWithFilterInterfaces_UnsupportedType() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(UnsupportedFiltersController).GetTypeInfo(); // Act var model = builder.CreateControllerModel(typeInfo); // Assert Assert.Empty(model.Filters); } [Fact] public void CreateControllerModel_ClassWithInheritedRoutes() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(DerivedClassInheritingRoutesController).GetTypeInfo(); // Act var model = builder.CreateControllerModel(typeInfo); // Assert var attributeRoutes = GetAttributeRoutes(model.Selectors); Assert.Equal(2, attributeRoutes.Count); Assert.Equal(2, model.Attributes.Count); var route = Assert.Single(attributeRoutes, r => r.Template == "A"); Assert.Contains(route.Attribute, model.Attributes); route = Assert.Single(attributeRoutes, r => r.Template == "B"); Assert.Contains(route.Attribute, model.Attributes); } [Fact] public void CreateControllerModel_ClassWithHiddenInheritedRoutes() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(DerivedClassHidingRoutesController).GetTypeInfo(); // Act var model = builder.CreateControllerModel(typeInfo); // Assert var attributeRoutes = GetAttributeRoutes(model.Selectors); Assert.Equal(2, attributeRoutes.Count); Assert.Equal(2, model.Attributes.Count); var route = Assert.Single(attributeRoutes, r => r.Template == "C"); Assert.Contains(route.Attribute, model.Attributes); route = Assert.Single(attributeRoutes, r => r.Template == "D"); Assert.Contains(route.Attribute, model.Attributes); } [Theory] [InlineData("GetFromDerived", true)] [InlineData("NewMethod", true)] // "NewMethod" is a public method declared with keyword "new". [InlineData("GetFromBase", true)] public void IsAction_WithInheritedMethods(string methodName, bool expected) { // Arrange var builder = new TestApplicationModelProvider(); var method = typeof(DerivedController).GetMethod(methodName); Assert.NotNull(method); // Act var isValid = builder.IsAction(typeof(DerivedController).GetTypeInfo(), method); // Assert Assert.Equal(expected, isValid); } [Fact] public void IsAction_OverridenMethodControllerClass() { // Arrange var builder = new TestApplicationModelProvider(); var method = typeof(BaseController).GetMethod(nameof(BaseController.Redirect)); Assert.NotNull(method); // Act var isValid = builder.IsAction(typeof(BaseController).GetTypeInfo(), method); // Assert Assert.False(isValid); } [Fact] public void IsAction_PrivateMethod_FromUserDefinedController() { // Arrange var builder = new TestApplicationModelProvider(); var method = typeof(DerivedController).GetMethod( "PrivateMethod", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); Assert.NotNull(method); // Act var isValid = builder.IsAction(typeof(DerivedController).GetTypeInfo(), method); // Assert Assert.False(isValid); } [Fact] public void IsAction_OperatorOverloadingMethod_FromOperatorOverloadingController() { // Arrange var builder = new TestApplicationModelProvider(); var method = typeof(OperatorOverloadingController).GetMethod("op_Addition"); Assert.NotNull(method); Assert.True(method.IsSpecialName); // Act var isValid = builder.IsAction(typeof(OperatorOverloadingController).GetTypeInfo(), method); // Assert Assert.False(isValid); } [Fact] public void IsAction_GenericMethod_FromUserDefinedController() { // Arrange var builder = new TestApplicationModelProvider(); var method = typeof(DerivedController).GetMethod("GenericMethod"); Assert.NotNull(method); // Act var isValid = builder.IsAction(typeof(DerivedController).GetTypeInfo(), method); // Assert Assert.False(isValid); } [Fact] public void IsAction_OverridenNonActionMethod() { // Arrange var builder = new TestApplicationModelProvider(); var method = typeof(DerivedController).GetMethod("OverridenNonActionMethod"); Assert.NotNull(method); // Act var isValid = builder.IsAction(typeof(DerivedController).GetTypeInfo(), method); // Assert Assert.False(isValid); } [Theory] [InlineData("Equals")] [InlineData("GetHashCode")] [InlineData("MemberwiseClone")] [InlineData("ToString")] public void IsAction_OverriddenMethodsFromObjectClass(string methodName) { // Arrange var builder = new TestApplicationModelProvider(); var method = typeof(DerivedController).GetMethod( methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); Assert.NotNull(method); // Act var isValid = builder.IsAction(typeof(DerivedController).GetTypeInfo(), method); // Assert Assert.False(isValid); } [Fact] public void IsAction_DerivedControllerIDisposableDisposeMethod() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(DerivedController).GetTypeInfo(); var methodInfo = typeInfo.GetRuntimeInterfaceMap(typeof(IDisposable)).TargetMethods[0]; var method = typeInfo.AsType().GetMethods().SingleOrDefault(m => (m == methodInfo)); Assert.NotNull(method); // Act var isValid = builder.IsAction(typeInfo, method); // Assert Assert.False(isValid); } [Fact] public void IsAction_DerivedControllerDisposeMethod() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(DerivedController).GetTypeInfo(); var methodInfo = typeInfo.GetRuntimeInterfaceMap(typeof(IDisposable)).TargetMethods[0]; var methods = typeInfo.AsType().GetMethods().Where(m => m.Name.Equals("Dispose") && m != methodInfo); Assert.NotEmpty(methods); foreach (var method in methods) { // Act var isValid = builder.IsAction(typeInfo, method); // Assert Assert.True(isValid); } } [Fact] public void IsAction_OverriddenDisposeMethod() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(DerivedOverriddenDisposeController).GetTypeInfo(); var method = typeInfo.GetDeclaredMethods("Dispose").SingleOrDefault(); Assert.NotNull(method); // Act var isValid = builder.IsAction(typeInfo, method); // Assert Assert.False(isValid); } [Fact] public void IsAction_NewDisposeMethod() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(DerivedNewDisposeController).GetTypeInfo(); var method = typeInfo.GetDeclaredMethods("Dispose").SingleOrDefault(); Assert.NotNull(method); // Act var isValid = builder.IsAction(typeInfo, method); // Assert Assert.True(isValid); } [Fact] public void IsAction_PocoControllerIDisposableDisposeMethod() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(IDisposablePocoController).GetTypeInfo(); var methodInfo = typeInfo.GetRuntimeInterfaceMap(typeof(IDisposable)).TargetMethods[0]; var method = typeInfo.AsType().GetMethods().SingleOrDefault(m => (m == methodInfo)); Assert.NotNull(method); // Act var isValid = builder.IsAction(typeInfo, method); // Assert Assert.False(isValid); } [Fact] public void IsAction_PocoControllerDisposeMethod() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(IDisposablePocoController).GetTypeInfo(); var methodInfo = typeInfo.GetRuntimeInterfaceMap(typeof(IDisposable)).TargetMethods[0]; var methods = typeInfo.AsType().GetMethods().Where(m => m.Name.Equals("Dispose") && m != methodInfo); Assert.NotEmpty(methods); foreach (var method in methods) { // Act var isValid = builder.IsAction(typeInfo, method); // Assert Assert.True(isValid); } } [Fact] public void IsAction_SimplePocoControllerDisposeMethod() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(SimplePocoController).GetTypeInfo(); var methods = typeInfo.AsType().GetMethods().Where(m => m.Name.Equals("Dispose")); Assert.NotEmpty(methods); foreach (var method in methods) { // Act var isValid = builder.IsAction(typeInfo, method); // Assert Assert.True(isValid); } } [Theory] [InlineData("StaticMethod")] [InlineData("ProtectedStaticMethod")] [InlineData("PrivateStaticMethod")] public void IsAction_StaticMethods(string methodName) { // Arrange var builder = new TestApplicationModelProvider(); var method = typeof(DerivedController).GetMethod( methodName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); Assert.NotNull(method); // Act var isValid = builder.IsAction(typeof(DerivedController).GetTypeInfo(), method); // Assert Assert.False(isValid); } [Fact] public void CreateActionModel_ConventionallyRoutedAction_WithoutHttpConstraints() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(ConventionallyRoutedController).GetTypeInfo(); var actionName = nameof(ConventionallyRoutedController.Edit); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.NotNull(action); Assert.Equal(actionName, action.ActionName); Assert.Empty(action.Attributes); Assert.Single(action.Selectors); Assert.Empty(action.Selectors[0].ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Empty(GetAttributeRoutes(action.Selectors)); } [Fact] public void CreateActionModel_ConventionallyRoutedAction_WithHttpConstraints() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(ConventionallyRoutedController).GetTypeInfo(); var actionName = nameof(ConventionallyRoutedController.Update); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.NotNull(action); Assert.Single(action.Selectors); var methodConstraint = Assert.Single( action.Selectors[0].ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Contains("PUT", methodConstraint.HttpMethods); Assert.Contains("PATCH", methodConstraint.HttpMethods); Assert.Equal(actionName, action.ActionName); Assert.Empty(GetAttributeRoutes(action.Selectors)); Assert.IsType<CustomHttpMethodsAttribute>(Assert.Single(action.Attributes)); } [Fact] public void CreateActionModel_ConventionallyRoutedActionWithHttpConstraints_AndInvalidRouteTemplateProvider() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(ConventionallyRoutedController).GetTypeInfo(); var actionName = nameof(ConventionallyRoutedController.Delete); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.NotNull(action); Assert.Single(action.Selectors); var methodConstraint = Assert.Single( action.Selectors[0].ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Contains("DELETE", methodConstraint.HttpMethods); Assert.Contains("HEAD", methodConstraint.HttpMethods); Assert.Equal(actionName, action.ActionName); Assert.Empty(GetAttributeRoutes(action.Selectors)); Assert.Single(action.Attributes.OfType<HttpDeleteAttribute>()); Assert.Single(action.Attributes.OfType<HttpHeadAttribute>()); } [Fact] public void CreateActionModel_ConventionallyRoutedAction_WithMultipleHttpConstraints() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(ConventionallyRoutedController).GetTypeInfo(); var actionName = nameof(ConventionallyRoutedController.Details); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.NotNull(action); Assert.Single(action.Selectors); var methodConstraint = Assert.Single( action.Selectors[0].ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Contains("GET", methodConstraint.HttpMethods); Assert.Contains("POST", methodConstraint.HttpMethods); Assert.Contains("HEAD", methodConstraint.HttpMethods); Assert.Equal(actionName, action.ActionName); Assert.Empty(GetAttributeRoutes(action.Selectors)); } [Fact] public void CreateActionModel_ConventionallyRoutedAction_WithMultipleOverlappingHttpConstraints() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(ConventionallyRoutedController).GetTypeInfo(); var actionName = nameof(ConventionallyRoutedController.List); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.NotNull(action); Assert.Single(action.Selectors); var methodConstraint = Assert.Single( action.Selectors[0].ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Contains("GET", methodConstraint.HttpMethods); Assert.Contains("PUT", methodConstraint.HttpMethods); Assert.Contains("POST", methodConstraint.HttpMethods); Assert.Equal(actionName, action.ActionName); Assert.Empty(GetAttributeRoutes(action.Selectors)); } [Fact] public void CreateActionModel_AttributeRouteOnAction() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(NoRouteAttributeOnControllerController).GetTypeInfo(); var actionName = nameof(NoRouteAttributeOnControllerController.Edit); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.NotNull(action); Assert.Single(action.Selectors); var methodConstraint = Assert.Single( action.Selectors[0].ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Equal(actionName, action.ActionName); var httpMethod = Assert.Single(methodConstraint.HttpMethods); Assert.Equal("HEAD", httpMethod); var attributeRoute = Assert.Single(GetAttributeRoutes(action.Selectors)); Assert.Equal("Change", attributeRoute.Template); Assert.IsType<HttpHeadAttribute>(Assert.Single(action.Attributes)); } [Fact] public void CreateActionModel_AttributeRouteOnAction_RouteAttribute() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(NoRouteAttributeOnControllerController).GetTypeInfo(); var actionName = nameof(NoRouteAttributeOnControllerController.Update); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.NotNull(action); Assert.Single(action.Selectors); Assert.Empty(action.Selectors[0].ActionConstraints); Assert.Equal(actionName, action.ActionName); var attributeRoute = Assert.Single(GetAttributeRoutes(action.Selectors)); Assert.Equal("Update", attributeRoute.Template); Assert.IsType<RouteAttribute>(Assert.Single(action.Attributes)); } [Fact] public void CreateActionModel_AttributeRouteOnAction_AcceptVerbsAttributeWithTemplate() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(NoRouteAttributeOnControllerController).GetTypeInfo(); var actionName = nameof(NoRouteAttributeOnControllerController.List); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.NotNull(action); Assert.Single(action.Selectors); var methodConstraint = Assert.Single( action.Selectors[0].ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Equal(actionName, action.ActionName); Assert.Equal( new[] { "GET", "HEAD" }, methodConstraint.HttpMethods.OrderBy(m => m, StringComparer.Ordinal)); var attributeRoute = Assert.Single(GetAttributeRoutes(action.Selectors)); Assert.Equal("ListAll", attributeRoute.Template); Assert.IsType<AcceptVerbsAttribute>(Assert.Single(action.Attributes)); } [Fact] public void CreateActionModel_AttributeRouteOnAction_CreatesOneActionInfoPerRouteTemplate() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(NoRouteAttributeOnControllerController).GetTypeInfo(); var actionName = nameof(NoRouteAttributeOnControllerController.Index); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.NotNull(action); Assert.Equal(actionName, action.ActionName); Assert.NotNull(action.Attributes); Assert.Equal(2, action.Attributes.Count); Assert.Single(action.Attributes.OfType<HttpGetAttribute>()); Assert.Single(action.Attributes.OfType<HttpPostAttribute>()); Assert.Equal(2, action.Selectors.Count); foreach (var actionSelectorModel in action.Selectors) { Assert.NotNull(actionSelectorModel.AttributeRouteModel); } var selectorModel = Assert.Single(action.Selectors, ai => ai.AttributeRouteModel?.Template == "List"); var methodConstraint = Assert.Single(selectorModel.ActionConstraints.OfType<HttpMethodActionConstraint>()); var listMethod = Assert.Single(methodConstraint.HttpMethods); Assert.Equal("POST", listMethod); var all = Assert.Single(action.Selectors, ai => ai.AttributeRouteModel?.Template == "All"); methodConstraint = Assert.Single(all.ActionConstraints.OfType<HttpMethodActionConstraint>()); var allMethod = Assert.Single(methodConstraint.HttpMethods); Assert.Equal("GET", allMethod); } [Fact] public void CreateActionModel_NoRouteOnController_AllowsConventionallyRoutedActions_OnTheSameController() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(NoRouteAttributeOnControllerController).GetTypeInfo(); var actionName = nameof(NoRouteAttributeOnControllerController.Remove); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.NotNull(action); Assert.Equal(actionName, action.ActionName); Assert.Empty(action.Attributes); Assert.Single(action.Selectors); Assert.Empty(action.Selectors[0].ActionConstraints); Assert.Null(action.Selectors[0].AttributeRouteModel); } [Theory] [InlineData(typeof(SingleRouteAttributeController))] [InlineData(typeof(MultipleRouteAttributeController))] public void CreateActionModel_RouteAttributeOnController_CreatesAttributeRoute_ForNonAttributedActions(Type controller) { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = controller.GetTypeInfo(); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod("Delete")); // Assert Assert.NotNull(action); Assert.Equal("Delete", action.ActionName); Assert.Single(action.Selectors); Assert.Empty(action.Selectors[0].ActionConstraints); Assert.Empty(GetAttributeRoutes(action.Selectors)); Assert.Empty(action.Attributes); } [Theory] [InlineData(typeof(SingleRouteAttributeController))] [InlineData(typeof(MultipleRouteAttributeController))] public void CreateActionModel_RouteOnController_CreatesOneActionInfoPerRouteTemplateOnAction(Type controller) { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = controller.GetTypeInfo(); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod("Index")); // Assert Assert.NotNull(action.Attributes); Assert.Equal(2, action.Attributes.Count); Assert.Equal(2, action.Selectors.Count); Assert.Equal("Index", action.ActionName); foreach (var selectorModel in action.Selectors) { var methodConstraint = Assert.Single(selectorModel.ActionConstraints.OfType<HttpMethodActionConstraint>()); var httpMethod = Assert.Single(methodConstraint.HttpMethods); Assert.Equal("GET", httpMethod); Assert.NotNull(selectorModel.AttributeRouteModel.Template); } Assert.Single(action.Selectors, ai => ai.AttributeRouteModel.Template.Equals("List")); Assert.Single(action.Selectors, ai => ai.AttributeRouteModel.Template.Equals("All")); } [Fact] public void CreateActionModel_MixedHttpVerbsAndRoutes_EmptyVerbWithRoute() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(MixedHttpVerbsAndRouteAttributeController).GetTypeInfo(); var actionName = nameof(MixedHttpVerbsAndRouteAttributeController.VerbAndRoute); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.NotNull(action); Assert.Single(action.Selectors); var methodConstraint = Assert.Single( action.Selectors[0].ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Equal<string>(new string[] { "GET" }, methodConstraint.HttpMethods); var attributeRoute = Assert.Single(GetAttributeRoutes(action.Selectors)); Assert.Equal("Products", attributeRoute.Template); } [Fact] public void CreateActionModel_MixedHttpVerbsAndRoutes_MultipleEmptyVerbsWithMultipleRoutes() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(MixedHttpVerbsAndRouteAttributeController).GetTypeInfo(); var actionName = nameof(MixedHttpVerbsAndRouteAttributeController.MultipleVerbsAndRoutes); // Act var actions = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.Equal(2, actions.Selectors.Count); // OrderBy is used because the order of the results may very depending on the platform / client. var selectorModel = Assert.Single(actions.Selectors, a => a.AttributeRouteModel.Template == "Products"); var methodConstraint = Assert.Single(selectorModel.ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Equal(new[] { "GET", "POST" }, methodConstraint.HttpMethods.OrderBy(key => key, StringComparer.Ordinal)); selectorModel = Assert.Single(actions.Selectors, a => a.AttributeRouteModel.Template == "v2/Products"); methodConstraint = Assert.Single(selectorModel.ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Equal(new[] { "GET", "POST" }, methodConstraint.HttpMethods.OrderBy(key => key, StringComparer.Ordinal)); } [Fact] public void CreateActionModel_MixedHttpVerbsAndRoutes_MultipleEmptyAndNonEmptyVerbsWithMultipleRoutes() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(MixedHttpVerbsAndRouteAttributeController).GetTypeInfo(); var actionName = nameof(MixedHttpVerbsAndRouteAttributeController.MultipleVerbsWithAnyWithoutTemplateAndRoutes); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.Equal(3, action.Selectors.Count); var selectorModel = Assert.Single(action.Selectors, s => s.AttributeRouteModel.Template == "Products"); var methodConstraint = Assert.Single(selectorModel.ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Equal<string>(new string[] { "GET" }, methodConstraint.HttpMethods); selectorModel = Assert.Single(action.Selectors, s => s.AttributeRouteModel.Template == "v2/Products"); methodConstraint = Assert.Single(selectorModel.ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Equal<string>(new string[] { "GET" }, methodConstraint.HttpMethods); selectorModel = Assert.Single(action.Selectors, s => s.AttributeRouteModel.Template == "Products/Buy"); methodConstraint = Assert.Single(selectorModel.ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Equal<string>(new string[] { "POST" }, methodConstraint.HttpMethods); } [Fact] public void CreateActionModel_MixedHttpVerbsAndRoutes_WithRouteOnController() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(RouteAttributeOnController).GetTypeInfo(); var actionName = nameof(RouteAttributeOnController.Get); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.Equal(2, action.Selectors.Count); var selectorModel = Assert.Single(action.Selectors, s => s.AttributeRouteModel == null); var methodConstraint = Assert.Single(selectorModel.ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Equal(new string[] { "GET" }, methodConstraint.HttpMethods); selectorModel = Assert.Single(action.Selectors, s => s.AttributeRouteModel?.Template == "id/{id?}"); methodConstraint = Assert.Single(selectorModel.ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Equal(new string[] { "GET" }, methodConstraint.HttpMethods); } [Fact] public void CreateActionModel_MixedHttpVerbsAndRoutes_MultipleEmptyAndNonEmptyVerbs() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(MixedHttpVerbsAndRouteAttributeController).GetTypeInfo(); var actionName = nameof(MixedHttpVerbsAndRouteAttributeController.Invalid); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.NotNull(action); Assert.Equal(2, action.Selectors.Count); var selectorModel = Assert.Single(action.Selectors, s => s.AttributeRouteModel?.Template == "Products"); var methodConstraint = Assert.Single(selectorModel.ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Equal<string>(new string[] { "POST" }, methodConstraint.HttpMethods); selectorModel = Assert.Single(action.Selectors, s => s.AttributeRouteModel?.Template == null); methodConstraint = Assert.Single(selectorModel.ActionConstraints.OfType<HttpMethodActionConstraint>()); Assert.Equal<string>(new string[] { "GET" }, methodConstraint.HttpMethods); } [Fact] public void CreateActionModel_SplitsConstraintsBasedOnRoute() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(MultipleRouteProviderOnActionController).GetTypeInfo(); var methodInfo = typeInfo.GetMethod(nameof(MultipleRouteProviderOnActionController.Edit)); // Act var actionModel = builder.CreateActionModel(typeInfo, methodInfo); // Assert Assert.Equal(3, actionModel.Attributes.Count); Assert.Equal(2, actionModel.Attributes.OfType<RouteAndConstraintAttribute>().Count()); Assert.Single(actionModel.Attributes.OfType<ConstraintAttribute>()); Assert.Equal(2, actionModel.Selectors.Count); var selectorModel = Assert.Single( actionModel.Selectors.Where(sm => sm.AttributeRouteModel?.Template == "R1")); Assert.Equal(2, selectorModel.ActionConstraints.Count); Assert.Single(selectorModel.ActionConstraints.OfType<RouteAndConstraintAttribute>()); Assert.Single(selectorModel.ActionConstraints.OfType<ConstraintAttribute>()); selectorModel = Assert.Single( actionModel.Selectors.Where(sm => sm.AttributeRouteModel?.Template == "R2")); Assert.Equal(2, selectorModel.ActionConstraints.Count); Assert.Single(selectorModel.ActionConstraints.OfType<RouteAndConstraintAttribute>()); Assert.Single(selectorModel.ActionConstraints.OfType<ConstraintAttribute>()); } [Fact] public void CreateActionModel_InheritedAttributeRoutes() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(DerivedClassInheritsAttributeRoutesController).GetTypeInfo(); var actionName = nameof(DerivedClassInheritsAttributeRoutesController.Edit); // Act var actions = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.Equal(2, actions.Attributes.Count); Assert.Equal(2, actions.Selectors.Count); var selectorModel = Assert.Single(actions.Selectors, a => a.AttributeRouteModel?.Template == "A"); Assert.Contains(selectorModel.AttributeRouteModel.Attribute, actions.Attributes); selectorModel = Assert.Single(actions.Selectors, a => a.AttributeRouteModel?.Template == "B"); Assert.Contains(selectorModel.AttributeRouteModel.Attribute, actions.Attributes); } [Fact] public void CreateActionModel_InheritedAttributeRoutesOverridden() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(DerivedClassOverridesAttributeRoutesController).GetTypeInfo(); var actionName = nameof(DerivedClassOverridesAttributeRoutesController.Edit); // Act var action = builder.CreateActionModel(typeInfo, typeInfo.AsType().GetMethod(actionName)); // Assert Assert.Equal(4, action.Attributes.Count); Assert.Equal(2, action.Selectors.Count); var selectorModel = Assert.Single(action.Selectors, a => a.AttributeRouteModel?.Template == "C"); Assert.Contains(selectorModel.AttributeRouteModel.Attribute, action.Attributes); selectorModel = Assert.Single(action.Selectors, a => a.AttributeRouteModel?.Template == "D"); Assert.Contains(selectorModel.AttributeRouteModel.Attribute, action.Attributes); } [Fact] public void ControllerDispose_ExplicitlyImplemented_IDisposableMethods_AreTreatedAs_NonActions() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(DerivedFromControllerAndExplicitIDisposableImplementationController).GetTypeInfo(); var context = new ApplicationModelProviderContext(new[] { typeInfo }); // Act builder.OnProvidersExecuting(context); // Assert var model = Assert.Single(context.Result.Controllers); Assert.Empty(model.Actions); } [Fact] public void ControllerDispose_MethodsNamedDispose_AreTreatedAsActions() { // Arrange var builder = new TestApplicationModelProvider(); var typeInfo = typeof(DerivedFromControllerAndHidesBaseDisposeMethodController).GetTypeInfo(); var context = new ApplicationModelProviderContext(new[] { typeInfo }); // Act builder.OnProvidersExecuting(context); // Assert var model = Assert.Single(context.Result.Controllers); var action = Assert.Single(model.Actions); // Make sure that the Dispose method is from the derived controller and not the base 'Controller' type Assert.Equal(typeInfo, action.ActionMethod.DeclaringType.GetTypeInfo()); } [BindProperties] public class BindPropertyController { public string Property { get; set; } [ModelBinder(typeof(ComplexObjectModelBinder))] public string BinderType { get; set; } [FromRoute] public string BinderSource { get; set; } } [Fact] public void CreatePropertyModel_AddsBindingInfoToProperty_IfDeclaringTypeHasBindPropertiesAttribute() { // Arrange var propertyInfo = typeof(BindPropertyController).GetProperty(nameof(BindPropertyController.Property)); // Act var property = Provider.CreatePropertyModel(propertyInfo); // Assert var bindingInfo = property.BindingInfo; Assert.NotNull(bindingInfo); Assert.Null(bindingInfo.BinderModelName); Assert.Null(bindingInfo.BinderType); Assert.Null(bindingInfo.BindingSource); Assert.Null(bindingInfo.PropertyFilterProvider); Assert.NotNull(bindingInfo.RequestPredicate); } [Fact] public void CreatePropertyModel_DoesNotSetBindingInfo_IfPropertySpecifiesBinderType() { // Arrange var propertyInfo = typeof(BindPropertyController).GetProperty(nameof(BindPropertyController.BinderType)); // Act var property = Provider.CreatePropertyModel(propertyInfo); // Assert var bindingInfo = property.BindingInfo; Assert.Same(typeof(ComplexObjectModelBinder), bindingInfo.BinderType); } [Fact] public void CreatePropertyModel_DoesNotSetBindingInfo_IfPropertySpecifiesBinderSource() { // Arrange var propertyInfo = typeof(BindPropertyController).GetProperty(nameof(BindPropertyController.BinderSource)); // Act var property = Provider.CreatePropertyModel(propertyInfo); // Assert var bindingInfo = property.BindingInfo; Assert.Null(bindingInfo.BinderType); Assert.Same(BindingSource.Path, property.BindingInfo.BindingSource); } public class DerivedFromBindPropertyController : BindPropertyController { public string DerivedProperty { get; set; } } [Fact] public void CreatePropertyModel_AppliesBindPropertyAttributeDeclaredOnBaseType() { // Arrange var propertyInfo = typeof(DerivedFromBindPropertyController).GetProperty( nameof(DerivedFromBindPropertyController.DerivedProperty)); // Act var property = Provider.CreatePropertyModel(propertyInfo); // Assert Assert.NotNull(property.BindingInfo); } [BindProperties] public class UserController : ControllerBase { public string DerivedProperty { get; set; } } [Fact] public void CreatePropertyModel_DoesNotApplyBindingInfoToPropertiesOnBaseType() { // This test ensures that applying BindPropertyAttribute on a user defined type does not cause properties on // Controller \ ControllerBase to be treated as model bound. // Arrange var derivedPropertyInfo = typeof(UserController).GetProperty(nameof(UserController.DerivedProperty)); var basePropertyInfo = typeof(UserController).GetProperty(nameof(ControllerBase.ControllerContext)); // Act var derivedProperty = Provider.CreatePropertyModel(derivedPropertyInfo); var baseProperty = Provider.CreatePropertyModel(basePropertyInfo); // Assert Assert.NotNull(derivedProperty.BindingInfo); Assert.Null(baseProperty.BindingInfo); } private IList<AttributeRouteModel> GetAttributeRoutes(IList<SelectorModel> selectors) { return selectors .Where(sm => sm.AttributeRouteModel != null) .Select(sm => sm.AttributeRouteModel) .ToList(); } private class DerivedFromControllerAndExplicitIDisposableImplementationController : ViewFeaturesController, IDisposable { void IDisposable.Dispose() { throw new NotImplementedException(); } } private class DerivedFromControllerAndHidesBaseDisposeMethodController : ViewFeaturesController { public new void Dispose() { throw new NotImplementedException(); } } private class ViewFeaturesController : ControllerBase, IDisposable { public virtual void Dispose() { } } private class BaseClassWithAttributeRoutesController { [Route("A")] [Route("B")] public virtual void Edit() { } } private class DerivedClassInheritsAttributeRoutesController : BaseClassWithAttributeRoutesController { public override void Edit() { } } private class DerivedClassOverridesAttributeRoutesController : BaseClassWithAttributeRoutesController { [Route("C")] [Route("D")] public override void Edit() { } } private class Controller : IDisposable { public void Dispose() { throw new NotImplementedException(); } [NonAction] public virtual IActionResult Redirect(string url) { return null; } } private class BaseController : Controller { public void GetFromBase() // Valid action method. { } [NonAction] public virtual void OverridenNonActionMethod() { } [NonAction] public virtual void NewMethod() { } public override IActionResult Redirect(string url) { return base.Redirect(url + "#RedirectOverride"); } } private class DerivedController : BaseController { public void GetFromDerived() // Valid action method. { } [HttpGet] public override void OverridenNonActionMethod() { } public new void NewMethod() // Valid action method. { } public void GenericMethod<T>() { } private void PrivateMethod() { } public static void StaticMethod() { } protected static void ProtectedStaticMethod() { } private static void PrivateStaticMethod() { } public string Dispose(string s) { return s; } public new void Dispose() { } } private class IDisposablePocoController : IDisposable { public string Index() { return "Hello world"; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } public string Dispose(string s) { return s; } } private class BaseClass : IDisposable { public virtual void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } } private class DerivedOverriddenDisposeController : BaseClass { public override void Dispose() { base.Dispose(); } } private class DerivedNewDisposeController : BaseClass { public new void Dispose() { base.Dispose(); } } private class SimplePocoController { public string Index() { return "Hello world"; } public void Dispose() { } public void Dispose(string s) { } } private class OperatorOverloadingController : Controller { public static OperatorOverloadingController operator +( OperatorOverloadingController c1, OperatorOverloadingController c2) { return new OperatorOverloadingController(); } } private class NoRouteAttributeOnControllerController : Controller { [HttpGet("All")] [HttpPost("List")] public void Index() { } [HttpHead("Change")] public void Edit() { } public void Remove() { } [Route("Update")] public void Update() { } [AcceptVerbs("GET", "HEAD", Route = "ListAll")] public void List() { } } [Route("Products")] private class SingleRouteAttributeController : Controller { [HttpGet("All")] [HttpGet("List")] public void Index() { } public void Delete() { } } [Route("Products")] [Route("Items")] private class MultipleRouteAttributeController : Controller { [HttpGet("All")] [HttpGet("List")] public void Index() { } public void Delete() { } } private class MixedHttpVerbsAndRouteAttributeController : Controller { // Should produce a single action constrained to GET [HttpGet] [Route("Products")] public void VerbAndRoute() { } // Should produce two actions constrained to GET,POST [HttpGet] [HttpPost] [Route("Products")] [Route("v2/Products")] public void MultipleVerbsAndRoutes() { } // Produces: // // Products - GET // v2/Products - GET // Products/Buy - POST [HttpGet] [Route("Products")] [Route("v2/Products")] [HttpPost("Products/Buy")] public void MultipleVerbsWithAnyWithoutTemplateAndRoutes() { } // Produces: // // (no route) - GET // Products - POST // // This is invalid, and will throw during the ADP construction phase. [HttpGet] [HttpPost("Products")] public void Invalid() { } } [Route("api/[controller]")] private class RouteAttributeOnController : Controller { [HttpGet] [HttpGet("id/{id?}")] public object Get(short? id) { return null; } [HttpDelete("{id}")] public object Delete(int id) { return null; } } // Here the constraints on the methods are acting as an IActionHttpMethodProvider and // not as an IRouteTemplateProvider given that there is no RouteAttribute // on the controller and the template for all the constraints on a method is null. private class ConventionallyRoutedController : Controller { public void Edit() { } [CustomHttpMethods("PUT", "PATCH")] public void Update() { } [HttpHead] [HttpDelete] public void Delete() { } [HttpPost] [HttpGet] [HttpHead] public void Details() { } [HttpGet] [HttpPut] [AcceptVerbs("GET", "POST")] public void List() { } } private class CustomHttpMethodsAttribute : Attribute, IActionHttpMethodProvider { private readonly string[] _methods; public CustomHttpMethodsAttribute(params string[] methods) { _methods = methods; } public IEnumerable<string> HttpMethods => _methods; } [Route("A")] [Route("B")] private class BaseClassWithRoutesController { } private class DerivedClassInheritingRoutesController : BaseClassWithRoutesController { } [Route("C")] [Route("D")] private class DerivedClassHidingRoutesController : BaseClassWithRoutesController { } private class StoreController : Controller, IActionFilter { public void OnActionExecuted(ActionExecutedContext context) { throw new NotImplementedException(); } public void OnActionExecuting(ActionExecutingContext context) { throw new NotImplementedException(); } } private class MyFilterAttribute : Attribute, IFilterMetadata { } [MyFilter] public class NoFiltersController { } public class ModelBinderController { [FromQuery] public string Bound { get; set; } public string Unbound { get; set; } public IFormFile FormFile { get; set; } public IActionResult PostAction([FromQuery] string fromQuery, IFormFileCollection formFileCollection, string unbound) => null; public IActionResult FormFilesSequences( IEnumerable<IFormFile> formFileEnumerable, ICollection<IFormFile> formFileCollection, IList<IFormFile> formFileIList, List<IFormFile> formFileList, IFormFile[] formFileArray) => null; public IActionResult PostAction1(Guid guid) => null; public IActionResult PostAction2([FromQuery] Guid fromQuery) => null; } public class SomeFiltersController : IAsyncActionFilter, IResultFilter { public Task OnActionExecutionAsync( ActionExecutingContext context, ActionExecutionDelegate next) { return null; } public void OnResultExecuted(ResultExecutedContext context) { } public void OnResultExecuting(ResultExecutingContext context) { } } private class UnsupportedFiltersController : IExceptionFilter, IAuthorizationFilter, IAsyncResourceFilter { public void OnAuthorization(AuthorizationFilterContext context) { throw new NotImplementedException(); } public void OnException(ExceptionContext context) { throw new NotImplementedException(); } public Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next) { throw new NotImplementedException(); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] private class RouteAndConstraintAttribute : Attribute, IActionConstraintMetadata, IRouteTemplateProvider { public RouteAndConstraintAttribute(string template) { Template = template; } public string Name { get; set; } public int? Order { get; set; } public string Template { get; private set; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] private class ConstraintAttribute : Attribute, IActionConstraintMetadata { } private class MultipleRouteProviderOnActionController { [Constraint] [RouteAndConstraint("R1")] [RouteAndConstraint("R2")] public void Edit() { } } private class AsyncActionController : Controller { public Task<IActionResult> GetPersonAsync() => null; [ActionName("GetRealAddressAsync")] public Task<IActionResult> GetAddressAsync() => null; } private class TestApplicationModelProvider : DefaultApplicationModelProvider { public TestApplicationModelProvider() : this(new MvcOptions(), new EmptyModelMetadataProvider()) { } public TestApplicationModelProvider( MvcOptions options, IModelMetadataProvider modelMetadataProvider) : base(Options.Create(options), modelMetadataProvider) { } } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace DiscUtils.Diagnostics { /// <summary> /// Stream wrapper that traces all read and write activity. /// </summary> public sealed class TracingStream : Stream { private Stream _wrapped; private Ownership _ownsWrapped; private List<StreamTraceRecord> _records; private bool _active; private bool _captureStack; private bool _captureStackFileDetails = false; private bool _traceReads; private bool _traceWrites = true; private StreamWriter _fileOut; /// <summary> /// Creates a new instance, wrapping an existing stream. /// </summary> /// <param name="toWrap">The stream to wrap</param> /// <param name="ownsWrapped">Indicates if this stream controls toWrap's lifetime</param> public TracingStream(Stream toWrap, Ownership ownsWrapped) { _wrapped = toWrap; _ownsWrapped = ownsWrapped; _records = new List<StreamTraceRecord>(); } /// <summary> /// Disposes of this instance. /// </summary> /// <param name="disposing"><c>true</c> if called from Dispose(), else <c>false</c></param> protected override void Dispose(bool disposing) { if (disposing) { if (_ownsWrapped == Ownership.Dispose && _wrapped != null) { _wrapped.Dispose(); } _wrapped = null; if (_fileOut != null) { _fileOut.Dispose(); } _fileOut = null; } base.Dispose(disposing); } /// <summary> /// Starts tracing stream activity. /// </summary> public void Start() { _active = true; } /// <summary> /// Stops tracing stream activity. /// </summary> /// <remarks>Old trace records are not discarded, use <c>Start</c> to resume the trace</remarks> public void Stop() { _active = false; } /// <summary> /// Resets tracing on the stream. /// </summary> /// <param name="start">Whether to enable or disable tracing after this method completes</param> public void Reset(bool start) { _active = false; _records.Clear(); if (start) { Start(); } } /// <summary> /// Gets and sets whether to capture stack traces for every read/write /// </summary> public bool CaptureStackTraces { get { return _captureStack; } set { _captureStack = value; } } /// <summary> /// Gets and sets whether to trace read activity (default is false). /// </summary> public bool TraceReads { get { return _traceReads; } set { _traceReads = value; } } /// <summary> /// Gets and sets whether to trace write activity (default is true). /// </summary> public bool TraceWrites { get { return _traceWrites; } set { _traceWrites = value; } } /// <summary> /// Directs trace output to a file as well as storing internally. /// </summary> /// <param name="path">The path to the file.</param> /// <remarks>Call this method after tracing has started to migrate to a new /// output file.</remarks> public void WriteToFile(string path) { if (_fileOut != null) { _fileOut.Dispose(); _fileOut = null; } if (!string.IsNullOrEmpty(path)) { _fileOut = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)); } } /// <summary> /// Gets a log of all recorded stream activity. /// </summary> public IEnumerable<StreamTraceRecord> Log { get { return _records; } } /// <summary> /// Gets an indication as to whether the stream can be read. /// </summary> public override bool CanRead { get { return _wrapped.CanRead; } } /// <summary> /// Gets an indication as to whether the stream position can be changed. /// </summary> public override bool CanSeek { get { return _wrapped.CanSeek; } } /// <summary> /// Gets an indication as to whether the stream can be written to. /// </summary> public override bool CanWrite { get { return _wrapped.CanWrite; } } /// <summary> /// Flushes the stream. /// </summary> public override void Flush() { _wrapped.Flush(); } /// <summary> /// Gets the length of the stream. /// </summary> public override long Length { get { return _wrapped.Length; } } /// <summary> /// Gets and sets the current stream position. /// </summary> public override long Position { get { return _wrapped.Position; } set { _wrapped.Position = value; } } /// <summary> /// Reads data from the stream. /// </summary> /// <param name="buffer">The buffer to fill</param> /// <param name="offset">The buffer offset to start from</param> /// <param name="count">The number of bytes to read</param> /// <returns>The number of bytes read</returns> public override int Read(byte[] buffer, int offset, int count) { long position = _wrapped.Position; try { int result = _wrapped.Read(buffer, offset, count); if (_active && _traceReads) { CreateAndAddRecord("READ", position, count, result); } return result; } catch(Exception e) { if (_active && _traceReads) { CreateAndAddRecord("READ", position, count, e); } throw; } } /// <summary> /// Moves the stream position. /// </summary> /// <param name="offset">The origin-relative location</param> /// <param name="origin">The base location</param> /// <returns>The new absolute stream position</returns> public override long Seek(long offset, SeekOrigin origin) { return _wrapped.Seek(offset, origin); } /// <summary> /// Sets the length of the stream. /// </summary> /// <param name="value">The new length</param> public override void SetLength(long value) { _wrapped.SetLength(value); } /// <summary> /// Writes data to the stream at the current location. /// </summary> /// <param name="buffer">The data to write</param> /// <param name="offset">The first byte to write from buffer</param> /// <param name="count">The number of bytes to write</param> public override void Write(byte[] buffer, int offset, int count) { long position = _wrapped.Position; try { _wrapped.Write(buffer, offset, count); if (_active && _traceWrites) { CreateAndAddRecord("WRITE", position, count); } } catch (Exception e) { if (_active && _traceWrites) { CreateAndAddRecord("WRITE", position, count, e); } throw; } } private StreamTraceRecord CreateAndAddRecord(string activity, long position, long count) { return CreateAndAddRecord(activity, position, count, 0, null); } private StreamTraceRecord CreateAndAddRecord(string activity, long position, long count, int result) { return CreateAndAddRecord(activity, position, count, result, null); } private StreamTraceRecord CreateAndAddRecord(string activity, long position, long count, Exception e) { return CreateAndAddRecord(activity, position, count, -1, e); } private StreamTraceRecord CreateAndAddRecord(string activity, long position, long count, int result, Exception ex) { StackTrace trace = (_captureStack ? new StackTrace(2, _captureStackFileDetails) : null); StreamTraceRecord record = new StreamTraceRecord(_records.Count, activity, position, trace); record.CountArg = count; record.Result = result; record.ExceptionThrown = ex; _records.Add(record); if (_fileOut != null) { _fileOut.WriteLine(record); if (trace != null) { _fileOut.Write(trace.ToString()); } if (ex != null) { _fileOut.WriteLine(ex); } _fileOut.Flush(); } return record; } } }
using System; using UnityEngine; using System.Collections; using System.Collections.Generic; //parts of this were inspired by https://github.com/prime31/UIToolkit/blob/master/Assets/Plugins/UIToolkit/UIElements/UIText.cs //how to interpret BMFont files: http://www.gamedev.net/topic/284560-bmfont-and-how-to-interpret-the-fnt-file/ public class FCharInfo { public int charID; public float x; public float y; public float width; public float height; public Rect uvRect; public Vector2 uvTopLeft; public Vector2 uvTopRight; public Vector2 uvBottomRight; public Vector2 uvBottomLeft; public float offsetX; public float offsetY; public float xadvance; public int page; public string letter; } public class FKerningInfo { public int first; public int second; public float amount; } public class FLetterQuad { public FCharInfo charInfo; public Rect rect; public Vector2 topLeft; public Vector2 topRight; public Vector2 bottomRight; public Vector2 bottomLeft; public void CalculateVectors() { topLeft.Set(rect.xMin, rect.yMax); topRight.Set(rect.xMax, rect.yMax); bottomRight.Set(rect.xMax, rect.yMin); bottomLeft.Set(rect.xMin, rect.yMin); } public void CalculateVectors(float offsetX, float offsetY) { topLeft.Set(rect.xMin + offsetX, rect.yMax + offsetY); topRight.Set(rect.xMax + offsetX, rect.yMax + offsetY); bottomRight.Set(rect.xMax + offsetX, rect.yMin + offsetY); bottomLeft.Set(rect.xMin + offsetX, rect.yMin + offsetY); } //this moves the quads by a certain offset public void CalculateVectorsToWholePixels(float offsetX, float offsetY) { float scaleInverse = Futile.displayScaleInverse; //the stuff is used to make sure the quad is resting on a whole pixel float xMod = (rect.xMin + offsetX) % scaleInverse; float yMod = (rect.yMin + offsetY) % scaleInverse; offsetX -= xMod; offsetY -= yMod; float roundedLeft = rect.xMin + offsetX; float roundedRight = rect.xMax + offsetX; float roundedTop = rect.yMax + offsetY; float roundedBottom = rect.yMin + offsetY; topLeft.x = roundedLeft; topLeft.y = roundedTop; topRight.x = roundedRight; topRight.y = roundedTop; bottomRight.x = roundedRight; bottomRight.y = roundedBottom; bottomLeft.x = roundedLeft; bottomLeft.y = roundedBottom; } } public class FTextParams { public float scaledLineHeightOffset = 0; public float scaledKerningOffset = 0; private float _lineHeightOffset = 0; private float _kerningOffset = 0; public float kerningOffset { get { return _kerningOffset; } set { _kerningOffset = value; scaledKerningOffset = value; } } public float lineHeightOffset { get { return _lineHeightOffset; } set { _lineHeightOffset = value; scaledLineHeightOffset = value; } } } public class FLetterQuadLine { public Rect bounds; public int letterCount; public FLetterQuad[] quads; } public class FFont { public const int ASCII_NEWLINE = 10; public const int ASCII_SPACE = 32; public const int ASCII_HYPHEN_MINUS = 45; public const int ASCII_LINEHEIGHT_REFERENCE = 77; //77 is the letter M private string _name; private FAtlasElement _element; private string _configPath; private FCharInfo[] _charInfos; private Dictionary<uint, FCharInfo> _charInfosByID; //chars with the index of array being the char id private FKerningInfo[] _kerningInfos; private int _kerningCount; private FKerningInfo _nullKerning = new FKerningInfo(); private float _lineHeight; //private float _lineBase; private int _configWidth; //private int _configHeight; private float _configRatio; private FTextParams _textParams; private float _offsetX; private float _offsetY; public FFont(string name, FAtlasElement element, string configPath, float offsetX, float offsetY, FTextParams textParams) { _name = name; _element = element; _configPath = configPath; _textParams = textParams; _offsetX = offsetX; _offsetY = offsetY; LoadAndParseConfigFile(); } private void LoadAndParseConfigFile() { TextAsset asset = (TextAsset)Resources.Load(_configPath, typeof(TextAsset)); if (asset == null) { throw new FutileException("Couldn't find font config file " + _configPath); } string[] separators = new string[1]; separators[0] = "\n"; //osx string[] lines = asset.text.Split(separators, StringSplitOptions.RemoveEmptyEntries); if (lines.Length <= 1) //osx line endings didn't work, try windows { separators[0] = "\r\n"; lines = asset.text.Split(separators, StringSplitOptions.RemoveEmptyEntries); } if (lines.Length <= 1) //those line endings didn't work, so we're on a magical OS { separators[0] = "\r"; lines = asset.text.Split(separators, StringSplitOptions.RemoveEmptyEntries); } if (lines.Length <= 1) //WHAT { throw new FutileException("Your font file is messed up"); } int wordCount = 0; int c = 0; int k = 0; _charInfosByID = new Dictionary<uint, FCharInfo>(127); //insert an empty char to be used when a character isn't in the font data file FCharInfo emptyChar = new FCharInfo(); _charInfosByID[0] = emptyChar; float resourceScale = Futile.resourceScale; Vector2 textureSize = _element.atlas.textureSize; bool wasKerningFound = false; int lineCount = lines.Length; for (int n = 0; n < lineCount; ++n) { string line = lines[n]; string[] words = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); /* we don't care about these, or else they could be in the elseif if(words[0] == "info") //info face="Franchise Bold" size=160 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1 { //do nothing } else if(words[0] == "page") //page id=0 file="FranchiseLarge" { //do nothing } */ if (words[0] == "common") //common lineHeight=168 base=26 scaleW=1024 scaleH=1024 pages=1 packed=0 { //these are the height and width of the original atlas built by Hiero _configWidth = int.Parse(words[3].Split('=')[1]); //_configHeight = int.Parse(words[4].Split('=')[1]); //this is the ratio of the config vs the size of the actual texture element _configRatio = _element.sourceSize.x / _configWidth; _lineHeight = int.Parse(words[1].Split('=')[1]) * _configRatio; //_lineBase = int.Parse(words[2].Split('=')[1]) * _configRatio; } else if (words[0] == "chars") //chars count=92 { int charCount = int.Parse(words[1].Split('=')[1]); _charInfos = new FCharInfo[charCount + 1]; //gotta add 1 because the charCount seems to be off by 1 } else if (words[0] == "char") //char id=32 x=0 y=0 width=0 height=0 xoffset=0 yoffset=120 xadvance=29 page=0 chnl=0 letter=a { FCharInfo charInfo = new FCharInfo(); wordCount = words.Length; for (int w = 1; w < wordCount; ++w) { string[] parts = words[w].Split('='); string partName = parts[0]; if (partName == "letter") { if (parts[1].Length >= 3) { charInfo.letter = parts[1].Substring(1, 1); } continue; //we don't care about the letter } if (partName == "\r") continue; //something weird happened with linebreaks, meh! int partValue = int.Parse(parts[1]); if (partName == "id") { charInfo.charID = partValue; } else if (partName == "x") { charInfo.x = partValue * _configRatio - _element.sourceRect.x; //offset to account for the trimmed atlas } else if (partName == "y") { charInfo.y = partValue * _configRatio - _element.sourceRect.y; //offset to account for the trimmed atlas } else if (partName == "width") { charInfo.width = partValue * _configRatio; } else if (partName == "height") { charInfo.height = partValue * _configRatio; } else if (partName == "xoffset") { charInfo.offsetX = partValue * _configRatio; } else if (partName == "yoffset") { charInfo.offsetY = partValue * _configRatio; } else if (partName == "xadvance") { charInfo.xadvance = partValue * _configRatio; } else if (partName == "page") { charInfo.page = partValue; } } Rect uvRect = new Rect ( _element.uvRect.x + charInfo.x / textureSize.x * resourceScale, (textureSize.y - charInfo.y - charInfo.height) / textureSize.y * resourceScale - (1.0f - _element.uvRect.yMax), charInfo.width / textureSize.x * resourceScale, charInfo.height / textureSize.y * resourceScale ); charInfo.uvRect = uvRect; charInfo.uvTopLeft.Set(uvRect.xMin, uvRect.yMax); charInfo.uvTopRight.Set(uvRect.xMax, uvRect.yMax); charInfo.uvBottomRight.Set(uvRect.xMax, uvRect.yMin); charInfo.uvBottomLeft.Set(uvRect.xMin, uvRect.yMin); _charInfosByID[(uint)charInfo.charID] = charInfo; _charInfos[c] = charInfo; c++; } else if (words[0] == "kernings") //kernings count=169 { wasKerningFound = true; int kerningCount = int.Parse(words[1].Split('=')[1]); _kerningInfos = new FKerningInfo[kerningCount + 100]; //kerning count can be wrong so just add 100 items of potential fudge factor } else if (words[0] == "kerning") //kerning first=56 second=57 amount=-1 { FKerningInfo kerningInfo = new FKerningInfo(); kerningInfo.first = -1; wordCount = words.Length; for (int w = 1; w < wordCount; w++) { string[] parts = words[w].Split('='); if (parts.Length >= 2) { string partName = parts[0]; int partValue = int.Parse(parts[1]); if (partName == "first") { kerningInfo.first = partValue; } else if (partName == "second") { kerningInfo.second = partValue; } else if (partName == "amount") { kerningInfo.amount = partValue * _configRatio; } } } if (kerningInfo.first != -1) { _kerningInfos[k] = kerningInfo; } k++; } } _kerningCount = k; if (!wasKerningFound) //if there are no kernings at all (like in a pixel font), then make an empty kerning array { _kerningInfos = new FKerningInfo[0]; } //make sure the space character doesn't have offsetY and offsetX if (_charInfosByID[32] != null) { _charInfosByID[32].offsetX = 0; _charInfosByID[32].offsetY = 0; } } public FLetterQuadLine[] GetQuadInfoForText(string text, FTextParams textParams) { int lineCount = 0; int letterCount = 0; char[] letters = text.ToCharArray(); //at some point these should probably be pooled and reused so we're not allocing new ones all the time FLetterQuadLine[] lines = new FLetterQuadLine[10]; int lettersLength = letters.Length; for (int c = 0; c < lettersLength; ++c) { char letter = letters[c]; if (letter == ASCII_NEWLINE) { lines[lineCount] = new FLetterQuadLine(); lines[lineCount].letterCount = letterCount; lines[lineCount].quads = new FLetterQuad[letterCount]; lineCount++; letterCount = 0; } else { letterCount++; } } lines[lineCount] = new FLetterQuadLine(); lines[lineCount].letterCount = letterCount; lines[lineCount].quads = new FLetterQuad[letterCount]; FLetterQuadLine[] oldLines = lines; lines = new FLetterQuadLine[lineCount + 1]; for (int c = 0; c < lineCount + 1; ++c) { lines[c] = oldLines[c]; } lineCount = 0; letterCount = 0; float nextX = 0; float nextY = 0; FCharInfo charInfo; char previousLetter = '\0'; float minX = float.MaxValue; float maxX = float.MinValue; float minY = float.MaxValue; float maxY = float.MinValue; float usableLineHeight = _lineHeight + textParams.scaledLineHeightOffset + _textParams.scaledLineHeightOffset; for (int c = 0; c < lettersLength; ++c) { char letter = letters[c]; if (letter == ASCII_NEWLINE) { lines[lineCount].bounds = new Rect(minX, minY, maxX - minX, maxY - minY); if (letterCount == 0) { lines[lineCount].bounds = new Rect(0, 0, nextY, nextY - usableLineHeight); } else { lines[lineCount].bounds = new Rect(minX, minY, maxX - minX, maxY - minY); } minX = float.MaxValue; maxX = float.MinValue; minY = float.MaxValue; maxY = float.MinValue; nextX = 0; nextY -= usableLineHeight; lineCount++; letterCount = 0; } else { FKerningInfo foundKerning = _nullKerning; for (int k = 0; k < _kerningCount; k++) { FKerningInfo kerningInfo = _kerningInfos[k]; if (kerningInfo.first == previousLetter && kerningInfo.second == letter) { foundKerning = kerningInfo; } } //TODO: Reuse letterquads with pooling! FLetterQuad letterQuad = new FLetterQuad(); if (_charInfosByID.ContainsKey(letter)) { charInfo = _charInfosByID[letter]; } else //we don't have that character in the font { //blank, character (could consider using the "char not found square") charInfo = _charInfosByID[0]; } float totalKern = foundKerning.amount + textParams.scaledKerningOffset + _textParams.scaledKerningOffset; nextX += totalKern; letterQuad.charInfo = charInfo; Rect quadRect = new Rect(nextX + charInfo.offsetX, nextY - charInfo.offsetY - charInfo.height, charInfo.width, charInfo.height); letterQuad.rect = quadRect; lines[lineCount].quads[letterCount] = letterQuad; minX = Math.Min(minX, quadRect.xMin); maxX = Math.Max(maxX, quadRect.xMax); maxY = Math.Max(maxY, nextY); minY = Math.Min(minY, nextY - usableLineHeight); // minY = Math.Min (minY, quadRect.yMin); // maxY = Math.Max (maxY, quadRect.yMax); nextX += charInfo.xadvance; letterCount++; } previousLetter = letter; } if (letterCount == 0) { lines[lineCount].bounds = new Rect(0, 0, nextY, nextY - usableLineHeight); } else { lines[lineCount].bounds = new Rect(minX, minY, maxX - minX, maxY - minY); } return lines; } public string name { get { return _name; } } public FAtlasElement element { get { return _element; } } public FTextParams textParams { get { return _textParams; } } public float offsetX { get { return _offsetX; } } public float offsetY { get { return _offsetY; } } // Not gonna deal with this stuff unless it's actually needed // In theory it'll handle nice quotes // // private int forceLowAsciiChar(int charID) // { // if(charID < 8200) return charID; //short circuit so we don't branch 6 times // // if(charID == 8211) return 150; // if(charID == 8212) return 151; // if(charID == 8216) return 145; // if(charID == 8217) return 146; // if(charID == 8220) return 147; // if(charID == 8221) return 148; // // return charID; // } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CSC.Common.Infrastructure.Utilities; using CSC.CSClassroom.Model.Assignments; using CSC.CSClassroom.Model.Users; using CSC.CSClassroom.Service.Classrooms; using CSC.CSClassroom.Service.Assignments; using CSC.CSClassroom.WebApp.Filters; using CSC.CSClassroom.WebApp.ViewModels.Question; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; namespace CSC.CSClassroom.WebApp.Controllers { /// <summary> /// The question controller. /// </summary> [Route(ClassroomRoutePrefix)] public class QuestionController : BaseClassroomController { /// <summary> /// The question service. /// </summary> private IQuestionService QuestionService { get; } /// <summary> /// The question category service. /// </summary> private IQuestionCategoryService QuestionCategoryService { get; } /// <summary> /// A list of supported question types. /// </summary> private static readonly IReadOnlyList<QuestionType> s_createQuestionTypes; /// <summary> /// A list of supported question types for randomly-selected question choices. /// </summary> private static readonly IReadOnlyList<QuestionType> s_randomlySelectedQuestionTypes; /// <summary> /// Caches the list of supported question types. /// </summary> static QuestionController() { s_createQuestionTypes = CreateQuestionTypes ( typeof(MultipleChoiceQuestion), typeof(ShortAnswerQuestion), typeof(MethodQuestion), typeof(ClassQuestion), typeof(ProgramQuestion), typeof(RandomlySelectedQuestion) ); s_randomlySelectedQuestionTypes = CreateQuestionTypes ( typeof(MultipleChoiceQuestion), typeof(ShortAnswerQuestion) ); } /// <summary> /// Creates a set of QuestionType objects for the given set of types. /// </summary> private static IReadOnlyList<QuestionType> CreateQuestionTypes(params Type[] types) { return types .Select(type => new QuestionType(type)) .ToList(); } /// <summary> /// Constructor. /// </summary> public QuestionController( BaseControllerArgs args, IClassroomService classroomService, IQuestionService questionService, IQuestionCategoryService questionCategoryService) : base(args, classroomService) { QuestionService = questionService; QuestionCategoryService = questionCategoryService; } /// <summary> /// Shows all questions. /// </summary> [Route("Questions")] [ClassroomAuthorization(ClassroomRole.Admin)] public async Task<IActionResult> Index() { var questions = await QuestionService.GetQuestionsAsync(ClassroomName); var sortedQuestions = questions.OrderBy(q => q.Name, new NaturalComparer()) .ToList(); if (ClassroomRole >= ClassroomRole.Admin) { return View(sortedQuestions); } else { return View(sortedQuestions.ToList()); } } /// <summary> /// Creates a new question. /// </summary> [Route("CreateQuestion")] [ClassroomAuthorization(ClassroomRole.Admin)] public async Task<IActionResult> Create( string questionType, int? questionCategoryId, int? sourceAssignmentId) { ViewBag.SourceAssignmentId = sourceAssignmentId; QuestionCategory category = null; if (questionCategoryId.HasValue) { category = await QuestionCategoryService.GetQuestionCategoryAsync ( ClassroomName, questionCategoryId.Value ); } var questionTypes = category?.RandomlySelectedQuestionId != null ? s_randomlySelectedQuestionTypes : s_createQuestionTypes; var questionTypeObj = questionTypes.FirstOrDefault(type => type.Type.Name == questionType); if (questionTypeObj == null) { return View ( "CreateEdit/SelectType", new SelectTypeViewModel(questionTypes, questionCategoryId) ); } else { await PopulateDropDownsAsync(); var newQuestion = (Question) Activator.CreateInstance(questionTypeObj.Type); newQuestion.QuestionCategory = category; newQuestion.QuestionCategoryId = category?.Id ?? 0; return View("CreateEdit", newQuestion); } } /// <summary> /// Creates a new question. /// </summary> [HttpPost] [ValidateAntiForgeryToken] [Route("CreateQuestion")] [ClassroomAuthorization(ClassroomRole.Admin)] public async Task<IActionResult> Create(int? sourceAssignmentId, Question question) { var category = await QuestionCategoryService.GetQuestionCategoryAsync ( ClassroomName, question.QuestionCategoryId ); if (ModelState.IsValid && await QuestionService.CreateQuestionAsync(ClassroomName, question, ModelErrors)) { if (sourceAssignmentId.HasValue) { return RedirectToAction ( "Edit", "Assignment", new { id = sourceAssignmentId.Value, createdQuestionId = question.Id } ); } else if (question.HasChoices) { return RedirectToAction("QuestionChoices", new { id = question.Id }); } else if (category.RandomlySelectedQuestionId.HasValue) { return RedirectToAction ( "QuestionChoices", new { id = category.RandomlySelectedQuestionId } ); } else { return RedirectToAction("Index"); } } else { await PopulateDropDownsAsync(); return View("CreateEdit", question); } } /// <summary> /// Creates a new question. /// </summary> [Route("DuplicateExistingQuestion")] [ClassroomAuthorization(ClassroomRole.Admin)] public async Task<IActionResult> DuplicateExisting(int id) { await PopulateDropDownsAsync(); var question = await QuestionService .DuplicateExistingQuestionAsync(ClassroomName, id); ViewBag.ActionName = "Create"; return View("CreateEdit", question); } /// <summary> /// Edits a question. /// </summary> [Route("Questions/{id}/Edit")] [ClassroomAuthorization(ClassroomRole.Admin)] public async Task<IActionResult> Edit(int? id, int? seed) { if (id == null) { return NotFound(); } await PopulateDropDownsAsync(); if (seed != null) { var questionInstance = await QuestionService.GetQuestionInstanceAsync ( ClassroomName, id.Value, seed.Value ); if (questionInstance == null) { return NotFound(); } if (questionInstance.Question == null) { return View("CreateEdit/QuestionGenerationError", questionInstance); } ViewBag.Seed = seed; return View("CreateEdit", questionInstance.Question); } else { var question = await QuestionService.GetQuestionAsync(ClassroomName, id.Value); if (question == null) { return NotFound(); } return View("CreateEdit", question); } } /// <summary> /// Edits a question. /// </summary> [HttpPost] [ValidateAntiForgeryToken] [Route("Questions/{id}/Edit")] [ClassroomAuthorization(ClassroomRole.Admin)] public async Task<IActionResult> Edit(int? id, Question question) { if (id != question.Id) { return NotFound(); } var category = await QuestionCategoryService.GetQuestionCategoryAsync ( ClassroomName, question.QuestionCategoryId ); if (ModelState.IsValid && await QuestionService.UpdateQuestionAsync(ClassroomName, question, ModelErrors)) { if (category.RandomlySelectedQuestionId.HasValue) { return RedirectToAction("QuestionChoices", new { id = category.RandomlySelectedQuestionId }); } else { return RedirectToAction("Index"); } } else { await PopulateDropDownsAsync(); return View("CreateEdit", question); } } /// <summary> /// Returns a new generated question template based off of an existing question. /// The generated question is not saved unless and until it is submitted through /// the Create action. /// </summary> [Route("GenerateFromExistingQuestion")] [ClassroomAuthorization(ClassroomRole.Admin)] public async Task<IActionResult> GenerateFromExisting(int id) { await PopulateDropDownsAsync(); var question = await QuestionService.GenerateFromExistingQuestionAsync ( ClassroomName, id ); ViewBag.ActionName = "Create"; return View("CreateEdit", question); } /// <summary> /// Deletes a question. /// </summary> [Route("Questions/{id}/Delete")] [ClassroomAuthorization(ClassroomRole.Admin)] public async Task<IActionResult> Delete(int id) { var question = await QuestionService.GetQuestionAsync(ClassroomName, id); if (question == null) { return NotFound(); } return View(question); } /// <summary> /// Deletes a question. /// </summary> [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] [Route("Questions/{id}/Delete")] [ClassroomAuthorization(ClassroomRole.Admin)] public async Task<IActionResult> DeleteConfirmed(int id) { var category = await QuestionService.DeleteQuestionAsync(ClassroomName, id); if (category.RandomlySelectedQuestionId.HasValue) { return RedirectToAction("QuestionChoices", new { id = category.RandomlySelectedQuestionId.Value }); } else { return RedirectToAction("Index"); } } /// <summary> /// Shows all questions. /// </summary> [Route("Question/{id}/Choices")] [ClassroomAuthorization(ClassroomRole.Admin)] public async Task<IActionResult> QuestionChoices(int id) { var choicesCategory = await QuestionService.GetQuestionChoicesAsync(ClassroomName, id); if (choicesCategory == null) { return NotFound(); } return View(choicesCategory); } /// <summary> /// Populates dropdown lists required by the Create/Edit actions. /// </summary> private async Task PopulateDropDownsAsync() { var questionCategories = await QuestionCategoryService .GetQuestionCategoriesAsync(ClassroomName); ViewBag.QuestionCategoryId = new SelectList ( questionCategories .OrderBy(qc => qc.Name, new NaturalComparer()), "Id", "Name" ); ViewBag.AvailableQuestions = await QuestionService.GetQuestionsAsync(ClassroomName); } } }
// 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.Runtime.Serialization.Formatters.Tests; using Xunit; namespace System.Reflection.Tests { public unsafe class PointerHolder { public int* field; public char* Property { get; set; } public void Method(byte* ptr, int expected) { Assert.Equal(expected, unchecked((int)ptr)); } public bool* Return(int expected) { return unchecked((bool*)expected); } } public unsafe class PointerTests { [Fact] public void Box_TypeNull() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => { Pointer.Box((void*)0, null); }); } [Fact] public void Box_NonPointerType() { Assert.Throws<ArgumentException>(() => { Pointer.Box((void*)0, typeof(int)); }); } [Fact] public void Unbox_Null() { Assert.Throws<ArgumentException>(() => { Pointer.Unbox(null); }); } [Fact] public void Unbox_NotPointer() { Assert.Throws<ArgumentException>(() => { Pointer.Unbox(new object()); }); } [Theory] [MemberData(nameof(Pointers))] public void PointerValueRoundtrips(int value) { void* ptr = unchecked((void*)value); void* result = Pointer.Unbox(Pointer.Box(ptr, typeof(int*))); Assert.Equal((IntPtr)ptr, (IntPtr)result); } public static IEnumerable<object[]> Pointers => new[] { new object[] { 0 }, new object[] { 1 }, new object[] { -1 }, new object[] { int.MaxValue }, new object[] { int.MinValue }, }; [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerFieldSetValue(int value) { var obj = new PointerHolder(); FieldInfo field = typeof(PointerHolder).GetField("field"); field.SetValue(obj, Pointer.Box(unchecked((void*)value), typeof(int*))); Assert.Equal(value, unchecked((int)obj.field)); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void IntPtrFieldSetValue(int value) { var obj = new PointerHolder(); FieldInfo field = typeof(PointerHolder).GetField("field"); field.SetValue(obj, (IntPtr)value); Assert.Equal(value, unchecked((int)obj.field)); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerFieldSetValue_InvalidType(int value) { var obj = new PointerHolder(); FieldInfo field = typeof(PointerHolder).GetField("field"); Assert.Throws<ArgumentException>(() => { field.SetValue(obj, Pointer.Box(unchecked((void*)value), typeof(long*))); }); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Issue https://github.com/dotnet/corefx/issues/17450")] public void PointerFieldGetValue(int value) { var obj = new PointerHolder(); obj.field = unchecked((int*)value); FieldInfo field = typeof(PointerHolder).GetField("field"); object actualValue = field.GetValue(obj); Assert.IsType<Pointer>(actualValue); void* actualPointer = Pointer.Unbox(actualValue); Assert.Equal(value, unchecked((int)actualPointer)); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerPropertySetValue(int value) { var obj = new PointerHolder(); PropertyInfo property = typeof(PointerHolder).GetProperty("Property"); property.SetValue(obj, Pointer.Box(unchecked((void*)value), typeof(char*))); Assert.Equal(value, unchecked((int)obj.Property)); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void IntPtrPropertySetValue(int value) { var obj = new PointerHolder(); PropertyInfo property = typeof(PointerHolder).GetProperty("Property"); property.SetValue(obj, (IntPtr)value); Assert.Equal(value, unchecked((int)obj.Property)); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerPropertySetValue_InvalidType(int value) { var obj = new PointerHolder(); PropertyInfo property = typeof(PointerHolder).GetProperty("Property"); Assert.Throws<ArgumentException>(() => { property.SetValue(obj, Pointer.Box(unchecked((void*)value), typeof(long*))); }); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerPropertyGetValue(int value) { var obj = new PointerHolder(); obj.Property = unchecked((char*)value); PropertyInfo property = typeof(PointerHolder).GetProperty("Property"); object actualValue = property.GetValue(obj); Assert.IsType<Pointer>(actualValue); void* actualPointer = Pointer.Unbox(actualValue); Assert.Equal(value, unchecked((int)actualPointer)); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerMethodParameter(int value) { var obj = new PointerHolder(); MethodInfo method = typeof(PointerHolder).GetMethod("Method"); method.Invoke(obj, new[] { Pointer.Box(unchecked((void*)value), typeof(byte*)), value }); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void IntPtrMethodParameter(int value) { var obj = new PointerHolder(); MethodInfo method = typeof(PointerHolder).GetMethod("Method"); method.Invoke(obj, new object[] { (IntPtr)value, value }); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerMethodParameter_InvalidType(int value) { var obj = new PointerHolder(); MethodInfo method = typeof(PointerHolder).GetMethod("Method"); Assert.Throws<ArgumentException>(() => { method.Invoke(obj, new[] { Pointer.Box(unchecked((void*)value), typeof(long*)), value }); }); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerMethodReturn(int value) { var obj = new PointerHolder(); MethodInfo method = typeof(PointerHolder).GetMethod("Return"); object actualValue = method.Invoke(obj, new object[] { value }); Assert.IsType<Pointer>(actualValue); void* actualPointer = Pointer.Unbox(actualValue); Assert.Equal(value, unchecked((int)actualPointer)); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using System.Threading; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting { using static ParameterValidationHelpers; /// <summary> /// Options for creating and running scripts. /// </summary> public sealed class ScriptOptions { public static readonly ScriptOptions Default = new ScriptOptions( filePath: "", references: ImmutableArray<MetadataReference>.Empty, namespaces: ImmutableArray<string>.Empty, metadataResolver: RuntimeMetadataReferenceResolver.Default, sourceResolver: SourceFileResolver.Default); /// <summary> /// An array of <see cref="MetadataReference"/>s to be added to the script. /// </summary> /// <remarks> /// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>). /// Unresolved references are resolved when the script is about to be executed /// (<see cref="Script.RunAsync(object, CancellationToken)"/>. /// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>. /// </remarks> public ImmutableArray<MetadataReference> MetadataReferences { get; private set; } /// <summary> /// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives. /// </summary> public MetadataReferenceResolver MetadataResolver { get; private set; } /// <summary> /// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive. /// </summary> public SourceReferenceResolver SourceResolver { get; private set; } /// <summary> /// The namespaces, static classes and aliases imported by the script. /// </summary> public ImmutableArray<string> Imports { get; private set; } /// <summary> /// The path to the script source if it originated from a file, empty otherwise. /// </summary> public string FilePath { get; private set; } internal ScriptOptions( string filePath, ImmutableArray<MetadataReference> references, ImmutableArray<string> namespaces, MetadataReferenceResolver metadataResolver, SourceReferenceResolver sourceResolver) { Debug.Assert(filePath != null); Debug.Assert(!references.IsDefault); Debug.Assert(!namespaces.IsDefault); Debug.Assert(metadataResolver != null); Debug.Assert(sourceResolver != null); FilePath = filePath; MetadataReferences = references; Imports = namespaces; MetadataResolver = metadataResolver; SourceResolver = sourceResolver; } private ScriptOptions(ScriptOptions other) : this(filePath: other.FilePath, references: other.MetadataReferences, namespaces: other.Imports, metadataResolver: other.MetadataResolver, sourceResolver: other.SourceResolver) { } // a reference to an assembly should by default be equivalent to #r, which applies recursive global alias: private static readonly MetadataReferenceProperties AssemblyReferenceProperties = MetadataReferenceProperties.Assembly.WithRecursiveAliases(true); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="FilePath"/> changed. /// </summary> public ScriptOptions WithFilePath(string filePath) => (FilePath == filePath) ? this : new ScriptOptions(this) { FilePath = filePath ?? "" }; private static MetadataReference CreateUnresolvedReference(string reference) => new UnresolvedMetadataReference(reference, AssemblyReferenceProperties); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> private ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) => MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) => WithReferences(ToImmutableArrayChecked(references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params MetadataReference[] references) => WithReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) => WithReferences(ConcatChecked(MetadataReferences, references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params MetadataReference[] references) => AddReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions WithReferences(IEnumerable<Assembly> references) => WithReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions WithReferences(params Assembly[] references) => WithReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions AddReferences(IEnumerable<Assembly> references) => AddReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly)); private static MetadataReference CreateReferenceFromAssembly(Assembly assembly) { return MetadataReference.CreateFromAssemblyInternal(assembly, AssemblyReferenceProperties); } /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions AddReferences(params Assembly[] references) => AddReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<string> references) => WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params string[] references) => WithReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<string> references) => AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params string[] references) => AddReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>. /// </summary> public ScriptOptions WithMetadataResolver(MetadataReferenceResolver resolver) => MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>. /// </summary> public ScriptOptions WithSourceResolver(SourceReferenceResolver resolver) => SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> private ScriptOptions WithImports(ImmutableArray<string> imports) => Imports.Equals(imports) ? this : new ScriptOptions(this) { Imports = CheckImmutableArray(imports, nameof(imports)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions WithImports(IEnumerable<string> imports) => WithImports(ToImmutableArrayChecked(imports, nameof(imports))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions WithImports(params string[] imports) => WithImports((IEnumerable<string>)imports); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions AddImports(IEnumerable<string> imports) => WithImports(ConcatChecked(Imports, imports, nameof(imports))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions AddImports(params string[] imports) => AddImports((IEnumerable<string>)imports); } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using PicPository.Models; using RethinkDb.Driver.Extras.Dao; using RethinkDb.Driver.Net; namespace PicPository.Dao { public class PictureDao : RethinkDao<Picture, Guid> { public PictureDao(IConnection conn, RethinkDbOptions options) : base(conn, options.Database, nameof(Picture)) { // empty } public IEnumerable<Picture> GetAllFromUser(string userId) { return this.Table.Filter(new { UserId = userId }).RunCursor<Picture>(this.conn).BufferedItems; } public async Task<IEnumerable<Picture>> GetAllFromUserAsync(string userId) { return (await this.Table.Filter(new { UserId = userId }).RunCursorAsync<Picture>(this.conn)).BufferedItems; } public IEnumerable<Picture> GetFromAlbumAndUser(string userId, string albumId) { return this.Table.Filter(new { UserId = userId, AlbumId = albumId }).RunCursor<Picture>(this.conn).BufferedItems; } public async Task<IEnumerable<Picture>> GetFromAlbumAndUserAsync(string userId, string albumId) { return (await this.Table.Filter(new { UserId = userId, AlbumId = albumId }).RunCursorAsync<Picture>(this.conn)).BufferedItems; } public Picture GetFromUserById(string userId, string pictureId) { var picture = this.Table.Get(pictureId).RunAtom<Picture>(this.conn); if (picture.UserId != userId) return null; return picture; } public async Task<Picture> GetFromUserByIdAsync(string userId, string pictureId) { var picture = await this.Table.Get(pictureId).RunAtomAsync<Picture>(this.conn); if (picture.UserId != userId) return null; return picture; } public bool UpdateFromUser(string userId, Picture picture) { var doc = this.GetFromUserById(userId, picture.Id.ToString()); if (doc == null) return false; picture.TimeStamp = DateTime.Now; var updated = this.Table.Update(picture).RunResult(this.conn).Replaced; return updated > 0; } public async Task<bool> UpdateFromUserAsync(string userId, Picture picture) { var doc = await this.GetFromUserByIdAsync(userId, picture.Id.ToString()); if (doc == null) return false; picture.TimeStamp = DateTime.Now; var updated = (await this.Table.Update(picture).RunResultAsync(this.conn)).Replaced; return updated > 0; } public bool DeleteFromUserById(string userId, string pictureId) { var picture = this.GetFromUserById(userId, pictureId); if (picture == null) return false; var deleted = this.Table.Get(pictureId).Delete().RunResult(this.conn).Deleted; return deleted > 0; } public async Task<bool> DeleteFromUserByIdAsync(string userId, string pictureId) { var picture = await this.GetFromUserByIdAsync(userId, pictureId); if (picture == null) return false; var deleted = (await this.Table.Get(pictureId).Delete().RunResultAsync(this.conn)).Deleted; return deleted > 0; } public IEnumerable<Picture> GetFeatured() { var pictures = this.Table.Filter(new { IsFeatured = true }).RunCursor<Picture>(this.conn).BufferedItems; return pictures; } public async Task<IEnumerable<Picture>> GetFeaturedAsync() { var pictures = (await this.Table.Filter(new { IsFeatured = true }).RunCursorAsync<Picture>(this.conn)).BufferedItems; return pictures; } public IEnumerable<Picture> GetFromSubscribed(List<string> subscribedUserIds) { var pictures = this.Table.Filter(doc => subscribedUserIds.Contains(doc.G("UserId").ToString())) .RunCursor<Picture>(this.conn).BufferedItems; return pictures; } public async Task<IEnumerable<Picture>> GetFromSubscribedAsync(List<string> subscribedUserIds) { var pictures = (await this.Table.Filter(doc => subscribedUserIds.Contains(doc.G("UserId").ToString())) .RunCursorAsync<Picture>(this.conn)).BufferedItems; return pictures; } public IEnumerable<Picture> Search(string searchString) { var chunks = new List<string>(searchString.Trim().Split(' ')); var albumPictureIdsList = R.Table(nameof(Album)).Filter(doc => { string title = doc.G("Title").ToString(); string description = doc.G("Description").ToString(); return title.Contains(searchString) || chunks.Contains(title) || description.Contains(searchString) || chunks.Contains(description); }).Pluck("PictureIds").RunCursor<IEnumerable<string>>(this.conn).BufferedItems; var pictureIds = new List<string>(); albumPictureIdsList.ForEach(list => pictureIds.AddRange(list)); var pictures = this.Table.Filter(doc => { string title = doc.G("Title").ToString(); string description = doc.G("Description").ToString(); string pictureId = doc.G("id").ToString(); return title.Contains(searchString) || chunks.Contains(title) || description.Contains(searchString) || chunks.Contains(description) || pictureIds.Contains(pictureId); }).RunCursor<Picture>(this.conn).BufferedItems; // TODO pictures where user is author of the picture or author of album return pictures; } public async Task<IEnumerable<Picture>> SearchAsync(string searchString) { var chunks = new List<string>(searchString.Trim().Split(' ')); var albumPictureIdsList = (await R.Table(nameof(Album)).Filter(doc => { string title = doc.G("Title").ToString(); string description = doc.G("Description").ToString(); return title.Contains(searchString) || chunks.Contains(title) || description.Contains(searchString) || chunks.Contains(description); }).Pluck("PictureIds").RunCursorAsync<IEnumerable<string>>(this.conn)).BufferedItems; var pictureIds = new List<string>(); albumPictureIdsList.ForEach(list => pictureIds.AddRange(list)); var pictures = (await this.Table.Filter(doc => { string title = doc.G("Title").ToString(); string description = doc.G("Description").ToString(); string pictureId = doc.G("id").ToString(); return title.Contains(searchString) || chunks.Contains(title) || description.Contains(searchString) || chunks.Contains(description) || pictureIds.Contains(pictureId); }).RunCursorAsync<Picture>(this.conn)).BufferedItems; // TODO pictures where user is author of the picture or author of album return pictures; } public void ToggleFeatured(string pictureId) { var picture = this.GetById(Guid.Parse(pictureId)); picture.IsFeatured = !picture.IsFeatured; picture.TimeStamp = DateTime.Now; this.Update(picture); } public async Task ToggleFeaturedAsync(string pictureId) { var picture = await this.GetByIdAsync(Guid.Parse(pictureId)); picture.IsFeatured = !picture.IsFeatured; picture.TimeStamp = DateTime.Now; await this.UpdateAsync(picture); } public IEnumerable<Picture> GetUsersFavourites(string userId) { // TODO rename FavouritePicture class to FavouritePictures // TODO make this query return ATOM value - one FavouritePicture var favouritePictures = R.Table(nameof(FavouritePicture)).Filter(new { UserId = userId }).RunCursor<FavouritePicture>(this.conn).BufferedItems; if (favouritePictures != null && favouritePictures.Count != 0) { var favouritePictureIds = favouritePictures[0].FavouritePictureIds; return this.Table.Get(favouritePictureIds).RunCursor<Picture>(this.conn).BufferedItems; } return new List<Picture>(); // TODO rewrite this to use UserDao FavouritePictureIds - FavouritePictures table does not exist from now } public async Task<IEnumerable<Picture>> GetUsersFavouritesAsync(string userId) { // TODO rename FavouritePicture class to FavouritePictures // TODO make this query return ATOM value - one FavouritePictures instance var favouritePictures = (await R.Table(nameof(FavouritePicture)).Filter(new { UserId = userId }).RunCursorAsync<FavouritePicture>(this.conn)).BufferedItems; if (favouritePictures != null && favouritePictures.Count != 0) { var favouritePictureIds = favouritePictures[0].FavouritePictureIds; return (await this.Table.Get(favouritePictureIds).RunCursorAsync<Picture>(this.conn)).BufferedItems; } return new List<Picture>(); // TODO rewrite this to use UserDao FavouritePictureIds - FavouritePictures table does not exist from now } public void AddFavouriteToUser(string userId, string favouritePictureId) { // TODO rename FavouritePicture class to FavouritePictures // TODO make this query return ATOM value - one FavouritePictures instance var favouritePictures = R.Table(nameof(FavouritePicture)).Filter(new { UserId = userId }).RunCursor<FavouritePicture>(this.conn).BufferedItems; if (favouritePictures != null && favouritePictures.Count != 0) { if (!favouritePictures[0].FavouritePictureIds.Contains(favouritePictureId)) { // TODO think of turning this to a Set data structure favouritePictures[0].FavouritePictureIds.Add(favouritePictureId); R.Table(nameof(FavouritePicture)).Update(favouritePictures[0]).Run(this.conn); } } else { var favouritePicture = new FavouritePicture { UserId = userId, FavouritePictureIds = new List<string>() { favouritePictureId } }; R.Table(nameof(FavouritePicture)).Insert(favouritePicture).Run(this.conn); } // TODO also add to FavouritePictureIds in UserDao // TODO rewrite this to use UserDao FavouritePictureIds - FavouritePictures table does not exist from now } public async Task AddFavouriteToUserAsync(string userId, string favouritePictureId) { // TODO rename FavouritePicture class to FavouritePictures // TODO make this query return ATOM value - one FavouritePictures instance var favouritePictures = (await R.Table(nameof(FavouritePicture)).Filter(new { UserId = userId }).RunCursorAsync<FavouritePicture>(this.conn)).BufferedItems; if (favouritePictures != null && favouritePictures.Count != 0) { if (!favouritePictures[0].FavouritePictureIds.Contains(favouritePictureId)) { // TODO think of turning this to a Set data structure favouritePictures[0].FavouritePictureIds.Add(favouritePictureId); await R.Table(nameof(FavouritePicture)).Update(favouritePictures[0]).RunAsync(this.conn); } } else { var favouritePicture = new FavouritePicture { UserId = userId, FavouritePictureIds = new List<string>() { favouritePictureId } }; await R.Table(nameof(FavouritePicture)).Insert(favouritePicture).RunAsync(this.conn); } // TODO also add to FavouritePictureIds in UserDao // TODO rewrite this to use UserDao FavouritePictureIds - FavouritePictures table does not exist from now } public void RemoveFavouriteFromUser(string userId, string pictureId) { // TODO rename FavouritePicture class to FavouritePictures // TODO make this query return ATOM value - one FavouritePictures instance var favouritePictures = R.Table(nameof(FavouritePicture)).Filter(new { UserId = userId }).RunCursor<FavouritePicture>(this.conn).BufferedItems; if (favouritePictures != null && favouritePictures.Count != 0) { favouritePictures[0].FavouritePictureIds.Remove(pictureId); R.Table(nameof(FavouritePicture)).Update(favouritePictures[0]).Run(this.conn); } // TODO also remove from FavouritePictureIds in UserDao // TODO rewrite this to use UserDao FavouritePictureIds - FavouritePictures table does not exist from now } public async Task RemoveFavouriteFromUserAsync(string userId, string pictureId) { // TODO rename FavouritePicture class to FavouritePictures // TODO make this query return ATOM value - one FavouritePictures instance var favouritePictures = (await R.Table(nameof(FavouritePicture)).Filter(new { UserId = userId }).RunCursorAsync<FavouritePicture>(this.conn)).BufferedItems; if (favouritePictures != null && favouritePictures.Count != 0) { favouritePictures[0].FavouritePictureIds.Remove(pictureId); await R.Table(nameof(FavouritePicture)).Update(favouritePictures[0]).RunAsync(this.conn); } // TODO also remove from FavouritePictureIds in UserDao // TODO rewrite this to use UserDao FavouritePictureIds - FavouritePictures table does not exist from now } public IEnumerable<Picture> GetUsersLikedPictures(string userId) { // TODO rename PictureLike class to PictureLikes // TODO make this query return ATOM value - one PictureLikes var pictureLikes = R.Table(nameof(PictureLike)).Filter(new { UserId = userId }).RunCursor<PictureLike>(this.conn).BufferedItems; if (pictureLikes != null && pictureLikes.Count != 0) { var likedPictureIds = pictureLikes[0].LikedPictureIds; return this.Table.Get(likedPictureIds).RunCursor<Picture>(this.conn).BufferedItems; } return new List<Picture>(); // TODO rewrite this to use UserDao LikedPictureIds - PictureLikes table does not exist from now } public async Task<IEnumerable<Picture>> GetUsersLikedPicturesAsync(string userId) { // TODO rename PictureLike class to PictureLikes // TODO make this query return ATOM value - one PictureLikes var pictureLikes = (await R.Table(nameof(PictureLike)).Filter(new { UserId = userId }).RunCursorAsync<PictureLike>(this.conn)).BufferedItems; if (pictureLikes != null && pictureLikes.Count != 0) { var likedPictureIds = pictureLikes[0].LikedPictureIds; return (await this.Table.Get(likedPictureIds).RunCursorAsync<Picture>(this.conn)).BufferedItems; } return new List<Picture>(); // TODO rewrite this to use UserDao LikedPictureIds - PictureLikes table does not exist from now } public void AddUserLikeToPicture(string userId, string pictureId) { // TODO rename PictureLike class to PictureLikes // TODO make this query return ATOM value - one PictureLikes instance var pictureLikes = R.Table(nameof(PictureLike)).Filter(new { UserId = userId }).RunCursor<PictureLike>(this.conn).BufferedItems; if (pictureLikes != null && pictureLikes.Count != 0) { if (!pictureLikes[0].LikedPictureIds.Contains(pictureId)) { // TODO think of turning this to a Set data structure pictureLikes[0].LikedPictureIds.Add(pictureId); R.Table(nameof(PictureLike)).Update(pictureLikes[0]).Run(this.conn); } } else { var pictureLike = new PictureLike { UserId = userId, LikedPictureIds = new List<string>() { pictureId } }; R.Table(nameof(PictureLike)).Insert(pictureLike).Run(this.conn); } // TODO also add PublicUser to UsersThatLiked in Pictures table // TODO also add to LikedPictureIds in UserDao // TODO rewrite this to use UserDao LikedPictureIds - PictureLikes table does not exist from now } public async Task AddUserLikeToPictureAsync(string userId, string pictureId) { // TODO rename PictureLike class to PictureLikes // TODO make this query return ATOM value - one PictureLikes instance var pictureLikes = (await R.Table(nameof(PictureLike)).Filter(new { UserId = userId }).RunCursorAsync<PictureLike>(this.conn)).BufferedItems; if (pictureLikes != null && pictureLikes.Count != 0) { if (!pictureLikes[0].LikedPictureIds.Contains(pictureId)) { // TODO think of turning this to a Set data structure pictureLikes[0].LikedPictureIds.Add(pictureId); await R.Table(nameof(PictureLike)).Update(pictureLikes[0]).RunAsync(this.conn); } } else { var pictureLike = new PictureLike { UserId = userId, LikedPictureIds = new List<string>() { pictureId } }; await R.Table(nameof(PictureLike)).Insert(pictureLike).RunAsync(this.conn); } // TODO also add PublicUser to UsersThatLiked in Pictures table // TODO also add to LikedPictureIds in UserDao // TODO rewrite this to use UserDao LikedPictureIds - PictureLikes table does not exist from now } public void RemoveUserLikeFromPicture(string userId, string pictureId) { // TODO rename PictureLike class to PictureLikes // TODO make this query return ATOM value - one PictureLikes instance var pictureLikes = R.Table(nameof(PictureLike)).Filter(new { UserId = userId }).RunCursor<PictureLike>(this.conn).BufferedItems; if (pictureLikes != null && pictureLikes.Count != 0) { pictureLikes[0].LikedPictureIds.Remove(pictureId); R.Table(nameof(PictureLike)).Update(pictureLikes[0]).Run(this.conn); } // TODO also remove PublicUser from UsersThatLiked in Pictures table // TODO also remove from LikedPictureIds in UserDao // TODO rewrite this to use UserDao LikedPictureIds - PictureLikes table does not exist from now } public async Task RemoveUserLikeFromPictureAsync(string userId, string pictureId) { // TODO rename PictureLike class to PictureLikes // TODO make this query return ATOM value - one PictureLikes instance var pictureLikes = (await R.Table(nameof(PictureLike)).Filter(new { UserId = userId }).RunCursorAsync<PictureLike>(this.conn)).BufferedItems; if (pictureLikes != null && pictureLikes.Count != 0) { pictureLikes[0].LikedPictureIds.Remove(pictureId); await R.Table(nameof(PictureLike)).Update(pictureLikes[0]).RunAsync(this.conn); } // TODO also remove PublicUser from UsersThatLiked in Pictures table // TODO also remove from LikedPictureIds in UserDao // TODO rewrite this to use UserDao LikedPictureIds - PictureLikes table does not exist from now } public Comment AddCommentToPicture(string userId, string pictureId, string commentText) { var picture = this.GetFromUserById(userId, pictureId); if (picture == null) return null; picture.TimeStamp = DateTime.Now; Comment comment = new Comment() { UserId = userId, DateCreated = DateTime.Now, Text = commentText }; picture.Comments.Add(comment); var updated = this.Table.Update(picture).RunResult(this.conn).Replaced; return updated > 0 ? comment : null; } public async Task<Comment> AddCommentToPictureAsync(string userId, string pictureId, string commentText) { var picture = await this.GetFromUserByIdAsync(userId, pictureId); if (picture == null) return null; picture.TimeStamp = DateTime.Now; Comment comment = new Comment() { UserId = userId, DateCreated = DateTime.Now, Text = commentText }; picture.Comments.Add(comment); var updated = (await this.Table.Update(picture).RunResultAsync(this.conn)).Replaced; return updated > 0 ? comment : 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. /*============================================================ ** ** ** ** ** ** Purpose: A Stream whose backing store is memory. Great ** for temporary storage without creating a temp file. Also ** lets users expose a byte[] as a stream. ** ** ===========================================================*/ using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; namespace System.IO { // A MemoryStream represents a Stream in memory (ie, it has no backing store). // This stream may reduce the need for temporary buffers and files in // an application. // // There are two ways to create a MemoryStream. You can initialize one // from an unsigned byte array, or you can create an empty one. Empty // memory streams are resizable, while ones created with a byte array provide // a stream "view" of the data. public class MemoryStream : Stream { private byte[] _buffer; // Either allocated internally or externally. private int _origin; // For user-provided arrays, start at this origin private int _position; // read/write head. [ContractPublicPropertyName("Length")] private int _length; // Number of bytes within the memory stream private int _capacity; // length of usable portion of buffer for stream // Note that _capacity == _buffer.Length for non-user-provided byte[]'s private bool _expandable; // User-provided buffers aren't expandable. private bool _writable; // Can user write to this stream? private bool _exposable; // Whether the array can be returned to the user. private bool _isOpen; // Is this stream open or closed? [NonSerialized] private Task<int> _lastReadTask; // The last successful task returned from ReadAsync private const int MemStreamMaxLength = Int32.MaxValue; public MemoryStream() : this(0) { } public MemoryStream(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity); } Contract.EndContractBlock(); _buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>(); _capacity = capacity; _expandable = true; _writable = true; _exposable = true; _origin = 0; // Must be 0 for byte[]'s created by MemoryStream _isOpen = true; } public MemoryStream(byte[] buffer) : this(buffer, true) { } public MemoryStream(byte[] buffer, bool writable) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); Contract.EndContractBlock(); _buffer = buffer; _length = _capacity = buffer.Length; _writable = writable; _exposable = false; _origin = 0; _isOpen = true; } public MemoryStream(byte[] buffer, int index, int count) : this(buffer, index, count, true, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable) : this(buffer, index, count, writable, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); _buffer = buffer; _origin = _position = index; _length = _capacity = index + count; _writable = writable; _exposable = publiclyVisible; // Can TryGetBuffer/GetBuffer return the array? _expandable = false; _isOpen = true; } public override bool CanRead { [Pure] get { return _isOpen; } } public override bool CanSeek { [Pure] get { return _isOpen; } } public override bool CanWrite { [Pure] get { return _writable; } } private void EnsureWriteable() { if (!CanWrite) __Error.WriteNotSupported(); } protected override void Dispose(bool disposing) { try { if (disposing) { _isOpen = false; _writable = false; _expandable = false; // Don't set buffer to null - allow TryGetBuffer, GetBuffer & ToArray to work. _lastReadTask = null; } } finally { // Call base.Close() to cleanup async IO resources base.Dispose(disposing); } } // returns a bool saying whether we allocated a new array. private bool EnsureCapacity(int value) { // Check for overflow if (value < 0) throw new IOException(SR.IO_StreamTooLong); if (value > _capacity) { int newCapacity = value; if (newCapacity < 256) newCapacity = 256; // We are ok with this overflowing since the next statement will deal // with the cases where _capacity*2 overflows. if (newCapacity < _capacity * 2) newCapacity = _capacity * 2; // We want to expand the array up to Array.MaxArrayLengthOneDimensional // And we want to give the user the value that they asked for if ((uint)(_capacity * 2) > Array.MaxByteArrayLength) newCapacity = value > Array.MaxByteArrayLength ? value : Array.MaxByteArrayLength; Capacity = newCapacity; return true; } return false; } public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Flush(); return Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } public virtual byte[] GetBuffer() { if (!_exposable) throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer); return _buffer; } public virtual bool TryGetBuffer(out ArraySegment<byte> buffer) { if (!_exposable) { buffer = default(ArraySegment<byte>); return false; } buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin)); return true; } // -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) --------------- // PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer()) internal byte[] InternalGetBuffer() { return _buffer; } // PERF: Get origin and length - used in ResourceWriter. [FriendAccessAllowed] internal void InternalGetOriginAndLength(out int origin, out int length) { if (!_isOpen) __Error.StreamIsClosed(); origin = _origin; length = _length; } // PERF: True cursor position, we don't need _origin for direct access internal int InternalGetPosition() { if (!_isOpen) __Error.StreamIsClosed(); return _position; } // PERF: Takes out Int32 as fast as possible internal int InternalReadInt32() { if (!_isOpen) __Error.StreamIsClosed(); int pos = (_position += 4); // use temp to avoid a race condition if (pos > _length) { _position = _length; __Error.EndOfFile(); } return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24); } // PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes internal int InternalEmulateRead(int count) { if (!_isOpen) __Error.StreamIsClosed(); int n = _length - _position; if (n > count) n = count; if (n < 0) n = 0; Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. _position += n; return n; } // Gets & sets the capacity (number of bytes allocated) for this stream. // The capacity cannot be set to a value less than the current length // of the stream. // public virtual int Capacity { get { if (!_isOpen) __Error.StreamIsClosed(); return _capacity - _origin; } set { // Only update the capacity if the MS is expandable and the value is different than the current capacity. // Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity if (value < Length) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); Contract.Ensures(_capacity - _origin == value); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); if (!_expandable && (value != Capacity)) __Error.MemoryStreamNotExpandable(); // MemoryStream has this invariant: _origin > 0 => !expandable (see ctors) if (_expandable && value != _capacity) { if (value > 0) { byte[] newBuffer = new byte[value]; if (_length > 0) Buffer.InternalBlockCopy(_buffer, 0, newBuffer, 0, _length); _buffer = newBuffer; } else { _buffer = null; } _capacity = value; } } } public override long Length { get { if (!_isOpen) __Error.StreamIsClosed(); return _length - _origin; } } public override long Position { get { if (!_isOpen) __Error.StreamIsClosed(); return _position - _origin; } set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.Ensures(Position == value); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); if (value > MemStreamMaxLength) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); _position = _origin + (int)value; } } public override int Read([In, Out] byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); int n = _length - _position; if (n > count) n = count; if (n <= 0) return 0; Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. if (n <= 8) { int byteCount = n; while (--byteCount >= 0) buffer[offset + byteCount] = _buffer[_position + byteCount]; } else Buffer.InternalBlockCopy(_buffer, _position, buffer, offset, n); _position += n; return n; } public override int Read(Span<byte> destination) { if (GetType() != typeof(MemoryStream)) { // MemoryStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior // to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload // should use the behavior of Read(byte[],int,int) overload. return base.Read(destination); } if (!_isOpen) { __Error.StreamIsClosed(); } int n = Math.Min(_length - _position, destination.Length); if (n <= 0) { return 0; } // TODO https://github.com/dotnet/corefx/issues/22388: // Read(byte[], int, int) has an n <= 8 optimization, presumably based // on benchmarking. Determine if/where such a cut-off is here and add // an equivalent optimization if necessary. new Span<byte>(_buffer, _position, n).CopyTo(destination); _position += n; return n; } public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Read(...) // If cancellation was requested, bail early if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); try { int n = Read(buffer, offset, count); var t = _lastReadTask; Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion, "Expected that a stored last task completed successfully"); return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n)); } catch (OperationCanceledException oce) { return Task.FromCancellation<int>(oce); } catch (Exception exception) { return Task.FromException<int>(exception); } } public override int ReadByte() { if (!_isOpen) __Error.StreamIsClosed(); if (_position >= _length) return -1; return _buffer[_position++]; } public override void CopyTo(Stream destination, int bufferSize) { // Since we did not originally override this method, validate the arguments // the same way Stream does for back-compat. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read) when we are not sure. if (GetType() != typeof(MemoryStream)) { base.CopyTo(destination, bufferSize); return; } int originalPosition = _position; // Seek to the end of the MemoryStream. int remaining = InternalEmulateRead(_length - originalPosition); // If we were already at or past the end, there's no copying to do so just quit. if (remaining > 0) { // Call Write() on the other Stream, using our internal buffer and avoiding any // intermediary allocations. destination.Write(_buffer, originalPosition, remaining); } } public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { // This implementation offers beter performance compared to the base class version. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to ReadAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into ReadAsync) when we are not sure. if (this.GetType() != typeof(MemoryStream)) return base.CopyToAsync(destination, bufferSize, cancellationToken); // If cancelled - return fast: if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); // Avoid copying data from this buffer into a temp buffer: // (require that InternalEmulateRead does not throw, // otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below) Int32 pos = _position; Int32 n = InternalEmulateRead(_length - _position); // If destination is not a memory stream, write there asynchronously: MemoryStream memStrDest = destination as MemoryStream; if (memStrDest == null) return destination.WriteAsync(_buffer, pos, n, cancellationToken); try { // If destination is a MemoryStream, CopyTo synchronously: memStrDest.Write(_buffer, pos, n); return Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) __Error.StreamIsClosed(); if (offset > MemStreamMaxLength) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_StreamLength); switch (loc) { case SeekOrigin.Begin: { int tempPosition = unchecked(_origin + (int)offset); if (offset < 0 || tempPosition < _origin) throw new IOException(SR.IO_SeekBeforeBegin); _position = tempPosition; break; } case SeekOrigin.Current: { int tempPosition = unchecked(_position + (int)offset); if (unchecked(_position + offset) < _origin || tempPosition < _origin) throw new IOException(SR.IO_SeekBeforeBegin); _position = tempPosition; break; } case SeekOrigin.End: { int tempPosition = unchecked(_length + (int)offset); if (unchecked(_length + offset) < _origin || tempPosition < _origin) throw new IOException(SR.IO_SeekBeforeBegin); _position = tempPosition; break; } default: throw new ArgumentException(SR.Argument_InvalidSeekOrigin); } Debug.Assert(_position >= 0, "_position >= 0"); return _position; } // Sets the length of the stream to a given value. The new // value must be nonnegative and less than the space remaining in // the array, Int32.MaxValue - origin // Origin is 0 in all cases other than a MemoryStream created on // top of an existing array and a specific starting offset was passed // into the MemoryStream constructor. The upper bounds prevents any // situations where a stream may be created on top of an array then // the stream is made longer than the maximum possible length of the // array (Int32.MaxValue). // public override void SetLength(long value) { if (value < 0 || value > Int32.MaxValue) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } Contract.Ensures(_length - _origin == value); Contract.EndContractBlock(); EnsureWriteable(); // Origin wasn't publicly exposed above. Debug.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails. if (value > (Int32.MaxValue - _origin)) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } int newLength = _origin + (int)value; bool allocatedNewArray = EnsureCapacity(newLength); if (!allocatedNewArray && newLength > _length) Array.Clear(_buffer, _length, newLength - _length); _length = newLength; if (_position > newLength) _position = newLength; } public virtual byte[] ToArray() { BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy."); byte[] copy = new byte[_length - _origin]; Buffer.InternalBlockCopy(_buffer, _origin, copy, 0, _length - _origin); return copy; } public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); EnsureWriteable(); int i = _position + count; // Check for overflow if (i < 0) throw new IOException(SR.IO_StreamTooLong); if (i > _length) { bool mustZero = _position > _length; if (i > _capacity) { bool allocatedNewArray = EnsureCapacity(i); if (allocatedNewArray) mustZero = false; } if (mustZero) Array.Clear(_buffer, _length, i - _length); _length = i; } if ((count <= 8) && (buffer != _buffer)) { int byteCount = count; while (--byteCount >= 0) _buffer[_position + byteCount] = buffer[offset + byteCount]; } else Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count); _position = i; } public override void Write(ReadOnlySpan<byte> source) { if (GetType() != typeof(MemoryStream)) { // MemoryStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior // to this Write(Span<byte>) overload being introduced. In that case, this Write(Span<byte>) overload // should use the behavior of Write(byte[],int,int) overload. base.Write(source); return; } if (!_isOpen) { __Error.StreamIsClosed(); } EnsureWriteable(); // Check for overflow int i = _position + source.Length; if (i < 0) { throw new IOException(SR.IO_StreamTooLong); } if (i > _length) { bool mustZero = _position > _length; if (i > _capacity) { bool allocatedNewArray = EnsureCapacity(i); if (allocatedNewArray) { mustZero = false; } } if (mustZero) { Array.Clear(_buffer, _length, i - _length); } _length = i; } source.CopyTo(new Span<byte>(_buffer, _position, source.Length)); _position = i; } public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Write(...) // If cancellation is already requested, bail early if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Write(buffer, offset, count); return Task.CompletedTask; } catch (OperationCanceledException oce) { return Task.FromCancellation<VoidTaskResult>(oce); } catch (Exception exception) { return Task.FromException(exception); } } public override void WriteByte(byte value) { if (!_isOpen) __Error.StreamIsClosed(); EnsureWriteable(); if (_position >= _length) { int newLength = _position + 1; bool mustZero = _position > _length; if (newLength >= _capacity) { bool allocatedNewArray = EnsureCapacity(newLength); if (allocatedNewArray) mustZero = false; } if (mustZero) Array.Clear(_buffer, _length, _position - _length); _length = newLength; } _buffer[_position++] = value; } // Writes this MemoryStream to another stream. public virtual void WriteTo(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); stream.Write(_buffer, _origin, _length - _origin); } } }
// 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 Internal.TypeSystem; using Internal.IL; using Internal.Runtime; namespace ILCompiler { internal class JitHelper { /// <summary> /// Returns JIT helper entrypoint. JIT helpers can be either implemented by entrypoint with given mangled name or /// by a method in class library. /// </summary> public static void GetEntryPoint(TypeSystemContext context, ReadyToRunHelper id, out string mangledName, out MethodDesc methodDesc) { mangledName = null; methodDesc = null; switch (id) { case ReadyToRunHelper.Throw: mangledName = "RhpThrowEx"; break; case ReadyToRunHelper.Rethrow: mangledName = "RhpRethrow"; break; case ReadyToRunHelper.Overflow: methodDesc = context.GetHelperEntryPoint("ThrowHelpers", "ThrowOverflowException"); break; case ReadyToRunHelper.RngChkFail: methodDesc = context.GetHelperEntryPoint("ThrowHelpers", "ThrowIndexOutOfRangeException"); break; case ReadyToRunHelper.FailFast: mangledName = "__fail_fast"; // TODO: Report stack buffer overrun break; case ReadyToRunHelper.ThrowNullRef: methodDesc = context.GetHelperEntryPoint("ThrowHelpers", "ThrowNullReferenceException"); break; case ReadyToRunHelper.ThrowDivZero: methodDesc = context.GetHelperEntryPoint("ThrowHelpers", "ThrowDivideByZeroException"); break; case ReadyToRunHelper.ThrowArgumentOutOfRange: methodDesc = context.GetHelperEntryPoint("ThrowHelpers", "ThrowArgumentOutOfRangeException"); break; case ReadyToRunHelper.ThrowArgument: methodDesc = context.GetHelperEntryPoint("ThrowHelpers", "ThrowArgumentException"); break; case ReadyToRunHelper.ThrowPlatformNotSupported: methodDesc = context.GetHelperEntryPoint("ThrowHelpers", "ThrowPlatformNotSupportedException"); break; case ReadyToRunHelper.DebugBreak: mangledName = "RhDebugBreak"; break; case ReadyToRunHelper.WriteBarrier: mangledName = "RhpAssignRef"; break; case ReadyToRunHelper.CheckedWriteBarrier: mangledName = "RhpCheckedAssignRef"; break; case ReadyToRunHelper.ByRefWriteBarrier: mangledName = "RhpByRefAssignRef"; break; case ReadyToRunHelper.Box: case ReadyToRunHelper.Box_Nullable: mangledName = "RhBox"; break; case ReadyToRunHelper.Unbox: mangledName = "RhUnbox2"; break; case ReadyToRunHelper.Unbox_Nullable: mangledName = "RhUnboxNullable"; break; case ReadyToRunHelper.NewMultiDimArr_NonVarArg: methodDesc = context.GetHelperEntryPoint("ArrayHelpers", "NewObjArray"); break; case ReadyToRunHelper.NewArray: mangledName = "RhNewArray"; break; case ReadyToRunHelper.NewObject: mangledName = "RhNewObject"; break; case ReadyToRunHelper.Stelem_Ref: mangledName = "RhpStelemRef"; break; case ReadyToRunHelper.Ldelema_Ref: mangledName = "RhpLdelemaRef"; break; case ReadyToRunHelper.MemCpy: mangledName = "memcpy"; // TODO: Null reference handling break; case ReadyToRunHelper.MemSet: mangledName = "memset"; // TODO: Null reference handling break; case ReadyToRunHelper.GetRuntimeTypeHandle: methodDesc = context.GetHelperEntryPoint("LdTokenHelpers", "GetRuntimeTypeHandle"); break; case ReadyToRunHelper.GetRuntimeMethodHandle: methodDesc = context.GetHelperEntryPoint("LdTokenHelpers", "GetRuntimeMethodHandle"); break; case ReadyToRunHelper.GetRuntimeFieldHandle: methodDesc = context.GetHelperEntryPoint("LdTokenHelpers", "GetRuntimeFieldHandle"); break; case ReadyToRunHelper.Lng2Dbl: mangledName = "RhpLng2Dbl"; break; case ReadyToRunHelper.ULng2Dbl: mangledName = "RhpULng2Dbl"; break; case ReadyToRunHelper.Dbl2Lng: mangledName = "RhpDbl2Lng"; break; case ReadyToRunHelper.Dbl2ULng: mangledName = "RhpDbl2ULng"; break; case ReadyToRunHelper.Dbl2Int: mangledName = "RhpDbl2Int"; break; case ReadyToRunHelper.Dbl2UInt: mangledName = "RhpDbl2UInt"; break; case ReadyToRunHelper.Dbl2IntOvf: methodDesc = context.GetHelperEntryPoint("MathHelpers", "Dbl2IntOvf"); break; case ReadyToRunHelper.Dbl2UIntOvf: methodDesc = context.GetHelperEntryPoint("MathHelpers", "Dbl2UIntOvf"); break; case ReadyToRunHelper.Dbl2LngOvf: methodDesc = context.GetHelperEntryPoint("MathHelpers", "Dbl2LngOvf"); break; case ReadyToRunHelper.Dbl2ULngOvf: methodDesc = context.GetHelperEntryPoint("MathHelpers", "Dbl2ULngOvf"); break; case ReadyToRunHelper.DblRem: mangledName = "RhpDblRem"; break; case ReadyToRunHelper.FltRem: mangledName = "RhpFltRem"; break; case ReadyToRunHelper.DblRound: mangledName = "RhpDblRound"; break; case ReadyToRunHelper.FltRound: mangledName = "RhpFltRound"; break; case ReadyToRunHelper.LMul: mangledName = "RhpLMul"; break; case ReadyToRunHelper.LMulOfv: methodDesc = context.GetHelperEntryPoint("MathHelpers", "LMulOvf"); break; case ReadyToRunHelper.ULMulOvf: methodDesc = context.GetHelperEntryPoint("MathHelpers", "ULMulOvf"); break; case ReadyToRunHelper.Mod: methodDesc = context.GetHelperEntryPoint("MathHelpers", "IMod"); break; case ReadyToRunHelper.UMod: methodDesc = context.GetHelperEntryPoint("MathHelpers", "UMod"); break; case ReadyToRunHelper.ULMod: methodDesc = context.GetHelperEntryPoint("MathHelpers", "ULMod"); break; case ReadyToRunHelper.LMod: methodDesc = context.GetHelperEntryPoint("MathHelpers", "LMod"); break; case ReadyToRunHelper.Div: methodDesc = context.GetHelperEntryPoint("MathHelpers", "IDiv"); break; case ReadyToRunHelper.UDiv: methodDesc = context.GetHelperEntryPoint("MathHelpers", "UDiv"); break; case ReadyToRunHelper.ULDiv: methodDesc = context.GetHelperEntryPoint("MathHelpers", "ULDiv"); break; case ReadyToRunHelper.LDiv: methodDesc = context.GetHelperEntryPoint("MathHelpers", "LDiv"); break; case ReadyToRunHelper.LRsz: mangledName = "RhpLRsz"; break; case ReadyToRunHelper.LRsh: mangledName = "RhpLRsh"; break; case ReadyToRunHelper.LLsh: mangledName = "RhpLLsh"; break; case ReadyToRunHelper.PInvokeBegin: mangledName = "RhpPInvoke"; break; case ReadyToRunHelper.PInvokeEnd: mangledName = "RhpPInvokeReturn"; break; case ReadyToRunHelper.ReversePInvokeEnter: mangledName = "RhpReversePInvoke2"; break; case ReadyToRunHelper.ReversePInvokeExit: mangledName = "RhpReversePInvokeReturn2"; break; case ReadyToRunHelper.CheckCastAny: mangledName = "RhTypeCast_CheckCast2"; break; case ReadyToRunHelper.CheckInstanceAny: mangledName = "RhTypeCast_IsInstanceOf2"; break; case ReadyToRunHelper.MonitorEnter: methodDesc = context.GetHelperEntryPoint("SynchronizedMethodHelpers", "MonitorEnter"); break; case ReadyToRunHelper.MonitorExit: methodDesc = context.GetHelperEntryPoint("SynchronizedMethodHelpers", "MonitorExit"); break; case ReadyToRunHelper.MonitorEnterStatic: methodDesc = context.GetHelperEntryPoint("SynchronizedMethodHelpers", "MonitorEnterStatic"); break; case ReadyToRunHelper.MonitorExitStatic: methodDesc = context.GetHelperEntryPoint("SynchronizedMethodHelpers", "MonitorExitStatic"); break; case ReadyToRunHelper.GVMLookupForSlot: methodDesc = context.SystemModule.GetKnownType("System.Runtime", "TypeLoaderExports").GetKnownMethod("GVMLookupForSlot", null); break; case ReadyToRunHelper.TypeHandleToRuntimeType: methodDesc = context.GetHelperEntryPoint("TypedReferenceHelpers", "TypeHandleToRuntimeTypeMaybeNull"); break; case ReadyToRunHelper.GetRefAny: methodDesc = context.GetHelperEntryPoint("TypedReferenceHelpers", "GetRefAny"); break; default: throw new NotImplementedException(id.ToString()); } } // // These methods are static compiler equivalent of RhGetRuntimeHelperForType // public static string GetNewObjectHelperForType(TypeDesc type) { if (EETypeBuilderHelpers.ComputeRequiresAlign8(type)) { if (type.HasFinalizer) return "RhpNewFinalizableAlign8"; if (type.IsValueType) return "RhpNewFastMisalign"; return "RhpNewFastAlign8"; } if (type.HasFinalizer) return "RhpNewFinalizable"; return "RhpNewFast"; } public static string GetNewArrayHelperForType(TypeDesc type) { if (EETypeBuilderHelpers.ComputeRequiresAlign8(type)) return "RhpNewArrayAlign8"; return "RhpNewArray"; } public static string GetCastingHelperNameForType(TypeDesc type, bool throwing) { if (type.IsArray) return throwing ? "RhTypeCast_CheckCastArray" : "RhTypeCast_IsInstanceOfArray"; if (type.IsInterface) return throwing ? "RhTypeCast_CheckCastInterface" : "RhTypeCast_IsInstanceOfInterface"; return throwing ? "RhTypeCast_CheckCastClass" : "RhTypeCast_IsInstanceOfClass"; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using owin_scim_host.Areas.HelpPage.ModelDescriptions; using owin_scim_host.Areas.HelpPage.Models; namespace owin_scim_host.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; namespace DiskQueue.Implementation { /// <summary> /// Default persistent queue session. /// <para>You should use <see cref="IPersistentQueue.OpenSession"/> to get a session.</para> /// <example>using (var q = PersistentQueue.WaitFor("myQueue")) using (var session = q.OpenSession()) { ... }</example> /// </summary> public sealed class PersistentQueueSession : IPersistentQueueSession { private readonly List<Operation> operations = new List<Operation>(); private readonly IList<Exception> pendingWritesFailures = new List<Exception>(); private readonly IList<WaitHandle> pendingWritesHandles = new List<WaitHandle>(); private Stream currentStream; private readonly int writeBufferSize; private readonly IPersistentQueueImpl queue; private readonly List<Stream> streamsToDisposeOnFlush = new List<Stream>(); static readonly object _ctorLock = new object(); volatile bool disposed; private readonly List<byte[]> buffer = new List<byte[]>(); private int bufferSize; private const int MinSizeThatMakeAsyncWritePractical = 64 * 1024; /// <summary> /// Create a default persistent queue session. /// <para>You should use <see cref="IPersistentQueue.OpenSession"/> to get a session.</para> /// <example>using (var q = PersistentQueue.WaitFor("myQueue")) using (var session = q.OpenSession()) { ... }</example> /// </summary> public PersistentQueueSession(IPersistentQueueImpl queue, Stream currentStream, int writeBufferSize) { lock (_ctorLock) { this.queue = queue; this.currentStream = currentStream; if (writeBufferSize < MinSizeThatMakeAsyncWritePractical) writeBufferSize = MinSizeThatMakeAsyncWritePractical; this.writeBufferSize = writeBufferSize; disposed = false; } } /// <summary> /// Queue data for a later decode. Data is written on `Flush()` /// </summary> public void Enqueue(byte[] data) { buffer.Add(data); bufferSize += data.Length; if (bufferSize > writeBufferSize) { AsyncFlushBuffer(); } } private void AsyncFlushBuffer() { queue.AcquireWriter(currentStream, AsyncWriteToStream, OnReplaceStream); } private void SyncFlushBuffer() { queue.AcquireWriter(currentStream, stream => { byte[] data = ConcatenateBufferAndAddIndividualOperations(stream); stream.Write(data, 0, data.Length); return stream.Position; }, OnReplaceStream); } private long AsyncWriteToStream(Stream stream) { byte[] data = ConcatenateBufferAndAddIndividualOperations(stream); var resetEvent = new ManualResetEvent(false); pendingWritesHandles.Add(resetEvent); long positionAfterWrite = stream.Position + data.Length; stream.BeginWrite(data, 0, data.Length, delegate(IAsyncResult ar) { try { stream.EndWrite(ar); } catch (Exception e) { lock (pendingWritesFailures) { pendingWritesFailures.Add(e); } } finally { resetEvent.Set(); } }, null); return positionAfterWrite; } private byte[] ConcatenateBufferAndAddIndividualOperations(Stream stream) { var data = new byte[bufferSize]; var start = (int)stream.Position; var index = 0; foreach (var bytes in buffer) { operations.Add(new Operation( OperationType.Enqueue, queue.CurrentFileNumber, start, bytes.Length )); Buffer.BlockCopy(bytes, 0, data, index, bytes.Length); start += bytes.Length; index += bytes.Length; } bufferSize = 0; buffer.Clear(); return data; } private void OnReplaceStream(Stream newStream) { streamsToDisposeOnFlush.Add(currentStream); currentStream = newStream; } /// <summary> /// Try to pull data from the queue. Data is removed from the queue on `Flush()` /// </summary> public byte[] Dequeue() { var entry = queue.Dequeue(); if (entry == null) return null; operations.Add(new Operation( OperationType.Dequeue, entry.FileNumber, entry.Start, entry.Length )); return entry.Data; } /// <summary> /// Commit actions taken in this session since last flush. /// If the session is disposed with no flush, actions are not persisted /// to the queue (Enqueues are not written, dequeues are left on the queue) /// </summary> public void Flush() { try { WaitForPendingWrites(); SyncFlushBuffer(); } finally { foreach (var stream in streamsToDisposeOnFlush) { stream.Flush(); stream.Dispose(); } streamsToDisposeOnFlush.Clear(); } currentStream.Flush(); queue.CommitTransaction(operations); operations.Clear(); } private void WaitForPendingWrites() { while (pendingWritesHandles.Count != 0) { var handles = pendingWritesHandles.Take(64).ToArray(); foreach (var handle in handles) { pendingWritesHandles.Remove(handle); } WaitHandle.WaitAll(handles); foreach (var handle in handles) { handle.Close(); } AssertNoPendingWritesFailures(); } } private void AssertNoPendingWritesFailures() { lock (pendingWritesFailures) { if (pendingWritesFailures.Count == 0) return; var array = pendingWritesFailures.ToArray(); pendingWritesFailures.Clear(); throw new PendingWriteException(array); } } /// <summary> /// Close session, restoring any non-flushed operations /// </summary> public void Dispose() { lock (_ctorLock) { if (disposed) return; disposed = true; queue.Reinstate(operations); operations.Clear(); foreach (var stream in streamsToDisposeOnFlush) { stream.Dispose(); } currentStream.Dispose(); GC.SuppressFinalize(this); } Thread.Sleep(0); } /// <summary> /// Dispose queue on destructor. This is a safty-valve. You should ensure you /// dispose of sessions normally. /// </summary> ~PersistentQueueSession() { if (disposed) return; Dispose(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; namespace Pulsar4X.UI.Panels { public partial class ClassDes_Options : DockContent { #region Properties /// <summary> /// For selecting the current Faction /// </summary> public ComboBox FactionComboBox { get { return m_oFactionComboBox; } } /// <summary> /// For selecting the current Class /// </summary> public ComboBox ClassComboBox { get { return m_oClassComboBox; } } /// <summary> /// For selecting the Current Class Type /// </summary> public ComboBox TypeComboBox { get { return m_oTypeComboBox; } } /// <summary> /// For selecting the current Hull Type /// </summary> public ComboBox HullComboBox { get { return m_oHullComboBox; } } public bool ShowCivilianDesigns { get { return m_oShowCivilianDesignsCheckBox.Checked; } set { m_oShowCivilianDesignsCheckBox.Checked = value; } } public CheckBox ShowCivilianDesignsCheckBox { get { return m_oShowCivilianDesignsCheckBox; } } public bool NoThemeName { get { return m_oNoThemeCheckBox.Checked; } set { m_oNoThemeCheckBox.Checked = value; } } public CheckBox NoThemeNameCheckBox { get { return m_oNoThemeCheckBox; } } public bool HideObsolete { get { return m_oHideObsoleteCheckBox.Checked; } set { m_oHideObsoleteCheckBox.Checked = value; } } public CheckBox HideObsoleteCheckBox { get { return m_oHideObsoleteCheckBox; } } public bool Tanker { get { return m_oTankerCheckBox.Checked; } set { m_oTankerCheckBox.Checked = value; } } public CheckBox TankerCheckBox { get { return m_oTankerCheckBox; } } public bool Collier { get { return m_oCollierCheckBox.Checked; } set { m_oCollierCheckBox.Checked = value; } } public CheckBox CollierCheckBox { get { return m_oCollierCheckBox; } } public bool Conscript { get { return m_oConscriptCheckBox.Checked; } set { m_oConscriptCheckBox.Checked = value; } } public bool SupplyShip { get { return m_oSupplyShipCheckBox.Checked; } set { m_oSupplyShipCheckBox.Checked = value; } } public CheckBox SupplyShipCheckBox { get { return m_oSupplyShipCheckBox; } } public CheckBox SizeInTonsCheckBox { get { return m_oSizeinTonsCheckBox; } } public bool Obsolete { get { return m_oObsoleteCheckBox.Checked; } set { m_oObsoleteCheckBox.Checked = value; } } public CheckBox KeepExcessQuarters { get { return m_oKeepExcessQCheckBox; } } public Button RenameButton { get { return m_oRenameButton; } } public Button AutoRenameButton { get { return m_oAutoRenameButton; } } public Button ReNumberButton { get { return m_oReNumberButton; } } public Button RandomNameButton { get { return m_oRandomNameButton; } } public Button NewButton { get { return m_oNewButton; } } public Button DeleteButton { get { return m_oDeleteButton; } } public Button NPRClassButton { get { return NPRClassButton; } } public Button DesignTechButton { get { return m_oDesignTechButton; } } public Button NewArmorButton { get { return m_oNewArmorButton; } } public Button NewHullButton { get { return m_oNewHullButton; } } public Button LockDesignButton { get { return m_oLockDesignButton; } } public Button CopyDesignButton { get { return m_oCopyDesignButton; } } public Button RefreshTechButton { get { return m_oRefreshTechButton; } } public Button ObsoleteCompButton { get { return m_oObsoleteCompButton; } } public Button FleetAssignButton { get { return m_oFleetAssignBbutton; } } public Button ViewTechButton { get { return m_oViewTechButton; } } public Button TextFileButton { get { return m_oTextFileButton; } } public Button SMModeButton { get { return m_oSMModeButton; } } public ComboBox MiniumRankComboBox { get { return m_oMiniumRankComboBox; } } public TextBox ClassPriority { get { return m_oClassPriorityTextBox; } } public Button SetRankInfoAndClassPriority { get { return m_oSetRankInfoButton; } } /// <summary> /// Allows the player to select a list of names this class will use. /// </summary> public ComboBox NameType { get { return m_oNameTypeComboBox; } } public ComboBox RefitFromSelection { get { return m_oRefitCostFromSelectionComboBox; } } public TextBox RefitCostFrom { get { return m_oRefitCostFromTextBox; } } public RichTextBox Notes { get { return m_oNotesRichTextBox; } } public Button SaveNotes { get { return m_oSaveNotesButton; } } #endregion /// <summary> /// Display for Ship information. /// </summary> private DataGridView m_oComponentDataGrid; public DataGridView ComponentDataGrid { get { return m_oComponentDataGrid; } } /// <summary> /// Display for selecting ordnance loadouts on the ordnance/fighters page. /// </summary> private DataGridView m_oMissileDataGrid; public DataGridView MissileDataGrid { get { return m_oMissileDataGrid; } } /// <summary> /// Preferred strikegroup selection display. /// </summary> private DataGridView m_oFighterDataGrid; public DataGridView FighterDataGrid { get { return m_oFighterDataGrid; } } public ClassDes_Options() { InitializeComponent(); this.AutoHidePortion = 0.2f; this.HideOnClose = true; this.Text = "Class Design Options"; this.TabText = "Class Design Options"; this.ToolTipText = "Class Design Options"; // events to make sure that only one sort button is active at a time. m_oSortAlphaRadioButton.CheckedChanged += new EventHandler(m_oSortAlphaRadioButton_CheckedChanged); m_oSortCostRadioButton.CheckedChanged += new EventHandler(m_oSortCostRadioButton_CheckedChanged); m_oSortHullRadioButton.CheckedChanged += new EventHandler(m_oSortHullRadioButton_CheckedChanged); m_oSortSizeRadioButton.CheckedChanged += new EventHandler(m_oSortSizeRadioButton_CheckedChanged); m_oComponentDataGrid = new DataGridView(); m_oComponentDataGrid.Dock = DockStyle.Top; m_oComponentDataGrid.SetBounds(3, 3, 745, 350); m_oComponentDataGrid.AllowUserToAddRows = false; m_oComponentDataGrid.AllowUserToDeleteRows = false; m_oComponentDataGrid.AllowUserToOrderColumns = false; m_oComponentDataGrid.AllowUserToResizeColumns = false; m_oComponentDataGrid.AllowUserToResizeRows = false; m_oComponentDataGrid.MultiSelect = false; m_oComponentDataGrid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; m_oComponentDataGrid.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; m_oComponentDataGrid.ReadOnly = true; m_oComponentDataGrid.Enabled = true; this.m_oAvailCompGroupBox.Controls.Add(m_oComponentDataGrid); m_oMissileDataGrid = new DataGridView(); m_oMissileDataGrid.Dock = DockStyle.Top; m_oMissileDataGrid.SetBounds(3, 3, 745, 350); m_oMissileDataGrid.AllowUserToAddRows = false; m_oMissileDataGrid.AllowUserToDeleteRows = false; m_oMissileDataGrid.AllowUserToOrderColumns = false; m_oMissileDataGrid.AllowUserToResizeColumns = false; m_oMissileDataGrid.AllowUserToResizeRows = false; m_oMissileDataGrid.MultiSelect = false; m_oMissileDataGrid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; m_oMissileDataGrid.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; m_oMissileDataGrid.RowHeadersVisible = false; m_oMissileDataGrid.ReadOnly = true; m_oMissileDataGrid.Enabled = true; this.m_oMissileGroupBox.Controls.Add(m_oMissileDataGrid); m_oFighterDataGrid = new DataGridView(); m_oFighterDataGrid.Dock = DockStyle.Top; m_oFighterDataGrid.SetBounds(3, 3, 745, 350); m_oFighterDataGrid.AllowUserToAddRows = false; m_oFighterDataGrid.AllowUserToDeleteRows = false; m_oFighterDataGrid.AllowUserToOrderColumns = false; m_oFighterDataGrid.AllowUserToResizeColumns = false; m_oFighterDataGrid.AllowUserToResizeRows = false; m_oFighterDataGrid.MultiSelect = false; m_oFighterDataGrid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; m_oFighterDataGrid.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; m_oFighterDataGrid.RowHeadersVisible = false; m_oFighterDataGrid.ReadOnly = true; m_oFighterDataGrid.Enabled = true; this.m_oStrikeGroupBox.Controls.Add(m_oFighterDataGrid); } #region Events void m_oSortSizeRadioButton_CheckedChanged(object sender, EventArgs e) { if (m_oSortSizeRadioButton.Checked == true) { m_oSortCostRadioButton.Checked = false; m_oSortHullRadioButton.Checked = false; m_oSortAlphaRadioButton.Checked = false; } } void m_oSortHullRadioButton_CheckedChanged(object sender, EventArgs e) { if (m_oSortHullRadioButton.Checked == true) { m_oSortCostRadioButton.Checked = false; m_oSortSizeRadioButton.Checked = false; m_oSortAlphaRadioButton.Checked = false; } } void m_oSortCostRadioButton_CheckedChanged(object sender, EventArgs e) { if (m_oSortCostRadioButton.Checked == true) { m_oSortHullRadioButton.Checked = false; m_oSortSizeRadioButton.Checked = false; m_oSortAlphaRadioButton.Checked = false; } } void m_oSortAlphaRadioButton_CheckedChanged(object sender, EventArgs e) { if (m_oSortAlphaRadioButton.Checked == true) { m_oSortHullRadioButton.Checked = false; m_oSortSizeRadioButton.Checked = false; m_oSortCostRadioButton.Checked = false; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests.FunctionalTests.Location.Steps { /// <summary> /// Location Steps (matches) /// </summary> public static partial class MatchesTests { /// <summary> /// Invalid Location Step - Missing axis . Expected error. /// /::bookstore /// </summary> [Fact] public static void MatchesTest151() { var xml = "books.xml"; var testExpression = @"/::bookstore"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Invalid Location Step - Missing Node test. Expected error. /// /child:: /// </summary> [Fact] public static void MatchesTest152() { var xml = "books.xml"; var testExpression = @"/child::"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Invalid Location Step - Using an invalid axis. Expected error. /// /bookstore/sibling::book /// </summary> [Fact] public static void MatchesTest153() { var xml = "books.xml"; var testExpression = @"/bookstore/sibling::book"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Invalid Location Step - Multiple axis. Location step can have only one axis. Test expresion uses nultiple axis. Expected error. /// /bookstore/child::ancestor::book /// </summary> [Fact] public static void MatchesTest154() { var xml = "books.xml"; var testExpression = @"/bookstore/child::ancestor::book"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Invalid Location Step - Multiple node tests using | - Multiple node-tests are not allowed. Test uses | to union two node tests. Error expected. /// /bookstore/child::(book | magazine) /// </summary> [Fact] public static void MatchesTest155() { var xml = "books.xml"; var testExpression = @"/bookstore/child::(book | magazine)"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Invalid Location Step - Multiple node tests using | - Multiple node-tests are not allowed. Test uses 'and' to combine two node tests. Error expected. /// /bookstore/book and magazine /// </summary> [Fact] public static void MatchesTest156() { var xml = "books.xml"; var testExpression = @"/bookstore/book and magazine"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Invalid Location Step - Multiple node tests using 'or' - Multiple node-tests are not allowed. Test uses 'or' to combine two node tests. Error expected. /// /bookstore/book or magazine /// </summary> [Fact] public static void MatchesTest157() { var xml = "books.xml"; var testExpression = @"/bookstore/book or magazine"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Valid Location step - Single predicate /// /bookstore/* [name()='book'] /// </summary> [Fact] public static void MatchesTest158() { var xml = "books.xml"; var startingNodePath = "/bookstore/book"; var testExpression = @"/bookstore/* [name()='book']"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Valid Location Step - Multiple predicates /// /bookstore/* [name()='book' or name()='magazine'][name()='magazine'] /// </summary> [Fact] public static void MatchesTest159() { var xml = "books.xml"; var startingNodePath = "/bookstore/magazine"; var testExpression = @"/bookstore/* [name()='book' or name()='magazine'][name()='magazine']"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Valid Location Step - No predicates /// /bookstore/book /// </summary> [Fact] public static void MatchesTest1510() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[5]"; var testExpression = @"/bookstore/book"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Check order of predicates - Test to check if the predicates are applied in the correct order. Should select the 3rd book node in the XML doc. /// /bookstore/book [position() = 1 or position() = 3 or position() = 6][position() = 2] /// </summary> [Fact] public static void MatchesTest1511() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[3]"; var testExpression = @"/bookstore/book [position() = 1 or position() = 3 or position() = 6][position() = 2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected Error : Abbreviated Axis specifier '.' is a valid location step, but not allowed in matches /// /. /// </summary> [Fact] public static void MatchesTest1512() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"/."; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected Error : Abbreviated Axis specifier '..' is a valid location step, but not allowed in matches /// /bookstore/book/.. /// </summary> [Fact] public static void MatchesTest1513() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"/bookstore/book/.."; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Invalid Expression '..' with node test. Node test is not allowed with an abbreviated axis specifier /// /bookstore/*/title/.. book /// </summary> [Fact] public static void MatchesTest1514() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[1]"; var testExpression = @"/bookstore/*/title/.. book"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Invalid Expression '.' with node test. Predicates are not allowed with abbreviated axis specifiers. /// /bookstore/*/title/.[name()='book'] /// </summary> [Fact] public static void MatchesTest1515() { var xml = "books.xml"; var startingNodePath = "/bookstore/book"; var testExpression = @"/bookstore/*/title/.[name()='book']"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Rest.Azure; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Newtonsoft.Json; using System.Collections.Generic; using Xunit; namespace Compute.Tests { public class VMOperationalTests : VMTestBase { class Image { [JsonProperty("uri")] public string Uri { get; set; } } class OSDisk { [JsonProperty("image")] public Image Image { get; set; } } class StorageProfile { [JsonProperty("osDisk")] public OSDisk OSDisk { get; set; } } class Properties { [JsonProperty("storageProfile")] public StorageProfile StorageProfile { get; set; } } class Resource { [JsonProperty("properties")] public Properties Properties { get; set; } } class Template { [JsonProperty("resources")] public List<Resource> Resources { get; set; } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VM /// GET VM Model View /// Start VM /// Stop VM /// Restart VM /// RunCommand VM /// Deallocate VM /// Generalize VM /// Capture VM /// Delete RG /// </summary> [Fact] public void TestVMOperations() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true, sku: "2019-Datacenter-smalldisk"); // Create resource group string rg1Name = ComputeManagementTestUtilities.GenerateName(TestPrefix) + 1; string as1Name = ComputeManagementTestUtilities.GenerateName("as"); string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix); VirtualMachine inputVM1; try { // Create Storage Account, so that both the VMs can share it var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName); VirtualMachine vm1 = CreateVM(rg1Name, as1Name, storageAccountOutput, imageRef, out inputVM1); m_CrpClient.VirtualMachines.Start(rg1Name, vm1.Name); m_CrpClient.VirtualMachines.Redeploy(rg1Name, vm1.Name); m_CrpClient.VirtualMachines.Restart(rg1Name, vm1.Name); m_CrpClient.VirtualMachines.PowerOff(rg1Name, vm1.Name); m_CrpClient.VirtualMachines.Deallocate(rg1Name, vm1.Name); m_CrpClient.VirtualMachines.Generalize(rg1Name, vm1.Name); VirtualMachine ephemeralVM; string as2Name = as1Name + "_ephemeral"; CreateVM(rg1Name, as2Name, storageAccountName, imageRef, out ephemeralVM, hasManagedDisks: true, hasDiffDisks: true, vmSize: VirtualMachineSizeTypes.StandardDS5V2, osDiskStorageAccountType: StorageAccountTypes.StandardLRS, dataDiskStorageAccountType: StorageAccountTypes.StandardLRS); m_CrpClient.VirtualMachines.Reimage(rg1Name, ephemeralVM.Name, tempDisk: true); var captureParams = new VirtualMachineCaptureParameters { DestinationContainerName = ComputeManagementTestUtilities.GenerateName(TestPrefix), VhdPrefix = ComputeManagementTestUtilities.GenerateName(TestPrefix), OverwriteVhds = true }; var captureResponse = m_CrpClient.VirtualMachines.Capture(rg1Name, vm1.Name, captureParams); Assert.NotNull(captureResponse); Assert.True(captureResponse.Resources.Count > 0); string resource = captureResponse.Resources[0].ToString(); Assert.Contains(captureParams.DestinationContainerName.ToLowerInvariant(), resource.ToLowerInvariant()); Assert.Contains(captureParams.VhdPrefix.ToLowerInvariant(), resource.ToLowerInvariant()); Resource template = JsonConvert.DeserializeObject<Resource>(resource); string imageUri = template.Properties.StorageProfile.OSDisk.Image.Uri; Assert.False(string.IsNullOrEmpty(imageUri)); // Create 3rd VM from the captured image // TODO : Provisioning Time-out Issues VirtualMachine inputVM2; string as3Name = as1Name + "b"; VirtualMachine vm3 = CreateVM(rg1Name, as3Name, storageAccountOutput, imageRef, out inputVM2, vm => { vm.StorageProfile.ImageReference = null; vm.StorageProfile.OsDisk.Image = new VirtualHardDisk { Uri = imageUri }; vm.StorageProfile.OsDisk.Vhd.Uri = vm.StorageProfile.OsDisk.Vhd.Uri.Replace(".vhd", "copy.vhd"); vm.StorageProfile.OsDisk.OsType = OperatingSystemTypes.Windows; }, false, false); Assert.True(vm3.StorageProfile.OsDisk.Image.Uri == imageUri); } finally { // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose // of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rg1Name); } } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VM /// GET VM Model View /// Redeploy VM /// Delete RG /// </summary> [Fact] public void TestVMOperations_Redeploy() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group string rg1Name = TestUtilities.GenerateName(TestPrefix) + 1; string asName = TestUtilities.GenerateName("as"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachine inputVM1; bool passed = false; try { // Create Storage Account, so that both the VMs can share it var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName); VirtualMachine vm1 = CreateVM(rg1Name, asName, storageAccountOutput, imageRef, out inputVM1); var redeployOperationResponse = m_CrpClient.VirtualMachines.BeginRedeployWithHttpMessagesAsync(rg1Name, vm1.Name); //Assert.Equal(HttpStatusCode.Accepted, redeployOperationResponse.Result.Response.StatusCode); var lroResponse = m_CrpClient.VirtualMachines.RedeployWithHttpMessagesAsync(rg1Name, vm1.Name).GetAwaiter().GetResult(); //Assert.Equal(ComputeOperationStatus.Succeeded, lroResponse.Status); passed = true; } finally { // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose // of the test to cover deletion. CSM does persistent retrying over all RG resources. var deleteRg1Response = m_ResourcesClient.ResourceGroups.BeginDeleteWithHttpMessagesAsync(rg1Name); //Assert.True(deleteRg1Response.StatusCode == HttpStatusCode.Accepted, // "BeginDeleting status was not Accepted."); } Assert.True(passed); } } [Fact] public void TestVMOperations_Reapply() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group string rg1Name = TestUtilities.GenerateName(TestPrefix) + 1; string asName = TestUtilities.GenerateName("as"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachine inputVM1; bool passed = false; try { // Create Storage Account, so that both the VMs can share it var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName); VirtualMachine vm1 = CreateVM(rg1Name, asName, storageAccountOutput, imageRef, out inputVM1); var reapplyperationResponse = m_CrpClient.VirtualMachines.BeginReapplyWithHttpMessagesAsync(rg1Name, vm1.Name); var lroResponse = m_CrpClient.VirtualMachines.ReapplyWithHttpMessagesAsync(rg1Name, vm1.Name).GetAwaiter().GetResult(); passed = true; } finally { // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose // of the test to cover deletion. CSM does persistent retrying over all RG resources. var deleteRg1Response = m_ResourcesClient.ResourceGroups.BeginDeleteWithHttpMessagesAsync(rg1Name); } Assert.True(passed); } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create VM /// Start VM /// Shutdown VM with skipShutdown = true /// Delete RG /// </summary> [Fact] public void TestVMOperations_PowerOffWithSkipShutdown() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group string rg1Name = TestUtilities.GenerateName(TestPrefix) + 1; string asName = TestUtilities.GenerateName("as"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachine inputVM1; bool passed = false; try { // Create Storage Account for this VM var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName); VirtualMachine vm1 = CreateVM(rg1Name, asName, storageAccountOutput, imageRef, out inputVM1); m_CrpClient.VirtualMachines.Start(rg1Name, vm1.Name); // Shutdown VM with SkipShutdown = true m_CrpClient.VirtualMachines.PowerOff(rg1Name, vm1.Name, true); passed = true; } finally { // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose // of the test to cover deletion. CSM does persistent retrying over all RG resources. var deleteRg1Response = m_ResourcesClient.ResourceGroups.BeginDeleteWithHttpMessagesAsync(rg1Name); } Assert.True(passed); } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VM /// GET VM Model View /// PerformMaintenance VM /// Delete RG /// </summary> [Fact] public void TestVMOperations_PerformMaintenance() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group string rg1Name = TestUtilities.GenerateName(TestPrefix) + 1; string asName = TestUtilities.GenerateName("as"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachine inputVM1 = null; bool passed = false; try { // Create Storage Account, so that both the VMs can share it var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName); VirtualMachine vm1 = CreateVM(rg1Name, asName, storageAccountOutput, imageRef, out inputVM1); m_CrpClient.VirtualMachines.PerformMaintenance(rg1Name, vm1.Name); passed = true; } catch (CloudException cex) { passed = true; string expectedMessage = $"Operation 'performMaintenance' is not allowed on VM '{inputVM1.Name}' since the Subscription of this VM" + " is not eligible."; Assert.Equal(expectedMessage, cex.Message); } finally { // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose // of the test to cover deletion. CSM does persistent retrying over all RG resources. var deleteRg1Response = m_ResourcesClient.ResourceGroups.BeginDeleteWithHttpMessagesAsync(rg1Name); } Assert.True(passed); } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VM /// Call SimulateEviction on that VM /// Delete RG /// </summary> [Fact] public void TestVMOperations_SimulateEviction() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group string rg1Name = TestUtilities.GenerateName(TestPrefix) + 1; string asName = TestUtilities.GenerateName("as"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachine inputVM1; bool passed = false; try { // Create Storage Account, so that both the VMs can share it var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName); VirtualMachine vm1 = CreateVM(rg1Name, asName, storageAccountOutput.Name, imageRef, out inputVM1, (virtualMachine) => { virtualMachine.Priority = VirtualMachinePriorityTypes.Spot; virtualMachine.AvailabilitySet = null; virtualMachine.BillingProfile = new BillingProfile { MaxPrice = -1 }; }, vmSize: VirtualMachineSizeTypes.StandardA1); m_CrpClient.VirtualMachines.SimulateEviction(rg1Name, vm1.Name); passed = true; } finally { // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose // of the test to cover deletion. CSM does persistent retrying over all RG resources. var deleteRg1Response = m_ResourcesClient.ResourceGroups.BeginDeleteWithHttpMessagesAsync(rg1Name); } Assert.True(passed); } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VM /// Call RunCommand on that VM /// Delete RG /// </summary> [Fact] public void TestVMOperations_RunCommand() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group string rg1Name = ComputeManagementTestUtilities.GenerateName(TestPrefix) + 1; string as1Name = ComputeManagementTestUtilities.GenerateName("as"); string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix); VirtualMachine inputVM1; try { // Create Storage Account, so that both the VMs can share it var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName); VirtualMachine vm1 = CreateVM(rg1Name, as1Name, storageAccountOutput, imageRef, out inputVM1); var runCommandImput = new RunCommandInput() { CommandId = "RunPowerShellScript", Script = new List<string>() { "param(", " [string]$arg1,", " [string]$arg2", ")", "echo This is a sample script with parameters $arg1 $arg2" }, Parameters = new List<RunCommandInputParameter>() { new RunCommandInputParameter("arg1","value1"), new RunCommandInputParameter("arg2","value2"), } }; RunCommandResult result = m_CrpClient.VirtualMachines.RunCommand(rg1Name, vm1.Name, runCommandImput); Assert.NotNull(result); Assert.NotNull(result.Value); Assert.True(result.Value.Count > 0); } finally { // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose // of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rg1Name); } } } } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Linq; using System.Security.Principal; using EventStore.Core.Bus; using EventStore.Core.Data; using EventStore.Core.Helpers; using EventStore.Core.Messages; using EventStore.Core.Messaging; using EventStore.Core.Services.TimerService; using EventStore.Core.TransactionLog.LogRecords; using EventStore.Projections.Core.Messages; namespace EventStore.Projections.Core.Services.Processing { public class EventByTypeIndexEventReader : EventReader { private const int _maxReadCount = 111; private readonly HashSet<string> _eventTypes; private readonly bool _resolveLinkTos; private readonly ITimeProvider _timeProvider; private class PendingEvent { public readonly EventRecord Event; public readonly EventRecord PositionEvent; public readonly float Progress; public readonly TFPos TfPosition; public PendingEvent(EventRecord @event, EventRecord positionEvent, TFPos tfPosition, float progress) { Event = @event; PositionEvent = positionEvent; Progress = progress; TfPosition = tfPosition; } } private int _deliveredEvents; private State _state; private TFPos _lastEventPosition; private readonly Dictionary<string, int> _fromPositions; private readonly Dictionary<string, string> _streamToEventType; public EventByTypeIndexEventReader( IODispatcher ioDispatcher, IPublisher publisher, Guid eventReaderCorrelationId, IPrincipal readAs, string[] eventTypes, TFPos fromTfPosition, Dictionary<string, int> fromPositions, bool resolveLinkTos, ITimeProvider timeProvider, bool stopOnEof = false, int? stopAfterNEvents = null) : base(ioDispatcher, publisher, eventReaderCorrelationId, readAs, stopOnEof, stopAfterNEvents) { if (eventTypes == null) throw new ArgumentNullException("eventTypes"); if (timeProvider == null) throw new ArgumentNullException("timeProvider"); if (eventTypes.Length == 0) throw new ArgumentException("empty", "eventTypes"); _timeProvider = timeProvider; _eventTypes = new HashSet<string>(eventTypes); _streamToEventType = eventTypes.ToDictionary(v => "$et-" + v, v => v); _lastEventPosition = fromTfPosition; _resolveLinkTos = resolveLinkTos; ValidateTag(fromPositions); _fromPositions = fromPositions; _state = new IndexBased(_eventTypes, this, readAs); } private void ValidateTag(Dictionary<string, int> fromPositions) { if (_eventTypes.Count != fromPositions.Count) throw new ArgumentException("Number of streams does not match", "fromPositions"); foreach (var stream in _streamToEventType.Keys.Where(stream => !fromPositions.ContainsKey(stream))) { throw new ArgumentException( String.Format("The '{0}' stream position has not been set", stream), "fromPositions"); } } public override void Dispose() { _state.Dispose(); base.Dispose(); } protected override void RequestEvents(bool delay) { if (_disposed || PauseRequested || Paused) return; _state.RequestEvents(delay); } protected override bool AreEventsRequested() { return _state.AreEventsRequested(); } private bool CheckEnough() { if (_stopAfterNEvents != null && _deliveredEvents >= _stopAfterNEvents) { _publisher.Publish( new ReaderSubscriptionMessage.EventReaderEof(EventReaderCorrelationId, maxEventsReached: true)); Dispose(); return true; } return false; } private void PublishIORequest(bool delay, Message readEventsForward) { if (delay) _publisher.Publish( TimerMessage.Schedule.Create( TimeSpan.FromMilliseconds(250), new PublishEnvelope(_publisher, crossThread: true), readEventsForward)); else _publisher.Publish(readEventsForward); } private void UpdateNextStreamPosition(string eventStreamId, int nextPosition) { int streamPosition; if (!_fromPositions.TryGetValue(eventStreamId, out streamPosition)) streamPosition = -1; if (nextPosition > streamPosition) _fromPositions[eventStreamId] = nextPosition; } private abstract class State : IDisposable { public abstract void RequestEvents(bool delay); public abstract bool AreEventsRequested(); public abstract void Dispose(); protected readonly EventByTypeIndexEventReader _reader; protected readonly IPrincipal _readAs; protected State(EventByTypeIndexEventReader reader, IPrincipal readAs) { _reader = reader; _readAs = readAs; } protected void DeliverEvent(float progress, ResolvedEvent resolvedEvent, TFPos position) { if (resolvedEvent.OriginalPosition <= _reader._lastEventPosition) return; _reader._lastEventPosition = resolvedEvent.OriginalPosition; _reader._deliveredEvents ++; _reader._publisher.Publish( //TODO: publish both link and event data new ReaderSubscriptionMessage.CommittedEventDistributed( _reader.EventReaderCorrelationId, resolvedEvent, _reader._stopOnEof ? (long?) null : position.PreparePosition, progress, source: this.GetType())); } protected void SendNotAuthorized() { _reader.SendNotAuthorized(); } } private class IndexBased : State, IHandle<ClientMessage.ReadStreamEventsForwardCompleted>, IHandle<ClientMessage.ReadStreamEventsBackwardCompleted> { private readonly Dictionary<string, string> _streamToEventType; private readonly HashSet<string> _eventsRequested = new HashSet<string>(); private bool _indexCheckpointStreamRequested; private int _lastKnownIndexCheckpointEventNumber = -1; private TFPos? _lastKnownIndexCheckpointPosition = null; private readonly Dictionary<string, Queue<PendingEvent>> _buffers = new Dictionary<string, Queue<PendingEvent>>(); private readonly Dictionary<string, bool> _eofs; private bool _disposed; private readonly IPublisher _publisher; public IndexBased(HashSet<string> eventTypes, EventByTypeIndexEventReader reader, IPrincipal readAs) : base(reader, readAs) { _streamToEventType = eventTypes.ToDictionary(v => "$et-" + v, v => v); _eofs = _streamToEventType.Keys.ToDictionary(v => v, v => false); // whatever the first event returned is (even if we start from the same position as the last processed event // let subscription handle this _publisher = _reader._publisher; } private TFPos GetTargetEventPosition(PendingEvent head) { return head.TfPosition; } public void Handle(ClientMessage.ReadStreamEventsForwardCompleted message) { if (_disposed) return; if (message.Result == ReadStreamResult.AccessDenied) { SendNotAuthorized(); return; } if (message.EventStreamId == "$et") { ReadIndexCheckpointStreamCompleted(message.Result, message.Events); return; } if (!_streamToEventType.ContainsKey(message.EventStreamId)) throw new InvalidOperationException( String.Format("Invalid stream name: {0}", message.EventStreamId)); if (!_eventsRequested.Contains(message.EventStreamId)) throw new InvalidOperationException("Read events has not been requested"); if (_reader.Paused) throw new InvalidOperationException("Paused"); switch (message.Result) { case ReadStreamResult.NoStream: _eofs[message.EventStreamId] = true; ProcessBuffersAndContinue(message, eof: true); break; case ReadStreamResult.Success: _reader.UpdateNextStreamPosition(message.EventStreamId, message.NextEventNumber); var isEof = message.Events.Length == 0; _eofs[message.EventStreamId] = isEof; EnqueueEvents(message); ProcessBuffersAndContinue(message, eof: isEof); break; default: throw new NotSupportedException( String.Format("ReadEvents result code was not recognized. Code: {0}", message.Result)); } } private void ProcessBuffersAndContinue(ClientMessage.ReadStreamEventsForwardCompleted message, bool eof) { ProcessBuffers(); _eventsRequested.Remove(message.EventStreamId); _reader.PauseOrContinueProcessing(delay: eof); CheckSwitch(); } private void CheckSwitch() { if (ShouldSwitch()) { Dispose(); _reader.DoSwitch(_lastKnownIndexCheckpointPosition.Value); } } public void Handle(ClientMessage.ReadStreamEventsBackwardCompleted message) { if (_disposed) return; if (message.Result == ReadStreamResult.AccessDenied) { SendNotAuthorized(); return; } ReadIndexCheckpointStreamCompleted(message.Result, message.Events); } private void EnqueueEvents(ClientMessage.ReadStreamEventsForwardCompleted message) { for (int index = 0; index < message.Events.Length; index++) { var @event = message.Events[index].Event; var @link = message.Events[index].Link; EventRecord positionEvent = (link ?? @event); var queue = GetStreamQueue(positionEvent); //TODO: progress calculation below is incorrect. sum(current)/sum(last_event) where sum by all streams var tfPosition = positionEvent.Metadata.ParseCheckpointTagJson().Position; var progress = 100.0f*(link ?? @event).EventNumber/message.LastEventNumber; var pendingEvent = new PendingEvent(@event, positionEvent, tfPosition, progress); queue.Enqueue(pendingEvent); } } private Queue<PendingEvent> GetStreamQueue(EventRecord positionEvent) { Queue<PendingEvent> queue; if (!_buffers.TryGetValue(positionEvent.EventStreamId, out queue)) { queue = new Queue<PendingEvent>(); _buffers.Add(positionEvent.EventStreamId, queue); } return queue; } private bool BeforeTheLastKnownIndexCheckpoint(TFPos tfPosition) { return _lastKnownIndexCheckpointPosition != null && tfPosition <= _lastKnownIndexCheckpointPosition; } private void ReadIndexCheckpointStreamCompleted( ReadStreamResult result, EventStore.Core.Data.ResolvedEvent[] events) { if (_disposed) return; if (!_indexCheckpointStreamRequested) throw new InvalidOperationException("Read index checkpoint has not been requested"); if (_reader.Paused) throw new InvalidOperationException("Paused"); _indexCheckpointStreamRequested = false; switch (result) { case ReadStreamResult.NoStream: _reader.PauseOrContinueProcessing(delay: true); _lastKnownIndexCheckpointPosition = default(TFPos); break; case ReadStreamResult.Success: if (events.Length == 0) { if (_lastKnownIndexCheckpointPosition == null) _lastKnownIndexCheckpointPosition = default(TFPos); } else { //NOTE: only one event if backward order was requested foreach (var @event in events) { var data = @event.Event.Data.ParseCheckpointTagJson(); _lastKnownIndexCheckpointEventNumber = @event.Event.EventNumber; _lastKnownIndexCheckpointPosition = data.Position; // reset eofs before this point - probably some where updated so we cannot go // forward with this position without making sure nothing appeared // NOTE: performance is not very good, but we should switch to TF mode shortly foreach (var key in _eofs.Keys.ToArray()) _eofs[key] = false; } } _reader.PauseOrContinueProcessing(delay: events.Length == 0); break; default: throw new NotSupportedException( String.Format("ReadEvents result code was not recognized. Code: {0}", result)); } } private void ProcessBuffers() { if (_disposed) // max N reached return; while (true) { var minStreamId = ""; var minPosition = new TFPos(Int64.MaxValue, Int64.MaxValue); var any = false; var anyEof = false; foreach (var streamId in _streamToEventType.Keys) { Queue<PendingEvent> buffer; _buffers.TryGetValue(streamId, out buffer); if ((buffer == null || buffer.Count == 0)) if (_eofs[streamId]) { anyEof = true; continue; // eof - will check if it was safe later } else return; // still reading var head = buffer.Peek(); var targetEventPosition = GetTargetEventPosition(head); if (targetEventPosition < minPosition) { minPosition = targetEventPosition; minStreamId = streamId; any = true; } } if (!any) break; if (!anyEof || BeforeTheLastKnownIndexCheckpoint(minPosition)) { var minHead = _buffers[minStreamId].Dequeue(); DeliverEventRetrievedByIndex( minHead.Event, minHead.PositionEvent, minHead.Progress, minPosition); } else return; // no safe events to deliver if (_reader.CheckEnough()) return; if (_buffers[minStreamId].Count == 0) _reader.PauseOrContinueProcessing(delay: false); } } private void RequestCheckpointStream(bool delay) { if (_disposed) throw new InvalidOperationException("Disposed"); if (_reader.PauseRequested || _reader.Paused) throw new InvalidOperationException("Paused or pause requested"); if (_indexCheckpointStreamRequested) return; _indexCheckpointStreamRequested = true; Message readRequest; if (_lastKnownIndexCheckpointEventNumber == -1) { readRequest = new ClientMessage.ReadStreamEventsBackward( Guid.NewGuid(), _reader.EventReaderCorrelationId, new SendToThisEnvelope(this), "$et", -1, 1, false, false, null, _readAs); } else { readRequest = new ClientMessage.ReadStreamEventsForward( Guid.NewGuid(), _reader.EventReaderCorrelationId, new SendToThisEnvelope(this), "$et", _lastKnownIndexCheckpointEventNumber + 1, 100, false, false, null, _readAs); } _reader.PublishIORequest(delay, readRequest); } private void RequestEvents(string stream, bool delay) { if (_disposed) throw new InvalidOperationException("Disposed"); if (_reader.PauseRequested || _reader.Paused) throw new InvalidOperationException("Paused or pause requested"); if (_eventsRequested.Contains(stream)) return; Queue<PendingEvent> queue; if (_buffers.TryGetValue(stream, out queue) && queue.Count > 0) return; _eventsRequested.Add(stream); var readEventsForward = new ClientMessage.ReadStreamEventsForward( Guid.NewGuid(), _reader.EventReaderCorrelationId, new SendToThisEnvelope(this), stream, _reader._fromPositions[stream], _maxReadCount, _reader._resolveLinkTos, false, null, _readAs); _reader.PublishIORequest(delay, readEventsForward); } private void DeliverEventRetrievedByIndex( EventRecord @event, EventRecord positionEvent, float progress, TFPos position) { //TODO: add event sequence validation for inside the index stream var resolvedEvent = new ResolvedEvent( positionEvent.EventStreamId, positionEvent.EventNumber, @event.EventStreamId, @event.EventNumber, true, new TFPos(-1, positionEvent.LogPosition), position, @event.EventId, @event.EventType, (@event.Flags & PrepareFlags.IsJson) != 0, @event.Data, @event.Metadata, positionEvent.Metadata, null, positionEvent.TimeStamp); DeliverEvent(progress, resolvedEvent, position); } public override bool AreEventsRequested() { return _eventsRequested.Count != 0 || _indexCheckpointStreamRequested; } public override void Dispose() { _disposed = true; } public override void RequestEvents(bool delay) { foreach (var stream in _streamToEventType.Keys) RequestEvents(stream, delay: delay); RequestCheckpointStream(delay: delay); } private bool ShouldSwitch() { if (_disposed) return false; if (_reader.Paused || _reader.PauseRequested) return false; Queue<PendingEvent> q; var shouldSwitch = _lastKnownIndexCheckpointPosition != null && _streamToEventType.Keys.All( v => _eofs[v] || _buffers.TryGetValue(v, out q) && q.Count > 0 && !BeforeTheLastKnownIndexCheckpoint(q.Peek().TfPosition)); return shouldSwitch; } } private class TfBased : State, IHandle<ClientMessage.ReadAllEventsForwardCompleted> { private readonly HashSet<string> _eventTypes; private readonly ITimeProvider _timeProvider; private bool _tfEventsRequested; private bool _disposed; private readonly Dictionary<string, string> _streamToEventType; private readonly IPublisher _publisher; private TFPos _fromTfPosition; public TfBased( ITimeProvider timeProvider, EventByTypeIndexEventReader reader, TFPos fromTfPosition, IPublisher publisher, IPrincipal readAs) : base(reader, readAs) { _timeProvider = timeProvider; _eventTypes = reader._eventTypes; _streamToEventType = _eventTypes.ToDictionary(v => "$et-" + v, v => v); _publisher = publisher; _fromTfPosition = fromTfPosition; } public void Handle(ClientMessage.ReadAllEventsForwardCompleted message) { if (_disposed) return; if (message.Result == ReadAllResult.AccessDenied) { SendNotAuthorized(); return; } if (!_tfEventsRequested) throw new InvalidOperationException("TF events has not been requested"); if (_reader.Paused) throw new InvalidOperationException("Paused"); _tfEventsRequested = false; switch (message.Result) { case ReadAllResult.Success: var eof = message.Events.Length == 0; var willDispose = _reader._stopOnEof && eof; _fromTfPosition = message.NextPos; if (!willDispose) { _reader.PauseOrContinueProcessing(delay: eof); } if (eof) { // the end //TODO: is it safe to pass NEXT as last commit position here DeliverLastCommitPosition(message.NextPos); // allow joining heading distribution SendIdle(); _reader.SendEof(); } else { foreach (var @event in message.Events) { var byStream = @event.Link != null && _streamToEventType.ContainsKey(@event.Link.EventStreamId); var byEvent = @event.Link == null && _eventTypes.Contains(@event.Event.EventType); if (byStream) { // ignore data just update positions _reader.UpdateNextStreamPosition( @event.Link.EventStreamId, @event.Link.EventNumber + 1); DeliverEventRetrievedFromTf( @event.Link, 100.0f*@event.Link.LogPosition/message.TfLastCommitPosition, @event.OriginalPosition.Value); } else if (byEvent) { DeliverEventRetrievedFromTf( @event.Event, 100.0f*@event.Event.LogPosition/message.TfLastCommitPosition, @event.OriginalPosition.Value); } if (_reader.CheckEnough()) return; } } if (_disposed) return; break; default: throw new NotSupportedException( String.Format("ReadEvents result code was not recognized. Code: {0}", message.Result)); } } private void RequestTfEvents(bool delay) { if (_disposed) throw new InvalidOperationException("Disposed"); if (_reader.PauseRequested || _reader.Paused) throw new InvalidOperationException("Paused or pause requested"); if (_tfEventsRequested) return; _tfEventsRequested = true; //TODO: we do not need resolve links, but lets check first with var readRequest = new ClientMessage.ReadAllEventsForward( Guid.NewGuid(), _reader.EventReaderCorrelationId, new SendToThisEnvelope(this), _fromTfPosition.CommitPosition, _fromTfPosition.PreparePosition == -1 ? 0 : _fromTfPosition.PreparePosition, 111, true, false, null, _readAs); _reader.PublishIORequest(delay, readRequest); } private void DeliverLastCommitPosition(TFPos lastPosition) { if (_reader._stopOnEof || _reader._stopAfterNEvents != null) return; _publisher.Publish( new ReaderSubscriptionMessage.CommittedEventDistributed( _reader.EventReaderCorrelationId, null, lastPosition.PreparePosition, 100.0f, source: this.GetType())); //TODO: check was is passed here } private void DeliverEventRetrievedFromTf(EventRecord @event, float progress, TFPos position) { var resolvedEvent = new ResolvedEvent( @event.EventStreamId, @event.EventNumber, @event.EventStreamId, @event.EventNumber, false, position, position, @event.EventId, @event.EventType, (@event.Flags & PrepareFlags.IsJson) != 0, @event.Data, @event.Metadata, null, null, @event.TimeStamp); DeliverEvent(progress, resolvedEvent, position); } private void SendIdle() { _publisher.Publish( new ReaderSubscriptionMessage.EventReaderIdle(_reader.EventReaderCorrelationId, _timeProvider.Now)); } public override void Dispose() { _disposed = true; } public override void RequestEvents(bool delay) { RequestTfEvents(delay: delay); } public override bool AreEventsRequested() { return _tfEventsRequested; } } private void DoSwitch(TFPos lastKnownIndexCheckpointPosition) { if (Paused || PauseRequested || _disposed) throw new InvalidOperationException("_paused || _pauseRequested || _disposed"); // skip reading TF up to last know index checkpoint position // as we could only gethere if there is no more indexed events before this point if (lastKnownIndexCheckpointPosition > _lastEventPosition) _lastEventPosition = lastKnownIndexCheckpointPosition; _state = new TfBased(_timeProvider, this, _lastEventPosition, this._publisher, ReadAs); _state.RequestEvents(delay: false); } } }
/* * 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 OpenMetaverse; using System; using System.Collections.Generic; namespace OpenSim.Framework { public class EstateSettings { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public delegate void SaveDelegate(EstateSettings rs); public event SaveDelegate OnSave; // Only the client uses these // private uint m_EstateID = 0; public uint EstateID { get { return m_EstateID; } set { m_EstateID = value; } } private string m_EstateName = "My Estate"; public string EstateName { get { return m_EstateName; } set { m_EstateName = value; } } private bool m_AllowLandmark = true; public bool AllowLandmark { get { return m_AllowLandmark; } set { m_AllowLandmark = value; } } private bool m_AllowParcelChanges = true; public bool AllowParcelChanges { get { return m_AllowParcelChanges; } set { m_AllowParcelChanges = value; } } private bool m_AllowSetHome = true; public bool AllowSetHome { get { return m_AllowSetHome; } set { m_AllowSetHome = value; } } private uint m_ParentEstateID = 1; public uint ParentEstateID { get { return m_ParentEstateID; } set { m_ParentEstateID = value; } } private float m_BillableFactor = 0.0f; public float BillableFactor { get { return m_BillableFactor; } set { m_BillableFactor = value; } } private int m_PricePerMeter = 1; public int PricePerMeter { get { return m_PricePerMeter; } set { m_PricePerMeter = value; } } private int m_RedirectGridX = 0; public int RedirectGridX { get { return m_RedirectGridX; } set { m_RedirectGridX = value; } } private int m_RedirectGridY = 0; public int RedirectGridY { get { return m_RedirectGridY; } set { m_RedirectGridY = value; } } // Used by the sim // private bool m_UseGlobalTime = true; public bool UseGlobalTime { get { return m_UseGlobalTime; } set { m_UseGlobalTime = value; } } private bool m_FixedSun = false; public bool FixedSun { get { return m_FixedSun; } set { m_FixedSun = value; } } private double m_SunPosition = 0.0; public double SunPosition { get { return m_SunPosition; } set { m_SunPosition = value; } } private bool m_AllowVoice = true; public bool AllowVoice { get { return m_AllowVoice; } set { m_AllowVoice = value; } } private bool m_AllowDirectTeleport = true; public bool AllowDirectTeleport { get { return m_AllowDirectTeleport; } set { m_AllowDirectTeleport = value; } } private bool m_DenyAnonymous = false; public bool DenyAnonymous { get { return m_DenyAnonymous; } set { m_DenyAnonymous = value; } } private bool m_DenyIdentified = false; public bool DenyIdentified { get { return m_DenyIdentified; } set { m_DenyIdentified = value; } } private bool m_DenyTransacted = false; public bool DenyTransacted { get { return m_DenyTransacted; } set { m_DenyTransacted = value; } } private bool m_AbuseEmailToEstateOwner = false; public bool AbuseEmailToEstateOwner { get { return m_AbuseEmailToEstateOwner; } set { m_AbuseEmailToEstateOwner = value; } } private bool m_BlockDwell = false; public bool BlockDwell { get { return m_BlockDwell; } set { m_BlockDwell = value; } } private bool m_EstateSkipScripts = false; public bool EstateSkipScripts { get { return m_EstateSkipScripts; } set { m_EstateSkipScripts = value; } } private bool m_ResetHomeOnTeleport = false; public bool ResetHomeOnTeleport { get { return m_ResetHomeOnTeleport; } set { m_ResetHomeOnTeleport = value; } } private bool m_TaxFree = false; public bool TaxFree { get { return m_TaxFree; } set { m_TaxFree = value; } } private bool m_PublicAccess = true; public bool PublicAccess { get { return m_PublicAccess; } set { m_PublicAccess = value; } } private string m_AbuseEmail = String.Empty; public string AbuseEmail { get { return m_AbuseEmail; } set { m_AbuseEmail= value; } } private UUID m_EstateOwner = UUID.Zero; public UUID EstateOwner { get { return m_EstateOwner; } set { m_EstateOwner = value; } } private bool m_DenyMinors = false; public bool DenyMinors { get { return m_DenyMinors; } set { m_DenyMinors = value; } } // All those lists... // private List<UUID> l_EstateManagers = new List<UUID>(); public UUID[] EstateManagers { get { return l_EstateManagers.ToArray(); } set { l_EstateManagers = new List<UUID>(value); } } private List<EstateBan> l_EstateBans = new List<EstateBan>(); public EstateBan[] EstateBans { get { return l_EstateBans.ToArray(); } set { l_EstateBans = new List<EstateBan>(value); } } private List<UUID> l_EstateAccess = new List<UUID>(); public UUID[] EstateAccess { get { return l_EstateAccess.ToArray(); } set { l_EstateAccess = new List<UUID>(value); } } private List<UUID> l_EstateGroups = new List<UUID>(); public UUID[] EstateGroups { get { return l_EstateGroups.ToArray(); } set { l_EstateGroups = new List<UUID>(value); } } public EstateSettings() { } public void Save() { if (OnSave != null) OnSave(this); } public void AddEstateUser(UUID avatarID) { if (avatarID == UUID.Zero) return; if (!l_EstateAccess.Contains(avatarID)) l_EstateAccess.Add(avatarID); } public void RemoveEstateUser(UUID avatarID) { if (l_EstateAccess.Contains(avatarID)) l_EstateAccess.Remove(avatarID); } public void AddEstateGroup(UUID avatarID) { if (avatarID == UUID.Zero) return; if (!l_EstateGroups.Contains(avatarID)) l_EstateGroups.Add(avatarID); } public void RemoveEstateGroup(UUID avatarID) { if (l_EstateGroups.Contains(avatarID)) l_EstateGroups.Remove(avatarID); } public void AddEstateManager(UUID avatarID) { if (avatarID == UUID.Zero) return; if (!l_EstateManagers.Contains(avatarID)) l_EstateManagers.Add(avatarID); } public void RemoveEstateManager(UUID avatarID) { if (l_EstateManagers.Contains(avatarID)) l_EstateManagers.Remove(avatarID); } public bool IsEstateManagerOrOwner(UUID avatarID) { if (IsEstateOwner(avatarID)) return true; return l_EstateManagers.Contains(avatarID); } public bool IsEstateOwner(UUID avatarID) { if (avatarID == m_EstateOwner) return true; return false; } public bool IsBanned(UUID avatarID) { foreach (EstateBan ban in l_EstateBans) if (ban.BannedUserID == avatarID) return true; return false; } public void AddBan(EstateBan ban) { if (ban == null) return; if (!IsBanned(ban.BannedUserID)) l_EstateBans.Add(ban); } public void ClearBans() { l_EstateBans.Clear(); } public void RemoveBan(UUID avatarID) { foreach (EstateBan ban in new List<EstateBan>(l_EstateBans)) if (ban.BannedUserID == avatarID) l_EstateBans.Remove(ban); } public bool HasAccess(UUID user) { if (IsEstateManagerOrOwner(user)) return true; return l_EstateAccess.Contains(user); } public void SetFromFlags(ulong regionFlags) { ResetHomeOnTeleport = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.ResetHomeOnTeleport) == (ulong)OpenMetaverse.RegionFlags.ResetHomeOnTeleport); BlockDwell = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.BlockDwell) == (ulong)OpenMetaverse.RegionFlags.BlockDwell); AllowLandmark = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowLandmark) == (ulong)OpenMetaverse.RegionFlags.AllowLandmark); AllowParcelChanges = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowParcelChanges) == (ulong)OpenMetaverse.RegionFlags.AllowParcelChanges); AllowSetHome = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowSetHome) == (ulong)OpenMetaverse.RegionFlags.AllowSetHome); } public bool GroupAccess(UUID groupID) { return l_EstateGroups.Contains(groupID); } } }
using System; using System.Collections; using NBitcoin.BouncyCastle.Crypto.Digests; using NBitcoin.BouncyCastle.Crypto.Parameters; using NBitcoin.BouncyCastle.Security; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Signers { /// <summary> ISO9796-2 - mechanism using a hash function with recovery (scheme 2 and 3). /// <p> /// Note: the usual length for the salt is the length of the hash /// function used in bytes.</p> /// </summary> public class Iso9796d2PssSigner : 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 readonly IDictionary trailerMap = Platform.CreateHashtable(); static Iso9796d2PssSigner() { 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 SecureRandom random; private byte[] standardSalt; private int hLen; private int trailer; private int keyBits; private byte[] block; private byte[] mBuf; private int messageLength; private readonly int saltLength; private bool fullMessage; private byte[] recoveredMessage; private byte[] preSig; private byte[] preBlock; private int preMStart; private int preTLength; /// <summary> /// Generate a signer for the with either implicit or explicit trailers /// for ISO9796-2, scheme 2 or 3. /// </summary> /// <param name="cipher">base cipher to use for signature creation/verification</param> /// <param name="digest">digest to use.</param> /// <param name="saltLength">length of salt in bytes.</param> /// <param name="isImplicit">whether or not the trailer is implicit or gives the hash.</param> public Iso9796d2PssSigner( IAsymmetricBlockCipher cipher, IDigest digest, int saltLength, bool isImplicit) { this.cipher = cipher; this.digest = digest; this.hLen = digest.GetDigestSize(); this.saltLength = saltLength; if (isImplicit) { trailer = TrailerImplicit; } else { string digestAlg = digest.AlgorithmName; if (!trailerMap.Contains(digestAlg)) throw new ArgumentException("no valid trailer for digest"); trailer = (int)trailerMap[digestAlg]; } } /// <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> /// <param name="saltLength">length of salt in bytes. /// </param> public Iso9796d2PssSigner( IAsymmetricBlockCipher cipher, IDigest digest, int saltLength) : this(cipher, digest, saltLength, false) { } public string AlgorithmName { get { return digest.AlgorithmName + "with" + "ISO9796-2S2"; } } /// <summary>Initialise the signer.</summary> /// <param name="forSigning">true if for signing, false if for verification.</param> /// <param name="parameters">parameters for signature generation/verification. If the /// parameters are for generation they should be a ParametersWithRandom, /// a ParametersWithSalt, or just an RsaKeyParameters object. If RsaKeyParameters /// are passed in a SecureRandom will be created. /// </param> /// <exception cref="ArgumentException">if wrong parameter type or a fixed /// salt is passed in which is the wrong length. /// </exception> public virtual void Init( bool forSigning, ICipherParameters parameters) { RsaKeyParameters kParam; if (parameters is ParametersWithRandom) { ParametersWithRandom p = (ParametersWithRandom) parameters; kParam = (RsaKeyParameters) p.Parameters; if (forSigning) { random = p.Random; } } else if (parameters is ParametersWithSalt) { if (!forSigning) throw new ArgumentException("ParametersWithSalt only valid for signing", "parameters"); ParametersWithSalt p = (ParametersWithSalt) parameters; kParam = (RsaKeyParameters) p.Parameters; standardSalt = p.GetSalt(); if (standardSalt.Length != saltLength) throw new ArgumentException("Fixed salt is of wrong length"); } else { kParam = (RsaKeyParameters) parameters; if (forSigning) { random = new SecureRandom(); } } cipher.Init(forSigning, kParam); keyBits = kParam.Modulus.BitLength; block = new byte[(keyBits + 7) / 8]; if (trailer == TrailerImplicit) { mBuf = new byte[block.Length - digest.GetDigestSize() - saltLength - 1 - 1]; } else { mBuf = new byte[block.Length - digest.GetDigestSize() - saltLength - 1 - 2]; } Reset(); } /// <summary> compare two byte arrays - constant time.</summary> private bool IsSameAs(byte[] a, byte[] b) { if (messageLength != b.Length) { return false; } bool isOkay = true; for (int i = 0; i != b.Length; 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); // // adjust block size for leading zeroes if necessary // if (block.Length < (keyBits + 7) / 8) { byte[] tmp = new byte[(keyBits + 7) / 8]; Array.Copy(block, 0, tmp, tmp.Length - block.Length, block.Length); ClearBlock(block); block = tmp; } int tLength; if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0) { tLength = 1; } else { int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF); string digestAlg = digest.AlgorithmName; if (!trailerMap.Contains(digestAlg)) throw new ArgumentException("unrecognised hash in signature"); if (sigTrail != (int)trailerMap[digestAlg]) throw new InvalidOperationException("signer initialised with wrong digest for trailer " + sigTrail); tLength = 2; } // // calculate H(m2) // byte[] m2Hash = new byte[hLen]; digest.DoFinal(m2Hash, 0); // // remove the mask // byte[] dbMask = MaskGeneratorFunction1(block, block.Length - hLen - tLength, hLen, block.Length - hLen - tLength); for (int i = 0; i != dbMask.Length; i++) { block[i] ^= dbMask[i]; } block[0] &= 0x7f; // // find out how much padding we've got // int mStart = 0; while (mStart < block.Length) { if (block[mStart++] == 0x01) break; } if (mStart >= block.Length) { ClearBlock(block); } fullMessage = (mStart > 1); recoveredMessage = new byte[dbMask.Length - mStart - saltLength]; Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length); recoveredMessage.CopyTo(mBuf, 0); preSig = signature; preBlock = block; preMStart = mStart; preTLength = tLength; } /// <summary> update the internal digest with the byte b</summary> public virtual void Update( byte input) { if (preSig == null && messageLength < mBuf.Length) { mBuf[messageLength++] = input; } else { digest.Update(input); } } /// <summary> update the internal digest with the byte array in</summary> public virtual void BlockUpdate( byte[] input, int inOff, int length) { if (preSig == null) { while (length > 0 && messageLength < mBuf.Length) { this.Update(input[inOff]); inOff++; length--; } } if (length > 0) { digest.BlockUpdate(input, inOff, length); } } /// <summary> reset the internal state</summary> public virtual void Reset() { digest.Reset(); messageLength = 0; if (mBuf != null) { ClearBlock(mBuf); } if (recoveredMessage != null) { ClearBlock(recoveredMessage); recoveredMessage = null; } fullMessage = false; if (preSig != null) { preSig = null; ClearBlock(preBlock); preBlock = null; } } /// <summary> Generate a signature for the loaded message using the key we were /// initialised with. /// </summary> public byte[] GenerateSignature() { int digSize = digest.GetDigestSize(); byte[] m2Hash = new byte[digSize]; digest.DoFinal(m2Hash, 0); byte[] C = new byte[8]; LtoOSP(messageLength * 8, C); digest.BlockUpdate(C, 0, C.Length); digest.BlockUpdate(mBuf, 0, messageLength); digest.BlockUpdate(m2Hash, 0, m2Hash.Length); byte[] salt; if (standardSalt != null) { salt = standardSalt; } else { salt = new byte[saltLength]; random.NextBytes(salt); } digest.BlockUpdate(salt, 0, salt.Length); byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); int tLength = 2; if (trailer == TrailerImplicit) { tLength = 1; } int off = block.Length - messageLength - salt.Length - hLen - tLength - 1; block[off] = (byte) (0x01); Array.Copy(mBuf, 0, block, off + 1, messageLength); Array.Copy(salt, 0, block, off + 1 + messageLength, salt.Length); byte[] dbMask = MaskGeneratorFunction1(hash, 0, hash.Length, block.Length - hLen - tLength); for (int i = 0; i != dbMask.Length; i++) { block[i] ^= dbMask[i]; } Array.Copy(hash, 0, block, block.Length - hLen - tLength, hLen); if (trailer == TrailerImplicit) { block[block.Length - 1] = (byte)TrailerImplicit; } else { block[block.Length - 2] = (byte) ((uint)trailer >> 8); block[block.Length - 1] = (byte) trailer; } block[0] &= (byte) (0x7f); byte[] b = cipher.ProcessBlock(block, 0, block.Length); ClearBlock(mBuf); ClearBlock(block); messageLength = 0; 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) { // // calculate H(m2) // byte[] m2Hash = new byte[hLen]; digest.DoFinal(m2Hash, 0); byte[] block; int tLength; int mStart = 0; if (preSig == null) { try { UpdateWithRecoveredMessage(signature); } catch (Exception) { return false; } } else { if (!Arrays.AreEqual(preSig, signature)) { throw new InvalidOperationException("UpdateWithRecoveredMessage called on different signature"); } } block = preBlock; mStart = preMStart; tLength = preTLength; preSig = null; preBlock = null; // // check the hashes // byte[] C = new byte[8]; LtoOSP(recoveredMessage.Length * 8, C); digest.BlockUpdate(C, 0, C.Length); if (recoveredMessage.Length != 0) { digest.BlockUpdate(recoveredMessage, 0, recoveredMessage.Length); } digest.BlockUpdate(m2Hash, 0, m2Hash.Length); // Update for the salt digest.BlockUpdate(block, mStart + recoveredMessage.Length, saltLength); byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); int off = block.Length - tLength - hash.Length; bool isOkay = true; for (int i = 0; i != hash.Length; i++) { if (hash[i] != block[off + i]) { isOkay = false; } } ClearBlock(block); ClearBlock(hash); if (!isOkay) { fullMessage = false; ClearBlock(recoveredMessage); return false; } // // if they've input a message check what we've recovered against // what was input. // if (messageLength != 0) { if (!IsSameAs(mBuf, recoveredMessage)) { ClearBlock(mBuf); return false; } messageLength = 0; } ClearBlock(mBuf); return true; } /// <summary> /// Return true if the full message was recoveredMessage. /// </summary> /// <returns>true on full message recovery, false otherwise, or if not sure.</returns> /// <seealso cref="ISignerWithRecovery.HasFullMessage"/> public virtual bool HasFullMessage() { return fullMessage; } /// <summary> int to octet string.</summary> /// <summary> int to octet string.</summary> private void ItoOSP( int i, byte[] sp) { sp[0] = (byte)((uint)i >> 24); sp[1] = (byte)((uint)i >> 16); sp[2] = (byte)((uint)i >> 8); sp[3] = (byte)((uint)i >> 0); } /// <summary> long to octet string.</summary> private void LtoOSP(long l, byte[] sp) { sp[0] = (byte)((ulong)l >> 56); sp[1] = (byte)((ulong)l >> 48); sp[2] = (byte)((ulong)l >> 40); sp[3] = (byte)((ulong)l >> 32); sp[4] = (byte)((ulong)l >> 24); sp[5] = (byte)((ulong)l >> 16); sp[6] = (byte)((ulong)l >> 8); sp[7] = (byte)((ulong)l >> 0); } /// <summary> mask generator function, as described in Pkcs1v2.</summary> private byte[] MaskGeneratorFunction1( byte[] Z, int zOff, int zLen, int length) { byte[] mask = new byte[length]; byte[] hashBuf = new byte[hLen]; byte[] C = new byte[4]; int counter = 0; digest.Reset(); do { ItoOSP(counter, C); digest.BlockUpdate(Z, zOff, zLen); digest.BlockUpdate(C, 0, C.Length); digest.DoFinal(hashBuf, 0); Array.Copy(hashBuf, 0, mask, counter * hLen, hLen); } while (++counter < (length / hLen)); if ((counter * hLen) < length) { ItoOSP(counter, C); digest.BlockUpdate(Z, zOff, zLen); digest.BlockUpdate(C, 0, C.Length); digest.DoFinal(hashBuf, 0); Array.Copy(hashBuf, 0, mask, counter * hLen, mask.Length - (counter * hLen)); } return mask; } } }
// // ArtworkManager.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 Novell, 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 System.Collections.Generic; using System.Text.RegularExpressions; using Mono.Unix; using Gdk; using Hyena; using Hyena.Gui; using Hyena.Collections; using Hyena.Data.Sqlite; using Banshee.Base; using Banshee.IO; using Banshee.Configuration; using Banshee.ServiceStack; namespace Banshee.Collection.Gui { public class ArtworkManager : IService { private Dictionary<int, SurfaceCache> scale_caches = new Dictionary<int, SurfaceCache> (); private HashSet<int> cacheable_cover_sizes = new HashSet<int> (); private HashSet<string> null_artwork_ids = new HashSet<string> (); private class SurfaceCache : LruCache<string, Cairo.ImageSurface> { public SurfaceCache (int max_items) : base (max_items) { } protected override void ExpireItem (Cairo.ImageSurface item) { if (item != null) { ((IDisposable)item).Dispose (); } } } public ArtworkManager () { AddCachedSize (36); AddCachedSize (40); AddCachedSize (42); AddCachedSize (48); AddCachedSize (64); AddCachedSize (90); AddCachedSize (300); try { MigrateCacheDir (); } catch (Exception e) { Log.Exception ("Could not migrate album artwork cache directory", e); } if (ApplicationContext.CommandLine.Contains ("fetch-artwork")) { ResetScanResultCache (); } Banshee.Metadata.MetadataService.Instance.ArtworkUpdated += OnArtworkUpdated; } public void Dispose () { Banshee.Metadata.MetadataService.Instance.ArtworkUpdated -= OnArtworkUpdated; } private void OnArtworkUpdated (IBasicTrackInfo track) { ClearCacheFor (track.ArtworkId, true); } public Cairo.ImageSurface LookupSurface (string id) { return LookupScaleSurface (id, 0); } public Cairo.ImageSurface LookupScaleSurface (string id, int size) { return LookupScaleSurface (id, size, false); } public Cairo.ImageSurface LookupScaleSurface (string id, int size, bool useCache) { SurfaceCache cache = null; Cairo.ImageSurface surface = null; if (id == null) { return null; } if (useCache && scale_caches.TryGetValue (size, out cache) && cache.TryGetValue (id, out surface)) { return surface; } if (null_artwork_ids.Contains (id)) { return null; } Pixbuf pixbuf = LookupScalePixbuf (id, size); if (pixbuf == null || pixbuf.Handle == IntPtr.Zero) { null_artwork_ids.Add (id); return null; } try { surface = PixbufImageSurface.Create (pixbuf); if (surface == null) { return null; } if (!useCache) { return surface; } if (cache == null) { int bytes = 4 * size * size; int max = (1 << 20) / bytes; ChangeCacheSize (size, max); cache = scale_caches[size]; } cache.Add (id, surface); return surface; } finally { DisposePixbuf (pixbuf); } } public Pixbuf LookupPixbuf (string id) { return LookupScalePixbuf (id, 0); } public Pixbuf LookupScalePixbuf (string id, int size) { if (id == null || (size != 0 && size < 10)) { return null; } if (null_artwork_ids.Contains (id)) { return null; } // Find the scaled, cached file string path = CoverArtSpec.GetPathForSize (id, size); if (File.Exists (new SafeUri (path))) { try { return new Pixbuf (path); } catch { null_artwork_ids.Add (id); return null; } } string orig_path = CoverArtSpec.GetPathForSize (id, 0); bool orig_exists = File.Exists (new SafeUri (orig_path)); if (!orig_exists) { // It's possible there is an image with extension .cover that's waiting // to be converted into a jpeg string unconverted_path = System.IO.Path.ChangeExtension (orig_path, "cover"); if (File.Exists (new SafeUri (unconverted_path))) { try { Pixbuf pixbuf = new Pixbuf (unconverted_path); if (pixbuf.Width < 50 || pixbuf.Height < 50) { Hyena.Log.DebugFormat ("Ignoring cover art {0} because less than 50x50", unconverted_path); null_artwork_ids.Add (id); return null; } pixbuf.Save (orig_path, "jpeg"); orig_exists = true; } catch { } finally { File.Delete (new SafeUri (unconverted_path)); } } } if (orig_exists && size >= 10) { try { Pixbuf pixbuf = new Pixbuf (orig_path); // Make it square if width and height difference is within 20% const double max_ratio = 1.2; double ratio = (double)pixbuf.Height / pixbuf.Width; int width = size, height = size; if (ratio > max_ratio) { width = (int)Math.Round (size / ratio); }else if (ratio < 1d / max_ratio) { height = (int)Math.Round (size * ratio); } Pixbuf scaled_pixbuf = pixbuf.ScaleSimple (width, height, Gdk.InterpType.Bilinear); if (IsCachedSize (size)) { Directory.Create (System.IO.Path.GetDirectoryName (path)); scaled_pixbuf.Save (path, "jpeg"); } else { Log.InformationFormat ("Uncached artwork size {0} requested", size); } DisposePixbuf (pixbuf); return scaled_pixbuf; } catch {} } null_artwork_ids.Add (id); return null; } public void ClearCacheFor (string id) { ClearCacheFor (id, false); } public void ClearCacheFor (string id, bool inMemoryCacheOnly) { if (String.IsNullOrEmpty (id)) { return; } // Clear from the in-memory cache foreach (int size in scale_caches.Keys) { scale_caches[size].Remove (id); } null_artwork_ids.Remove (id); if (inMemoryCacheOnly) { return; } // And delete from disk foreach (int size in CachedSizes ()) { var uri = new SafeUri (CoverArtSpec.GetPathForSize (id, size)); if (File.Exists (uri)) { File.Delete (uri); } } } public void AddCachedSize (int size) { cacheable_cover_sizes.Add (size); } public bool IsCachedSize (int size) { return cacheable_cover_sizes.Contains (size); } public IEnumerable<int> CachedSizes () { return cacheable_cover_sizes; } public void ChangeCacheSize (int size, int max_count) { SurfaceCache cache; if (scale_caches.TryGetValue (size, out cache)) { if (max_count > cache.MaxCount) { Log.DebugFormat ( "Growing surface cache for {0}px images to {1:0.00} MiB ({2} items)", size, 4 * size * size * max_count / 1048576d, max_count); cache.MaxCount = max_count; } } else { Log.DebugFormat ( "Creating new surface cache for {0}px images, capped at {1:0.00} MiB ({2} items)", size, 4 * size * size * max_count / 1048576d, max_count); scale_caches.Add (size, new SurfaceCache (max_count)); } } private static int dispose_count = 0; public static void DisposePixbuf (Pixbuf pixbuf) { if (pixbuf != null && pixbuf.Handle != IntPtr.Zero) { pixbuf.Dispose (); pixbuf = null; // There is an issue with disposing Pixbufs where we need to explicitly // call the GC otherwise it doesn't get done in a timely way. But if we // do it every time, it slows things down a lot; so only do it every 100th. if (++dispose_count % 100 == 0) { System.GC.Collect (); dispose_count = 0; } } } string IService.ServiceName { get { return "ArtworkManager"; } } #region Cache Directory Versioning/Migration private const int CUR_VERSION = 3; private void MigrateCacheDir () { int version = CacheVersion; if (version == CUR_VERSION) { return; } var legacy_root_path = CoverArtSpec.LegacyRootPath; if (version < 1) { string legacy_artwork_path = Paths.Combine (LegacyPaths.ApplicationData, "covers"); if (!Directory.Exists (legacy_root_path)) { Directory.Create (legacy_root_path); if (Directory.Exists (legacy_artwork_path)) { Directory.Move (new SafeUri (legacy_artwork_path), new SafeUri (legacy_root_path)); } } if (Directory.Exists (legacy_artwork_path)) { Log.InformationFormat ("Deleting old (Banshee < 1.0) artwork cache directory {0}", legacy_artwork_path); Directory.Delete (legacy_artwork_path, true); } } if (version < 2) { int deleted = 0; foreach (string dir in Directory.GetDirectories (legacy_root_path)) { int size; string dirname = System.IO.Path.GetFileName (dir); if (Int32.TryParse (dirname, out size) && !IsCachedSize (size)) { Directory.Delete (dir, true); deleted++; } } if (deleted > 0) { Log.InformationFormat ("Deleted {0} extraneous album-art cache directories", deleted); } } if (version < 3) { Log.Information ("Migrating album-art cache directory"); var started = DateTime.Now; int count = 0; var root_path = CoverArtSpec.RootPath; if (!Directory.Exists (root_path)) { Directory.Create (root_path); } string sql = "SELECT Title, ArtistName FROM CoreAlbums"; using (var reader = new HyenaDataReader (ServiceManager.DbConnection.Query (sql))) { while (reader.Read ()) { var album = reader.Get<string>(0); var artist = reader.Get<string>(1); var old_file = CoverArtSpec.CreateLegacyArtistAlbumId (artist, album); var new_file = CoverArtSpec.CreateArtistAlbumId (artist, album); if (String.IsNullOrEmpty (old_file) || String.IsNullOrEmpty (new_file)) { continue; } old_file = String.Format ("{0}.jpg", old_file); new_file = String.Format ("{0}.jpg", new_file); var old_path = new SafeUri (Paths.Combine (legacy_root_path, old_file)); var new_path = new SafeUri (Paths.Combine (root_path, new_file)); if (Banshee.IO.File.Exists (old_path) && !Banshee.IO.File.Exists (new_path)) { Banshee.IO.File.Move (old_path, new_path); count++; } } } if (ServiceManager.DbConnection.TableExists ("PodcastSyndications")) { sql = "SELECT Title FROM PodcastSyndications"; foreach (var title in ServiceManager.DbConnection.QueryEnumerable<string> (sql)) { var old_digest = CoverArtSpec.LegacyEscapePart (title); var new_digest = CoverArtSpec.Digest (title); if (String.IsNullOrEmpty (old_digest) || String.IsNullOrEmpty (new_digest)) { continue; } var old_file = String.Format ("podcast-{0}.jpg", old_digest); var new_file = String.Format ("podcast-{0}.jpg", new_digest); var old_path = new SafeUri (Paths.Combine (legacy_root_path, old_file)); var new_path = new SafeUri (Paths.Combine (root_path, new_file)); if (Banshee.IO.File.Exists (old_path) && !Banshee.IO.File.Exists (new_path)) { Banshee.IO.File.Move (old_path, new_path); count++; } } } if (count == 0) { ResetScanResultCache (); } Directory.Delete (legacy_root_path, true); Log.InformationFormat ("Migrated {0} files in {1}s", count, DateTime.Now.Subtract(started).TotalSeconds); } CacheVersion = CUR_VERSION; } private void ResetScanResultCache () { try { ServiceManager.DbConnection.Execute ("DELETE FROM CoverArtDownloads"); DatabaseConfigurationClient.Client.Set<DateTime> ("last_cover_art_scan", DateTime.MinValue); Log.InformationFormat ("Reset CoverArtDownloads table so missing artwork will get fetched"); } catch {} } private static SafeUri cache_version_file = new SafeUri (Paths.Combine (CoverArtSpec.RootPath, ".cache_version")); private static int CacheVersion { get { var file = cache_version_file; if (!Banshee.IO.File.Exists (file)) { file = new SafeUri (Paths.Combine (CoverArtSpec.LegacyRootPath, ".cache_version")); if (!Banshee.IO.File.Exists (file)) { file = null; } } if (file != null) { using (var reader = new System.IO.StreamReader (Banshee.IO.File.OpenRead (file))) { int version; if (Int32.TryParse (reader.ReadLine (), out version)) { return version; } } } return 0; } set { using (var writer = new System.IO.StreamWriter (Banshee.IO.File.OpenWrite (cache_version_file, true))) { writer.Write (value.ToString ()); } } } #endregion } }
// Released to the public domain. Use, modify and relicense at will. using System; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Audio; using OpenTK.Audio.OpenAL; using OpenTK.Input; using QuickFont; using System.Drawing; namespace StarterKit { class Game : GameWindow { QFont heading1; QFont heading2; QFont mainText; QFont codeText; QFont controlsText; QFont monoSpaced; #region string constants String introduction = @"Welcome to the QuickFont tutorial. All text in this tutorial (including headings!) is drawn with QuickFont, so it is also intended to showcase the library. :) If you want to get started immediately, you can skip the rest of this introduction by pressing [Right]. You can also press [Left] to go back to previous pages at any point" + Environment.NewLine + Environment.NewLine + "Why QuickFont? QuickFont is intended as a replacement (and improvement upon) OpenTK's TextPrinter library. My primary motivation for writing it was for practical reasons: I'm using OpenTK to write a game, and currently the most annoying bugs are all being caused by TextPrinter: it is slow, it is buggy, and no one wants to maintain it." + Environment.NewLine + Environment.NewLine + "I did consider simply fixing it, but then decided that it would be easier and more fun to write my own library from scratch. That is exactly what I've done." + Environment.NewLine + Environment.NewLine + "In fact it's turned out to be well worth it. It has only taken me a few days to write the library, and already it has quite a few really cool features which I will be using in my game."; String usingQuickFontIsSuperEasy = @"Using QuickFont is super easy. To load a font: "; String loadingAFont1 = "myFont = new QFont(\"HappySans.ttf\", 16);"; String andPrintWithIt = @"...and to print with it: "; String printWithFont1 = "QFont.Begin();" + Environment.NewLine + "myFont.Print(\"Hello World!\")" + Environment.NewLine + "QFont.End();"; String itIsAlsoEasyToMeasure = "It is also very easy to measure text: "; String measureText1 = "var bounds = myFont.Measure(\"Hello World\"); "; String oneOfTheFirstGotchas = "One of the first \"gotchas\" that I experienced with the old TextPrinter was having to manage a private font collection. Unlike TextPrinter, QuickFont does not need the private font collection (or Font object for that matter) to exist after construction. QuickFont works out everything it needs at load time, hence you can just pass it a file name, it will load the pfc internally and then chuck it away immediately. If you still prefer to manage a font collection yourself, and you simply want to create a QuickFont from a font object, that's fine: QuickFont has a constructor for this: "; String loadingAFont2 = "myFont = new QFont(fontObject);"; String whenPrintingText = "When printing text, you can specify" + Environment.NewLine + "an alignment. Unbounded text can" + Environment.NewLine + "be left-aligned, right-aligned " + Environment.NewLine + "or centered. You specify the " + Environment.NewLine + "alignment as follows: "; String printWithFont2 = "myFont.Print(\"Hello World!\",QFontAlignment.Right)"; String righAlignedText = "Right-aligned text will appear" + Environment.NewLine + "to the left of the original" + Environment.NewLine + "position, given by this red line."; String centredTextAsYou = "Centred text, as you would expect, is centred" + Environment.NewLine + "around the current position. The default alignment" + Environment.NewLine + "is Left. As you can see, you can include " + Environment.NewLine + "line-breaks in unbounded text."; String ofCourseItsNot = "Of course, it's not much fun having to insert your own line-breaks. A much better option is to simply specify the bounds of your text, and then let QuickFont decide where the line-breaks should go for you. You do this by specifying maxWidth. " + Environment.NewLine + Environment.NewLine + "You can still specify line-breaks for new paragraphs. For example, this is all written using a single print. QuickFont is also clever enough to spot where it might have accidentally inserted a line-break just before you have explicitly included one in the text. In this case, it will make sure that it does not insert a redundant line-break. :)" + Environment.NewLine + Environment.NewLine + "Another really cool feature of QuickFont, as you may have guessed already, is that it supports justified bounded text. It was quite tricky to get it all working pixel-perfectly, but as you can see, the results are pretty good. The precise justification settings are configurable in myFont.Options." + Environment.NewLine + Environment.NewLine + "You can press the [Up] and [Down] arrow keys to change the alignment on this block of bounded text. You can also press the [Enter] key to test some serious bounding! Note that the bound height is always ignored."; String anotherCoolFeature = "QuickFont works by using the System.Drawing to render to a bitmap, and then measuring and targeting each glyph before packing them into another bitmap which is then turned into an OpenGL texture. So essentially all fonts are \"texture\" fonts. However, QuickFont also allows you to get at the bitmaps before they are turned into OpenGL textures, save them to png file(s), modify them and then load (and retarget/remeasure) them again as QFonts. Sound complicated? - Don't worry, it's really easy. :)" + Environment.NewLine + Environment.NewLine + "Firstly, you need to create your new silhouette files from an existing font. You only want to call this code once, as calling it again will overwrite your modified .png, so take care. :) "; String textureFontCode1 = "QFont.CreateTextureFontFiles(\"HappySans.ttf\",16,\"myTextureFont\");"; String thisWillHaveCreated = "This will have created two files: \"myTextureFont.qfont\" and \"myTextureFont.png\" (or possibly multiple png files if your font is very large - I will explain how to configure this later). The next step is to actually texture your font. The png file(s) contain packed font silhouettes, perfect for layer effects in programs such as photoshop or GIMP. I suggest locking the alpha channel first, because QuickFont will complain if you merge two glyphs. You can enlarge glyphs at this stage, and QuickFont will automatically retarget each glyph when you next load the texture; however, it will fail if glyphs are merged... "; String ifYouDoIntend = "...if you do intend to increase the size of the glyphs, then you can configure the silhouette texture to be generated with larger glyph margins to avoid glyphs merging. Here, I've also configured the texture sheet size a bit larger because the font is large and I want it all on one sheet for convenience: "; String textureFontCode2 = "QFontBuilderConfiguration config = new QFontBuilderConfiguration();" + Environment.NewLine + "config.GlyphMargin = 6;" + Environment.NewLine + "config.PageWidth = 1024;" + Environment.NewLine + "config.PageHeight = 1024;" + Environment.NewLine + "QFont.CreateTextureFontFiles(\"HappySans.ttf\",48,config,\"myTextureFont\");"; String actuallyTexturing = "Actually texturing the glyphs is really going to come down to how skilled you are in photoshop, and how good the original font was that you chose as a silhouette. To give you an idea: this very cool looking font I'm using for headings only took me 3 minutes to texture in photoshop because I did it with layer affects that did all glyphs at once. :)" + Environment.NewLine + Environment.NewLine + "Anyway, once you've finished texturing your font, save the png file. Now you can load the font and write with it just like any other font!"; String textureFontCode3 = "myTexureFont = QFont.FromQFontFile(\"myTextureFont.qfont\");"; String asIhaveleant = "As I have learnt, trying to create drop-shadows as part of the glyphs themselves gives very poor results because the glyphs become larger than usual and the font looks poor when printed. To do drop-shadows properly, they need to be rendered separately underneath each glyph. This is what QuickFont does. In fact it does a lot more: it will generate the drop-shadow textures for you. It's super-easy to create a font with a drop-shadow: "; String dropShadowCode1 = "myFont = new QFont(\"HappySans.ttf\", 16, new QFontBuilderConfiguration(true));"; String thisWorksFine = "This works fine for texture fonts too: "; String dropShadowCode2 = "myTexureFont = QFont.FromQFontFile(\"myTextureFont.qfont\", new QFontLoaderConfiguration(true));"; String onceAFont = "Once a font has been loaded with a drop-shadow, it will automatically be rendered with a shadow. However, you can turn this off or customise the drop-shadow in myFont.options when rendering (I am rotating the drop shadow here, which looks kind of cool but is now giving me a headache xD). I've turned drop-shadows on for this font on this page; however, they are very subtle because the font is so tiny. If you want the shadow to be more visible for tiny fonts like this, you could modify the DropShadowConfiguration object passed into the font constructor to blur the shadow less severely during creation. "; String thereAreActually = "There are actually a lot more interesting config values and neat things that QuickFont does. Now that I look back at it, it's a bit crazy that I got this all done in a few days, but this tutorial is getting a bit tedious to write and I'm dying to get on with making my game, so I'm going to leave it at this. " + Environment.NewLine + Environment.NewLine + "I suppose I should also mention that there are almost certainly going to be a few bugs. Let me know if you find any and I will get them fixed asap. :) " + Environment.NewLine + Environment.NewLine + "I should probably also say something about the code: it's not unit tested and it probably would need a good few hours of refactoring before it would be clean enough to be respectable. I will do this at some point. Also, feel free to berate me if I'm severely breaking any conventions. I'm a programmer by profession and really should know better. ;)" + Environment.NewLine + Environment.NewLine + "With regard to features: I'm probably not going to add many more to this library. It really is intended for rendering cool-looking text quickly for things like games. If you want highly formatted text, for example, then it probably isn't the right tool. I hope you find it useful; I know I already do! :P" + Environment.NewLine + Environment.NewLine + "A tiny disclaimer: all of QuickFont is written from scratch apart from ~100 lines I stole from TextPrinter for setting the correct perspective. Obviously the example itself is just a hacked around version of the original example that comes with OpenTK."; String hereIsSomeMono = "Here is some mononspaced text. Monospaced fonts will automatically be rendered in monospace mode; however, you can render monospaced fonts ordinarily " + "or ordinary fonts in monospace mode using the render option:"; String monoCode1 = " myFont.Options.Monospacing = QFontMonospacing.Yes; "; String theDefaultMono = "The default value for this is QFontMonospacing.Natural which simply means that if the underlying font was monospaced, then use monospacing. "; String mono = " ** ** ** * * ** " + Environment.NewLine + " * * * * * * ** * * * " + Environment.NewLine + " * * * * * * ** * * " + Environment.NewLine + " * * ** * * ** "; #endregion int currentDemoPage = 1; int lastPage = 9; QFontAlignment cycleAlignment = QFontAlignment.Left; /// <summary>Creates a 800x600 window with the specified title.</summary> public Game() : base(800, 600, GraphicsMode.Default, "OpenTK Quick Start Sample") { VSync = VSyncMode.On; this.WindowBorder = WindowBorder.Fixed; } private void KeyDown(object sender, KeyboardKeyEventArgs keyEventArgs) { switch (keyEventArgs.Key) { case Key.Space: case Key.Right: currentDemoPage++; break; case Key.BackSpace: case Key.Left: currentDemoPage--; break; case Key.Enter: { if (currentDemoPage == 4) boundsAnimationCnt = 0f; } break; case Key.Up: { if (currentDemoPage == 4) { if(cycleAlignment == QFontAlignment.Justify) cycleAlignment = QFontAlignment.Left; else cycleAlignment++; } } break; case Key.Down: { if (currentDemoPage == 4) { if(cycleAlignment == QFontAlignment.Left) cycleAlignment = QFontAlignment.Justify; else cycleAlignment--; } } break; case Key.F9: break; } if (currentDemoPage > lastPage) currentDemoPage = lastPage; if (currentDemoPage < 1) currentDemoPage = 1; } /// <summary>Load resources here.</summary> /// <param name="e">Not used.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.Keyboard.KeyDown += KeyDown; /* QFontBuilderConfiguration config = new QFontBuilderConfiguration(); config.PageWidth = 1024; config.PageHeight = 1024; config.GlyphMargin = 6; QFont.CreateTextureFontFiles("BURNSTOW.TTF", 120, config, "metalFont"); */ heading2 = QFont.FromQFontFile("woodenFont.qfont", 1.0f, new QFontLoaderConfiguration(true)); var builderConfig = new QFontBuilderConfiguration(true); builderConfig.ShadowConfig.blurRadius = 1; //reduce blur radius because font is very small builderConfig.TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit; //best render hint for this font mainText = new QFont("Fonts/times.ttf", 14, builderConfig); heading1 = new QFont("Fonts/HappySans.ttf", 72, new QFontBuilderConfiguration(true)); controlsText = new QFont("Fonts/HappySans.ttf", 32, new QFontBuilderConfiguration(true)); codeText = new QFont("Fonts/Comfortaa-Regular.ttf", 12,FontStyle.Regular); heading1.Options.Colour = new Color4(0.2f, 0.2f, 0.2f, 1.0f); mainText.Options.Colour = new Color4(0.1f, 0.1f, 0.1f, 1.0f); mainText.Options.DropShadowActive = false; codeText.Options.Colour = new Color4(0.0f, 0.0f, 0.4f, 1.0f); QFontBuilderConfiguration config2 = new QFontBuilderConfiguration(); config2.SuperSampleLevels = 1; // font = new QFont("Fonts/times.ttf", 16,config2); // font.Options.Colour = new Color4(0.1f, 0.1f, 0.1f, 1.0f); // font.Options.CharacterSpacing = 0.1f; monoSpaced = new QFont("Fonts/Anonymous.ttf", 10); monoSpaced.Options.Colour = new Color4(0.1f, 0.1f, 0.1f, 1.0f); Console.WriteLine(" Monospaced : " + monoSpaced.IsMonospacingActive); GL.ClearColor(1.0f, 1.0f, 1.0f, 0.0f); GL.Disable(EnableCap.DepthTest); } /// <summary> /// Called when your window is resized. Set your viewport here. It is also /// a good place to set up your projection matrix (which probably changes /// along when the aspect ratio of your window). /// </summary> /// <param name="e">Not used.</param> protected override void OnResize(EventArgs e) { base.OnResize(e); GL.Viewport(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width, ClientRectangle.Height); Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, Width / (float)Height, 1.0f, 64.0f); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref projection); } double cnt; double boundsAnimationCnt = 1.0f; /// <summary> /// Called when it is time to setup the next frame. Add you game logic here. /// </summary> /// <param name="e">Contains timing information for framerate independent logic.</param> protected override void OnUpdateFrame(FrameEventArgs e) { base.OnUpdateFrame(e); if (Keyboard[Key.Escape]) Exit(); cnt += e.Time; if (boundsAnimationCnt < 1.0f) boundsAnimationCnt += e.Time * 0.2f; else boundsAnimationCnt = 1.0f; } private void PrintWithBounds(QFont font, string text, RectangleF bounds, QFontAlignment alignment, ref float yOffset) { GL.Disable(EnableCap.Texture2D); GL.Color4(1.0f, 0f, 0f, 1.0f); float maxWidth = bounds.Width; float height = font.Measure(text, maxWidth, alignment).Height; GL.Begin(BeginMode.LineLoop); GL.Vertex3(bounds.X, bounds.Y, 0f); GL.Vertex3(bounds.X + bounds.Width, bounds.Y, 0f); GL.Vertex3(bounds.X + bounds.Width, bounds.Y + height, 0f); GL.Vertex3(bounds.X, bounds.Y + height, 0f); GL.End(); font.Print(text, maxWidth, alignment, new Vector2(bounds.X,bounds.Y)); yOffset += height; } //some helpers private void PrintComment(string comment, ref float yOffset) { PrintComment(mainText, comment, QFontAlignment.Justify, ref yOffset); } private void PrintComment(QFont font, string comment,QFontAlignment alignment, ref float yOffset){ GL.PushMatrix(); yOffset += 20; GL.Translate(30f, yOffset, 0f); font.Print(comment, Width - 60, alignment); yOffset += font.Measure(comment, Width - 60, alignment).Height; GL.PopMatrix(); } private void PrintCommentWithLine(string comment, QFontAlignment alignment, float xOffset, ref float yOffset) { PrintCommentWithLine(mainText, comment, alignment, xOffset, ref yOffset); } private void PrintCommentWithLine(QFont font, string comment, QFontAlignment alignment, float xOffset, ref float yOffset) { GL.PushMatrix(); yOffset += 20; GL.Translate((int)xOffset, yOffset, 0f); font.Print(comment, alignment); var bounds = font.Measure(comment, Width-60, alignment); GL.Disable(EnableCap.Texture2D); GL.Begin(BeginMode.Lines); GL.Color4(1.0f, 0f, 0f, 1f); GL.Vertex2(0f, 0f); GL.Color4(1.0f, 0f, 0f, 1f); GL.Vertex2(0f, bounds.Height + 20f); GL.End(); yOffset += bounds.Height; GL.PopMatrix(); } private void PrintCode(string code, ref float yOffset){ GL.PushMatrix(); yOffset += 20; GL.Translate(50f, yOffset, 0f); codeText.Print(code, Width - 50, QFontAlignment.Left); yOffset += codeText.Measure(code, Width - 50, QFontAlignment.Left).Height; GL.PopMatrix(); } /// <summary> /// Called when it is time to render the next frame. Add your rendering code here. /// </summary> /// <param name="e">Contains timing information.</param> protected override void OnRenderFrame(FrameEventArgs e) { base.OnRenderFrame(e); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); Matrix4 modelview = Matrix4.LookAt(Vector3.Zero, Vector3.UnitZ, Vector3.UnitY); GL.MatrixMode(MatrixMode.Modelview); GL.LoadMatrix(ref modelview); QFont.Begin(); GL.Begin(BeginMode.Quads); GL.Color3(1.0f, 1.0f, 1.0); GL.Vertex2(0, 0); GL.Color3(0.9f, 0.9f, 0.9f); GL.Vertex2(0, Height); GL.Color3(0.9f, 0.9f, 0.9f); GL.Vertex2(Width, Height); GL.Color3(0.9f, 0.9f, 0.9f); GL.Vertex2(Width, 0); GL.End(); QFont.End(); switch (currentDemoPage) { case 1: { float yOffset = 0; QFont.Begin(); GL.PushMatrix(); GL.Translate(Width * 0.5f, yOffset, 0f); heading1.Print("QuickFont", QFontAlignment.Centre); yOffset += heading1.Measure("QuickFont").Height; GL.PopMatrix(); GL.PushMatrix(); GL.Translate(20f, yOffset, 0f); heading2.Print("Introduction", QFontAlignment.Left); yOffset += heading2.Measure("Introduction").Height; GL.PopMatrix(); GL.PushMatrix(); GL.Translate(30f, yOffset + 20, 0f); mainText.Print(introduction, Width - 60, QFontAlignment.Justify); GL.PopMatrix(); QFont.End(); } break; case 2: { float yOffset = 20; QFont.Begin(); GL.PushMatrix(); GL.Translate(20f, yOffset, 0f); heading2.Print("Easy as ABC!", QFontAlignment.Left); yOffset += heading2.Measure("Easy as ABC!").Height; GL.PopMatrix(); PrintComment(usingQuickFontIsSuperEasy, ref yOffset); PrintCode(loadingAFont1, ref yOffset); PrintComment(andPrintWithIt, ref yOffset); PrintCode(printWithFont1, ref yOffset); PrintComment(itIsAlsoEasyToMeasure, ref yOffset); PrintCode(measureText1, ref yOffset); PrintComment(oneOfTheFirstGotchas, ref yOffset); PrintCode(loadingAFont2, ref yOffset); QFont.End(); } break; case 3: { float yOffset = 20; QFont.Begin(); GL.PushMatrix(); GL.Translate(20f, yOffset, 0f); heading2.Print("Alignment", QFontAlignment.Left); yOffset += heading2.Measure("Easy as ABC!").Height; GL.PopMatrix(); PrintCommentWithLine(whenPrintingText, QFontAlignment.Left, Width * 0.5f, ref yOffset); PrintCode(printWithFont2, ref yOffset); PrintCommentWithLine(righAlignedText, QFontAlignment.Right, Width * 0.5f, ref yOffset); yOffset += 10f; PrintCommentWithLine(centredTextAsYou, QFontAlignment.Centre, Width * 0.5f, ref yOffset); QFont.End(); } break; case 4: { float yOffset = 20; QFont.Begin(); GL.PushMatrix(); GL.Translate(20f, yOffset, 0f); heading2.Print("Bounds and Justify", QFontAlignment.Left); yOffset += heading2.Measure("Easy as ABC!").Height; GL.PopMatrix(); GL.PushMatrix(); yOffset += 20; GL.Translate((int)(Width * 0.5), yOffset, 0f); controlsText.Print("Press [Up], [Down] or [Enter]!", QFontAlignment.Centre); yOffset += controlsText.Measure("[]").Height; GL.PopMatrix(); float boundShrink = (int) (350* (1- Math.Cos(boundsAnimationCnt * Math.PI * 2))); yOffset += 15; ; PrintWithBounds(mainText, ofCourseItsNot, new RectangleF(30f + boundShrink*0.5f, yOffset, Width - 60 - boundShrink, 350f), cycleAlignment, ref yOffset); string printWithBounds = "myFont.Print(text,400f,QFontAlignment." + cycleAlignment + ");"; yOffset += 15f; PrintCode(printWithBounds, ref yOffset); QFont.End(); } break; case 5: { float yOffset = 20; QFont.Begin(); GL.PushMatrix(); GL.Translate(20f, yOffset, 0f); heading2.Print("Your own Texture Fonts", QFontAlignment.Left); yOffset += heading2.Measure("T").Height; GL.PopMatrix(); PrintComment(anotherCoolFeature, ref yOffset); PrintCode(textureFontCode1, ref yOffset); PrintComment(thisWillHaveCreated, ref yOffset); QFont.End(); } break; case 6: { float yOffset = 20; QFont.Begin(); GL.PushMatrix(); GL.Translate(20f, yOffset, 0f); heading2.Print("Your own Texture Fonts", QFontAlignment.Left); yOffset += heading2.Measure("T").Height; GL.PopMatrix(); PrintComment(ifYouDoIntend, ref yOffset); PrintCode(textureFontCode2, ref yOffset); PrintComment(actuallyTexturing, ref yOffset); PrintCode(textureFontCode3, ref yOffset); QFont.End(); } break; case 7: { float yOffset = 20; QFont.Begin(); heading2.Options.DropShadowOffset = new Vector2(0.1f + 0.2f * (float)Math.Sin(cnt), 0.1f + 0.2f * (float)Math.Cos(cnt)); GL.PushMatrix(); GL.Translate(20f, yOffset, 0f); heading2.Print("Drop Shadows", QFontAlignment.Left); yOffset += heading2.Measure("T").Height; GL.PopMatrix(); heading2.Options.DropShadowOffset = new Vector2(0.16f, 0.16f); //back to default mainText.Options.DropShadowActive = true; mainText.Options.DropShadowOpacity = 0.7f; mainText.Options.DropShadowOffset = new Vector2(0.1f + 0.2f * (float)Math.Sin(cnt), 0.1f + 0.2f * (float)Math.Cos(cnt)); PrintComment(asIhaveleant, ref yOffset); PrintCode(dropShadowCode1, ref yOffset); PrintComment(thisWorksFine, ref yOffset); PrintCode(dropShadowCode2, ref yOffset); PrintComment(onceAFont, ref yOffset); mainText.Options.DropShadowActive = false; QFont.End(); } break; case 8: { float yOffset = 20; QFont.Begin(); monoSpaced.Options.CharacterSpacing = 0.05f; GL.PushMatrix(); GL.Translate(20f, yOffset, 0f); heading2.Print("Monospaced Fonts", QFontAlignment.Left); yOffset += heading2.Measure("T").Height; GL.PopMatrix(); PrintComment(monoSpaced, hereIsSomeMono, QFontAlignment.Left, ref yOffset); PrintCode(monoCode1, ref yOffset); PrintComment(monoSpaced, theDefaultMono, QFontAlignment.Left, ref yOffset); PrintCommentWithLine(monoSpaced, mono, QFontAlignment.Left, Width * 0.5f, ref yOffset); yOffset += 2f; PrintCommentWithLine(monoSpaced, mono, QFontAlignment.Right, Width * 0.5f, ref yOffset); yOffset += 2f; PrintCommentWithLine(monoSpaced, mono, QFontAlignment.Centre, Width * 0.5f, ref yOffset); yOffset += 2f; monoSpaced.Options.CharacterSpacing = 0.5f; PrintComment(monoSpaced, "As usual, you can adjust character spacing with myFont.Options.CharacterSpacing.", QFontAlignment.Left, ref yOffset); QFont.End(); } break; case 9: { float yOffset = 20; QFont.Begin(); GL.PushMatrix(); GL.Translate(20f, yOffset, 0f); heading2.Print("In Conclusion", QFontAlignment.Left); yOffset += heading2.Measure("T").Height; GL.PopMatrix(); PrintComment(thereAreActually, ref yOffset); QFont.End(); } break; } QFont.Begin(); if (currentDemoPage != lastPage) { GL.PushMatrix(); GL.Translate(Width - 10 - 16 * (float)(1 + Math.Sin(cnt * 4)), Height - controlsText.Measure("P").Height - 10f, 0f); controlsText.Options.Colour = new Color4(0.8f, 0.1f, 0.1f, 1.0f); controlsText.Print("Press [Right] ->", QFontAlignment.Right); GL.PopMatrix(); } if (currentDemoPage != 1) { GL.PushMatrix(); GL.Translate(10 + 16 * (float)(1 + Math.Sin(cnt * 4)), Height - controlsText.Measure("P").Height - 10f, 0f); controlsText.Options.Colour = new Color4(0.8f, 0.1f, 0.1f, 1.0f); controlsText.Print("<- Press [Left]", QFontAlignment.Left); GL.PopMatrix(); } QFont.End(); GL.Disable(EnableCap.Texture2D); SwapBuffers(); } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { // The 'using' idiom guarantees proper resource cleanup. // We request 30 UpdateFrame events per second, and unlimited // RenderFrame events (as fast as the computer can handle). using (Game game = new Game()) { game.Run(30.0); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.Net.Sockets { // TODO: // - Plumb status through async APIs to avoid callbacks on synchronous completion // - NOTE: this will require refactoring in the *Async APIs to accommodate the lack // of completion posting // - Add support for unregistering + reregistering for events // - This will require a new state for each queue, unregistred, to track whether or // not the queue is currently registered to receive events // - Audit Close()-related code for the possibility of file descriptor recycling issues // - It might make sense to change _closeLock to a ReaderWriterLockSlim that is // acquired for read by all public methods before attempting a completion and // acquired for write by Close() and HandlEvents() // // NOTE: the publicly-exposed asynchronous methods should match the behavior of // Winsock overlapped sockets as closely as possible. Especially important are // completion semantics, as the consuming code relies on the Winsock behavior. // // Winsock queues a completion callback for an overlapped operation in two cases: // 1. the operation successfully completes synchronously, or // 2. the operation completes asynchronously, successfully or otherwise. // In other words, a completion callback is queued iff an operation does not // fail synchronously. The asynchronous methods below (e.g. ReceiveAsync) may // fail synchronously for either of the following reasons: // 1. an underlying system call fails synchronously, or // 2. an underlying system call returns EAGAIN, but the socket is closed before // the method is able to enqueue its corresponding operation. // In the first case, the async method should return the SocketError that // corresponds to the native error code; in the second, the method should return // SocketError.OperationAborted (which matches what Winsock would return in this // case). The publicly-exposed synchronous methods may also encounter the second // case. In this situation these methods should return SocketError.Interrupted // (which again matches Winsock). internal sealed class SocketAsyncContext { private abstract class AsyncOperation { private enum State { Waiting = 0, Running = 1, Complete = 2, Cancelled = 3 } private int _state; // Actually AsyncOperation.State. #if DEBUG private int _callbackQueued; // When non-zero, the callback has been queued. #endif public AsyncOperation Next; protected object CallbackOrEvent; public SocketError ErrorCode; public byte[] SocketAddress; public int SocketAddressLen; public ManualResetEventSlim Event { private get { return (ManualResetEventSlim)CallbackOrEvent; } set { CallbackOrEvent = value; } } public AsyncOperation() { _state = (int)State.Waiting; Next = this; } public void QueueCompletionCallback() { Debug.Assert(!(CallbackOrEvent is ManualResetEventSlim), $"Unexpected CallbackOrEvent: {CallbackOrEvent}"); Debug.Assert(_state != (int)State.Cancelled, $"Unexpected _state: {_state}"); #if DEBUG Debug.Assert(Interlocked.CompareExchange(ref _callbackQueued, 1, 0) == 0, $"Unexpected _callbackQueued: {_callbackQueued}"); #endif ThreadPool.QueueUserWorkItem(o => ((AsyncOperation)o).InvokeCallback(), this); } public bool TryComplete(SocketAsyncContext context) { Debug.Assert(_state == (int)State.Waiting, $"Unexpected _state: {_state}"); return DoTryComplete(context); } public bool TryCompleteAsync(SocketAsyncContext context) { return TryCompleteOrAbortAsync(context, abort: false); } public void AbortAsync() { bool completed = TryCompleteOrAbortAsync(null, abort: true); Debug.Assert(completed, $"Expected TryCompleteOrAbortAsync to return true"); } private bool TryCompleteOrAbortAsync(SocketAsyncContext context, bool abort) { Debug.Assert(context != null || abort, $"Unexpected values: context={context}, abort={abort}"); State oldState = (State)Interlocked.CompareExchange(ref _state, (int)State.Running, (int)State.Waiting); if (oldState == State.Cancelled) { // This operation has been cancelled. The canceller is responsible for // correctly updating any state that would have been handled by // AsyncOperation.Abort. return true; } Debug.Assert(oldState != State.Complete && oldState != State.Running, $"Unexpected oldState: {oldState}"); bool completed; if (abort) { Abort(); ErrorCode = SocketError.OperationAborted; completed = true; } else { completed = DoTryComplete(context); } if (completed) { var @event = CallbackOrEvent as ManualResetEventSlim; if (@event != null) { @event.Set(); } else { QueueCompletionCallback(); } Volatile.Write(ref _state, (int)State.Complete); return true; } Volatile.Write(ref _state, (int)State.Waiting); return false; } public bool Wait(int timeout) { if (Event.Wait(timeout)) { return true; } var spinWait = new SpinWait(); for (;;) { int state = Interlocked.CompareExchange(ref _state, (int)State.Cancelled, (int)State.Waiting); switch ((State)state) { case State.Running: // A completion attempt is in progress. Keep busy-waiting. spinWait.SpinOnce(); break; case State.Complete: // A completion attempt succeeded. Consider this operation as having completed within the timeout. return true; case State.Waiting: // This operation was successfully cancelled. return false; } } } protected abstract void Abort(); protected abstract bool DoTryComplete(SocketAsyncContext context); protected abstract void InvokeCallback(); } private abstract class TransferOperation : AsyncOperation { public byte[] Buffer; public int Offset; public int Count; public SocketFlags Flags; public int BytesTransferred; public SocketFlags ReceivedFlags; protected sealed override void Abort() { } } private abstract class SendReceiveOperation : TransferOperation { public IList<ArraySegment<byte>> Buffers; public int BufferIndex; public Action<int, byte[], int, SocketFlags, SocketError> Callback { private get { return (Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent; } set { CallbackOrEvent = value; } } protected sealed override void InvokeCallback() { Callback(BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, ErrorCode); } } private sealed class SendOperation : SendReceiveOperation { protected override bool DoTryComplete(SocketAsyncContext context) { return SocketPal.TryCompleteSendTo(context._socket, Buffer, Buffers, ref BufferIndex, ref Offset, ref Count, Flags, SocketAddress, SocketAddressLen, ref BytesTransferred, out ErrorCode); } } private sealed class ReceiveOperation : SendReceiveOperation { protected override bool DoTryComplete(SocketAsyncContext context) { return SocketPal.TryCompleteReceiveFrom(context._socket, Buffer, Buffers, Offset, Count, Flags, SocketAddress, ref SocketAddressLen, out BytesTransferred, out ReceivedFlags, out ErrorCode); } } private sealed class ReceiveMessageFromOperation : TransferOperation { public bool IsIPv4; public bool IsIPv6; public IPPacketInformation IPPacketInformation; public Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError> Callback { private get { return (Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError>)CallbackOrEvent; } set { CallbackOrEvent = value; } } protected override bool DoTryComplete(SocketAsyncContext context) { return SocketPal.TryCompleteReceiveMessageFrom(context._socket, Buffer, Offset, Count, Flags, SocketAddress, ref SocketAddressLen, IsIPv4, IsIPv6, out BytesTransferred, out ReceivedFlags, out IPPacketInformation, out ErrorCode); } protected override void InvokeCallback() { Callback(BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, IPPacketInformation, ErrorCode); } } private abstract class AcceptOrConnectOperation : AsyncOperation { } private sealed class AcceptOperation : AcceptOrConnectOperation { public int AcceptedFileDescriptor; public Action<int, byte[], int, SocketError> Callback { private get { return (Action<int, byte[], int, SocketError>)CallbackOrEvent; } set { CallbackOrEvent = value; } } protected override void Abort() { AcceptedFileDescriptor = -1; } protected override bool DoTryComplete(SocketAsyncContext context) { bool completed = SocketPal.TryCompleteAccept(context._socket, SocketAddress, ref SocketAddressLen, out AcceptedFileDescriptor, out ErrorCode); Debug.Assert(ErrorCode == SocketError.Success || AcceptedFileDescriptor == -1, $"Unexpected values: ErrorCode={ErrorCode}, AcceptedFileDescriptor={AcceptedFileDescriptor}"); return completed; } protected override void InvokeCallback() { Callback(AcceptedFileDescriptor, SocketAddress, SocketAddressLen, ErrorCode); } } private sealed class ConnectOperation : AcceptOrConnectOperation { public Action<SocketError> Callback { private get { return (Action<SocketError>)CallbackOrEvent; } set { CallbackOrEvent = value; } } protected override void Abort() { } protected override bool DoTryComplete(SocketAsyncContext context) { bool result = SocketPal.TryCompleteConnect(context._socket, SocketAddressLen, out ErrorCode); context.RegisterConnectResult(ErrorCode); return result; } protected override void InvokeCallback() { Callback(ErrorCode); } } private enum QueueState { Clear = 0, Set = 1, Stopped = 2, } private struct OperationQueue<TOperation> where TOperation : AsyncOperation { private AsyncOperation _tail; public QueueState State { get; set; } public bool IsStopped { get { return State == QueueState.Stopped; } } public bool IsEmpty { get { return _tail == null; } } public void Enqueue(TOperation operation) { Debug.Assert(!IsStopped, "Expected !IsStopped"); Debug.Assert(operation.Next == operation, "Expected operation.Next == operation"); if (!IsEmpty) { operation.Next = _tail.Next; _tail.Next = operation; } _tail = operation; } private bool TryDequeue(out TOperation operation) { if (_tail == null) { operation = null; return false; } AsyncOperation head = _tail.Next; if (head == _tail) { _tail = null; } else { _tail.Next = head.Next; } head.Next = null; operation = (TOperation)head; return true; } private void Requeue(TOperation operation) { // Insert at the head of the queue Debug.Assert(!IsStopped, "Expected !IsStopped"); Debug.Assert(operation.Next == null, "Operation already in queue"); if (IsEmpty) { operation.Next = operation; _tail = operation; } else { operation.Next = _tail.Next; _tail.Next = operation; } } public OperationQueue<TOperation> Stop() { OperationQueue<TOperation> result = this; _tail = null; State = QueueState.Stopped; return result; } public void Complete(SocketAsyncContext context) { if (IsStopped) return; State = QueueState.Set; TOperation op; while (TryDequeue(out op)) { if (!op.TryCompleteAsync(context)) { Requeue(op); return; } } } public void StopAndAbort() { OperationQueue<TOperation> queue = Stop(); TOperation op; while (queue.TryDequeue(out op)) { op.AbortAsync(); } } public bool AllOfType<TCandidate>() where TCandidate : TOperation { bool tailIsCandidateType = _tail is TCandidate; #if DEBUG // We assume that all items are of the specified type, or all are not. Check this invariant. if (_tail != null) { AsyncOperation op = _tail; do { Debug.Assert((op is TCandidate) == tailIsCandidateType, $"Unexpected values: op={op}, tailIsCandidateType={tailIsCandidateType}"); op = op.Next; } while (op != _tail); } #endif return tailIsCandidateType; } } private SafeCloseSocket _socket; private OperationQueue<TransferOperation> _receiveQueue; private OperationQueue<SendOperation> _sendQueue; private OperationQueue<AcceptOrConnectOperation> _acceptOrConnectQueue; private SocketAsyncEngine.Token _asyncEngineToken; private Interop.Sys.SocketEvents _registeredEvents; private bool _nonBlockingSet; private bool _connectFailed; // // We have separate locks for send and receive queues, so they can proceed concurrently. Accept and connect // use the same lock as send, since they can't happen concurrently anyway. // private readonly object _sendAcceptConnectLock = new object(); private readonly object _receiveLock = new object(); private readonly object _registerLock = new object(); public SocketAsyncContext(SafeCloseSocket socket) { _socket = socket; } private void Register(Interop.Sys.SocketEvents events) { lock (_registerLock) { Debug.Assert((_registeredEvents & events) == Interop.Sys.SocketEvents.None, $"Unexpected values: _registeredEvents={_registeredEvents}, events={events}"); if (!_asyncEngineToken.WasAllocated) { _asyncEngineToken = new SocketAsyncEngine.Token(this); } events |= _registeredEvents; Interop.Error errorCode; if (!_asyncEngineToken.TryRegister(_socket, _registeredEvents, events, out errorCode)) { // TODO: throw an appropriate exception throw new Exception(string.Format("SocketAsyncContext.Register: {0}", errorCode)); } _registeredEvents = events; } } public void Close() { // Drain queues lock (_sendAcceptConnectLock) { _acceptOrConnectQueue.StopAndAbort(); _sendQueue.StopAndAbort(); } lock (_receiveLock) { _receiveQueue.StopAndAbort(); } lock (_registerLock) { // Freeing the token will prevent any future event delivery. This socket will be unregistered // from the event port automatically by the OS when it's closed. _asyncEngineToken.Free(); } } public void SetNonBlocking() { // // Our sockets may start as blocking, and later transition to non-blocking, either because the user // explicitly requested non-blocking mode, or because we need non-blocking mode to support async // operations. We never transition back to blocking mode, to avoid problems synchronizing that // transition with the async infrastructure. // // Note that there's no synchronization here, so we may set the non-blocking option multiple times // in a race. This should be fine. // if (!_nonBlockingSet) { if (Interop.Sys.Fcntl.SetIsNonBlocking(_socket, 1) != 0) { throw new SocketException((int)SocketPal.GetSocketErrorForErrorCode(Interop.Sys.GetLastError())); } _nonBlockingSet = true; } } public void CheckForPriorConnectFailure() { if (_connectFailed) { throw new PlatformNotSupportedException(SR.net_sockets_connect_multiconnect_notsupported); } } public void RegisterConnectResult(SocketError error) { if (error != SocketError.Success && error != SocketError.WouldBlock) { _connectFailed = true; } } private bool TryBeginOperation<TOperation>(ref OperationQueue<TOperation> queue, TOperation operation, Interop.Sys.SocketEvents events, bool maintainOrder, out bool isStopped) where TOperation : AsyncOperation { // Exactly one of the two queue locks must be held by the caller Debug.Assert(Monitor.IsEntered(_sendAcceptConnectLock) ^ Monitor.IsEntered(_receiveLock)); switch (queue.State) { case QueueState.Stopped: isStopped = true; return false; case QueueState.Clear: break; case QueueState.Set: if (queue.IsEmpty || !maintainOrder) { isStopped = false; queue.State = QueueState.Clear; return false; } break; } if ((_registeredEvents & events) == Interop.Sys.SocketEvents.None) { Register(events); } queue.Enqueue(operation); isStopped = false; return true; } public SocketError Accept(byte[] socketAddress, ref int socketAddressLen, int timeout, out int acceptedFd) { Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}"); Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); SocketError errorCode; if (SocketPal.TryCompleteAccept(_socket, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode)) { Debug.Assert(errorCode == SocketError.Success || acceptedFd == -1, $"Unexpected values: errorCode={errorCode}, acceptedFd={acceptedFd}"); return errorCode; } using (var @event = new ManualResetEventSlim(false, 0)) { var operation = new AcceptOperation { Event = @event, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen }; bool isStopped; while (true) { lock (_sendAcceptConnectLock) { if (TryBeginOperation(ref _acceptOrConnectQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: false, isStopped: out isStopped)) { break; } } if (isStopped) { acceptedFd = -1; return SocketError.Interrupted; } if (operation.TryComplete(this)) { socketAddressLen = operation.SocketAddressLen; acceptedFd = operation.AcceptedFileDescriptor; return operation.ErrorCode; } } if (!operation.Wait(timeout)) { acceptedFd = -1; return SocketError.TimedOut; } socketAddressLen = operation.SocketAddressLen; acceptedFd = operation.AcceptedFileDescriptor; return operation.ErrorCode; } } public SocketError AcceptAsync(byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketError> callback) { Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}"); Debug.Assert(callback != null, "Expected non-null callback"); SetNonBlocking(); int acceptedFd; SocketError errorCode; if (SocketPal.TryCompleteAccept(_socket, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode)) { Debug.Assert(errorCode == SocketError.Success || acceptedFd == -1, $"Unexpected values: errorCode={errorCode}, acceptedFd={acceptedFd}"); if (errorCode == SocketError.Success) { ThreadPool.QueueUserWorkItem(args => { var tup = (Tuple<Action<int, byte[], int, SocketError>, int, byte[], int>)args; tup.Item1(tup.Item2, tup.Item3, tup.Item4, SocketError.Success); }, Tuple.Create(callback, acceptedFd, socketAddress, socketAddressLen)); } return errorCode; } var operation = new AcceptOperation { Callback = callback, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen }; bool isStopped; while (true) { lock (_sendAcceptConnectLock) { if (TryBeginOperation(ref _acceptOrConnectQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: false, isStopped: out isStopped)) { break; } } if (isStopped) { return SocketError.OperationAborted; } if (operation.TryComplete(this)) { operation.QueueCompletionCallback(); break; } } return SocketError.IOPending; } public SocketError Connect(byte[] socketAddress, int socketAddressLen, int timeout) { Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}"); Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); CheckForPriorConnectFailure(); SocketError errorCode; if (SocketPal.TryStartConnect(_socket, socketAddress, socketAddressLen, out errorCode)) { RegisterConnectResult(errorCode); return errorCode; } using (var @event = new ManualResetEventSlim(false, 0)) { var operation = new ConnectOperation { Event = @event, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen }; bool isStopped; while (true) { lock (_sendAcceptConnectLock) { if (TryBeginOperation(ref _acceptOrConnectQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: false, isStopped: out isStopped)) { break; } } if (isStopped) { return SocketError.Interrupted; } if (operation.TryComplete(this)) { return operation.ErrorCode; } } return operation.Wait(timeout) ? operation.ErrorCode : SocketError.TimedOut; } } public SocketError ConnectAsync(byte[] socketAddress, int socketAddressLen, Action<SocketError> callback) { Debug.Assert(socketAddress != null, "Expected non-null socketAddress"); Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}"); Debug.Assert(callback != null, "Expected non-null callback"); CheckForPriorConnectFailure(); SetNonBlocking(); SocketError errorCode; if (SocketPal.TryStartConnect(_socket, socketAddress, socketAddressLen, out errorCode)) { RegisterConnectResult(errorCode); if (errorCode == SocketError.Success) { ThreadPool.QueueUserWorkItem(arg => ((Action<SocketError>)arg)(SocketError.Success), callback); } return errorCode; } var operation = new ConnectOperation { Callback = callback, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen }; bool isStopped; while (true) { lock (_sendAcceptConnectLock) { if (TryBeginOperation(ref _acceptOrConnectQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: false, isStopped: out isStopped)) { break; } } if (isStopped) { return SocketError.OperationAborted; } if (operation.TryComplete(this)) { operation.QueueCompletionCallback(); break; } } return SocketError.IOPending; } public SocketError Receive(byte[] buffer, int offset, int count, ref SocketFlags flags, int timeout, out int bytesReceived) { int socketAddressLen = 0; return ReceiveFrom(buffer, offset, count, ref flags, null, ref socketAddressLen, timeout, out bytesReceived); } public SocketError ReceiveAsync(byte[] buffer, int offset, int count, SocketFlags flags, Action<int, byte[], int, SocketFlags, SocketError> callback) { return ReceiveFromAsync(buffer, offset, count, flags, null, 0, callback); } public SocketError ReceiveFrom(byte[] buffer, int offset, int count, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, int timeout, out int bytesReceived) { Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); ManualResetEventSlim @event = null; try { ReceiveOperation operation; lock (_receiveLock) { SocketFlags receivedFlags; SocketError errorCode; if (_receiveQueue.IsEmpty && SocketPal.TryCompleteReceiveFrom(_socket, buffer, offset, count, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode)) { flags = receivedFlags; return errorCode; } @event = new ManualResetEventSlim(false, 0); operation = new ReceiveOperation { Event = @event, Buffer = buffer, Offset = offset, Count = count, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, }; bool isStopped; while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { flags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return SocketError.Interrupted; } if (operation.TryComplete(this)) { socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return operation.ErrorCode; } } } bool signaled = operation.Wait(timeout); socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return signaled ? operation.ErrorCode : SocketError.TimedOut; } finally { if (@event != null) @event.Dispose(); } } public SocketError ReceiveFromAsync(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketFlags, SocketError> callback) { SetNonBlocking(); lock (_receiveLock) { int bytesReceived; SocketFlags receivedFlags; SocketError errorCode; if (_receiveQueue.IsEmpty && SocketPal.TryCompleteReceiveFrom(_socket, buffer, offset, count, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode)) { if (errorCode == SocketError.Success) { ThreadPool.QueueUserWorkItem(args => { var tup = (Tuple<Action<int, byte[], int, SocketFlags, SocketError>, int, byte[], int, SocketFlags>)args; tup.Item1(tup.Item2, tup.Item3, tup.Item4, tup.Item5, SocketError.Success); }, Tuple.Create(callback, bytesReceived, socketAddress, socketAddressLen, receivedFlags)); } return errorCode; } var operation = new ReceiveOperation { Callback = callback, Buffer = buffer, Offset = offset, Count = count, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, }; bool isStopped; while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { return SocketError.OperationAborted; } if (operation.TryComplete(this)) { operation.QueueCompletionCallback(); break; } } return SocketError.IOPending; } } public SocketError Receive(IList<ArraySegment<byte>> buffers, ref SocketFlags flags, int timeout, out int bytesReceived) { return ReceiveFrom(buffers, ref flags, null, 0, timeout, out bytesReceived); } public SocketError ReceiveAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, Action<int, byte[], int, SocketFlags, SocketError> callback) { return ReceiveFromAsync(buffers, flags, null, 0, callback); } public SocketError ReceiveFrom(IList<ArraySegment<byte>> buffers, ref SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesReceived) { Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); ManualResetEventSlim @event = null; try { ReceiveOperation operation; lock (_receiveLock) { SocketFlags receivedFlags; SocketError errorCode; if (_receiveQueue.IsEmpty && SocketPal.TryCompleteReceiveFrom(_socket, buffers, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode)) { flags = receivedFlags; return errorCode; } @event = new ManualResetEventSlim(false, 0); operation = new ReceiveOperation { Event = @event, Buffers = buffers, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, }; bool isStopped; while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { flags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return SocketError.Interrupted; } if (operation.TryComplete(this)) { socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return operation.ErrorCode; } } } bool signaled = operation.Wait(timeout); socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; bytesReceived = operation.BytesTransferred; return signaled ? operation.ErrorCode : SocketError.TimedOut; } finally { if (@event != null) @event.Dispose(); } } public SocketError ReceiveFromAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketFlags, SocketError> callback) { SetNonBlocking(); ReceiveOperation operation; lock (_receiveLock) { int bytesReceived; SocketFlags receivedFlags; SocketError errorCode; if (_receiveQueue.IsEmpty && SocketPal.TryCompleteReceiveFrom(_socket, buffers, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode)) { if (errorCode == SocketError.Success) { ThreadPool.QueueUserWorkItem(args => { var tup = (Tuple<Action<int, byte[], int, SocketFlags, SocketError>, int, byte[], int, SocketFlags>)args; tup.Item1(tup.Item2, tup.Item3, tup.Item4, tup.Item5, SocketError.Success); }, Tuple.Create(callback, bytesReceived, socketAddress, socketAddressLen, receivedFlags)); } return errorCode; } operation = new ReceiveOperation { Callback = callback, Buffers = buffers, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, }; bool isStopped; while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { return SocketError.OperationAborted; } if (operation.TryComplete(this)) { operation.QueueCompletionCallback(); break; } } return SocketError.IOPending; } } public SocketError ReceiveMessageFrom(byte[] buffer, int offset, int count, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, int timeout, out IPPacketInformation ipPacketInformation, out int bytesReceived) { Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); ManualResetEventSlim @event = null; try { ReceiveMessageFromOperation operation; lock (_receiveLock) { SocketFlags receivedFlags; SocketError errorCode; if (_receiveQueue.IsEmpty && SocketPal.TryCompleteReceiveMessageFrom(_socket, buffer, offset, count, flags, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out bytesReceived, out receivedFlags, out ipPacketInformation, out errorCode)) { flags = receivedFlags; return errorCode; } @event = new ManualResetEventSlim(false, 0); operation = new ReceiveMessageFromOperation { Event = @event, Buffer = buffer, Offset = offset, Count = count, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, IsIPv4 = isIPv4, IsIPv6 = isIPv6, }; bool isStopped; while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; ipPacketInformation = operation.IPPacketInformation; bytesReceived = operation.BytesTransferred; return SocketError.Interrupted; } if (operation.TryComplete(this)) { socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; ipPacketInformation = operation.IPPacketInformation; bytesReceived = operation.BytesTransferred; return operation.ErrorCode; } } } bool signaled = operation.Wait(timeout); socketAddressLen = operation.SocketAddressLen; flags = operation.ReceivedFlags; ipPacketInformation = operation.IPPacketInformation; bytesReceived = operation.BytesTransferred; return signaled ? operation.ErrorCode : SocketError.TimedOut; } finally { if (@event != null) @event.Dispose(); } } public SocketError ReceiveMessageFromAsync(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, bool isIPv4, bool isIPv6, Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError> callback) { SetNonBlocking(); lock (_receiveLock) { int bytesReceived; SocketFlags receivedFlags; IPPacketInformation ipPacketInformation; SocketError errorCode; if (_receiveQueue.IsEmpty && SocketPal.TryCompleteReceiveMessageFrom(_socket, buffer, offset, count, flags, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out bytesReceived, out receivedFlags, out ipPacketInformation, out errorCode)) { if (errorCode == SocketError.Success) { ThreadPool.QueueUserWorkItem(args => { var tup = (Tuple<Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError>, int, byte[], int, SocketFlags, IPPacketInformation>)args; tup.Item1(tup.Item2, tup.Item3, tup.Item4, tup.Item5, tup.Item6, SocketError.Success); }, Tuple.Create(callback, bytesReceived, socketAddress, socketAddressLen, receivedFlags, ipPacketInformation)); } return errorCode; } var operation = new ReceiveMessageFromOperation { Callback = callback, Buffer = buffer, Offset = offset, Count = count, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, IsIPv4 = isIPv4, IsIPv6 = isIPv6, }; bool isStopped; while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { return SocketError.OperationAborted; } if (operation.TryComplete(this)) { operation.QueueCompletionCallback(); break; } } return SocketError.IOPending; } } public SocketError Send(byte[] buffer, int offset, int count, SocketFlags flags, int timeout, out int bytesSent) { return SendTo(buffer, offset, count, flags, null, 0, timeout, out bytesSent); } public SocketError SendAsync(byte[] buffer, int offset, int count, SocketFlags flags, Action<int, byte[], int, SocketFlags, SocketError> callback) { return SendToAsync(buffer, offset, count, flags, null, 0, callback); } public SocketError SendTo(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent) { Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); ManualResetEventSlim @event = null; try { SendOperation operation; lock (_sendAcceptConnectLock) { bytesSent = 0; SocketError errorCode; if (_sendQueue.IsEmpty && SocketPal.TryCompleteSendTo(_socket, buffer, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode)) { return errorCode; } @event = new ManualResetEventSlim(false, 0); operation = new SendOperation { Event = @event, Buffer = buffer, Offset = offset, Count = count, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, BytesTransferred = bytesSent }; bool isStopped; while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { bytesSent = operation.BytesTransferred; return SocketError.Interrupted; } if (operation.TryComplete(this)) { bytesSent = operation.BytesTransferred; return operation.ErrorCode; } } } bool signaled = operation.Wait(timeout); bytesSent = operation.BytesTransferred; return signaled ? operation.ErrorCode : SocketError.TimedOut; } finally { if (@event != null) @event.Dispose(); } } public SocketError SendToAsync(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketFlags, SocketError> callback) { SetNonBlocking(); lock (_sendAcceptConnectLock) { int bytesSent = 0; SocketError errorCode; if (_sendQueue.IsEmpty && SocketPal.TryCompleteSendTo(_socket, buffer, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode)) { if (errorCode == SocketError.Success) { ThreadPool.QueueUserWorkItem(args => { var tup = (Tuple<Action<int, byte[], int, SocketFlags, SocketError>, int, byte[], int>)args; tup.Item1(tup.Item2, tup.Item3, tup.Item4, 0, SocketError.Success); }, Tuple.Create(callback, bytesSent, socketAddress, socketAddressLen)); } return errorCode; } var operation = new SendOperation { Callback = callback, Buffer = buffer, Offset = offset, Count = count, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, BytesTransferred = bytesSent }; bool isStopped; while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { return SocketError.OperationAborted; } if (operation.TryComplete(this)) { operation.QueueCompletionCallback(); break; } } return SocketError.IOPending; } } public SocketError Send(IList<ArraySegment<byte>> buffers, SocketFlags flags, int timeout, out int bytesSent) { return SendTo(buffers, flags, null, 0, timeout, out bytesSent); } public SocketError SendAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, Action<int, byte[], int, SocketFlags, SocketError> callback) { return SendToAsync(buffers, flags, null, 0, callback); } public SocketError SendTo(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent) { Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}"); ManualResetEventSlim @event = null; try { SendOperation operation; lock (_sendAcceptConnectLock) { bytesSent = 0; int bufferIndex = 0; int offset = 0; SocketError errorCode; if (_sendQueue.IsEmpty && SocketPal.TryCompleteSendTo(_socket, buffers, ref bufferIndex, ref offset, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode)) { return errorCode; } @event = new ManualResetEventSlim(false, 0); operation = new SendOperation { Event = @event, Buffers = buffers, BufferIndex = bufferIndex, Offset = offset, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, BytesTransferred = bytesSent }; bool isStopped; while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { bytesSent = operation.BytesTransferred; return SocketError.Interrupted; } if (operation.TryComplete(this)) { bytesSent = operation.BytesTransferred; return operation.ErrorCode; } } } bool signaled = operation.Wait(timeout); bytesSent = operation.BytesTransferred; return signaled ? operation.ErrorCode : SocketError.TimedOut; } finally { if (@event != null) @event.Dispose(); } } public SocketError SendToAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketFlags, SocketError> callback) { SetNonBlocking(); lock (_sendAcceptConnectLock) { int bufferIndex = 0; int offset = 0; int bytesSent = 0; SocketError errorCode; if (_sendQueue.IsEmpty && SocketPal.TryCompleteSendTo(_socket, buffers, ref bufferIndex, ref offset, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode)) { if (errorCode == SocketError.Success) { ThreadPool.QueueUserWorkItem(args => { var tup = (Tuple<Action<int, byte[], int, SocketFlags, SocketError>, int, byte[], int>)args; tup.Item1(tup.Item2, tup.Item3, tup.Item4, SocketFlags.None, SocketError.Success); }, Tuple.Create(callback, bytesSent, socketAddress, socketAddressLen)); } return errorCode; } var operation = new SendOperation { Callback = callback, Buffers = buffers, BufferIndex = bufferIndex, Offset = offset, Flags = flags, SocketAddress = socketAddress, SocketAddressLen = socketAddressLen, }; bool isStopped; while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped)) { if (isStopped) { return SocketError.OperationAborted; } if (operation.TryComplete(this)) { operation.QueueCompletionCallback(); break; } } return SocketError.IOPending; } } public unsafe void HandleEvents(Interop.Sys.SocketEvents events) { if ((events & Interop.Sys.SocketEvents.Error) != 0) { // Set the Read and Write flags as well; the processing for these events // will pick up the error. events |= Interop.Sys.SocketEvents.Read | Interop.Sys.SocketEvents.Write; } if ((events & Interop.Sys.SocketEvents.Read) != 0) { lock (_sendAcceptConnectLock) { if (_acceptOrConnectQueue.AllOfType<AcceptOperation>()) { _acceptOrConnectQueue.Complete(this); } } lock (_receiveLock) { _receiveQueue.Complete(this); } } if ((events & Interop.Sys.SocketEvents.Write) != 0) { lock (_sendAcceptConnectLock) { if (_acceptOrConnectQueue.AllOfType<ConnectOperation>()) { _acceptOrConnectQueue.Complete(this); } _sendQueue.Complete(this); } } } } }
// // Copyright (c) 2006-2018 Erik Ylvisaker // // 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 AgateLib.Collections.Generic; using AgateLib.Mathematics.Geometry.Algorithms.ConvexDecomposition; namespace AgateLib.Mathematics.Geometry.Algorithms { using Quality; using System.Collections.Generic; using System.Linq; /// <summary> /// Implementation of the Shamos-Hoey Algorithm found at http://geomalgorithms.com/a09-_intersect-3.html#simple_Polygon() /// </summary> public class PolygonSweepLineAlgorithm : IPolygonSimpleDetectionAlgorithm { // Copyright 2001 softSurfer, 2012 Dan Sunday // This code may be freely used and modified for any purpose // providing that this copyright notice is included with it. // SoftSurfer makes no warranty for this code, and cannot be held // liable for any real or imagined damage resulting from its use. // Users of this code must verify correctness for their application. // Cleaned up by Erik Ylvisaker // Assume that classes are already given for the objects: // Point with 2D coordinates {float x, y;} // Polygon with n vertices {int n; Point *V;} with V[n]=V[0] // Tnode is a node element structure for a BBT // BBT is a class for a Balanced Binary Tree // such as an AVL, a 2-3, or a red-black tree // with methods given by the placeholder code: private enum EventType { Left, Right } // xyorder(): determines the xy lexicographical order of two points // returns: (+1) if p1 > p2; (-1) if p1 < p2; and 0 if equal private static int XYOrder(Microsoft.Xna.Framework.Vector2 p1, Microsoft.Xna.Framework.Vector2 p2) { // test the x-coord first if (p1.X > p2.X) { return 1; } if (p1.X < p2.X) { return (-1); } // and test the y-coord second if (p1.Y > p2.Y) { return 1; } if (p1.Y < p2.Y) { return (-1); } // when you exclude all other possibilities, what remains is... return 0; // they are the same point } // isLeft(): tests if point P2 is Left|On|Right of the line P0 to P1. // returns: >0 for left, 0 for on, and <0 for right of the line. // (see Algorithm 1 on Area of Triangles) private static double IsLeft(Microsoft.Xna.Framework.Vector2 P0, Microsoft.Xna.Framework.Vector2 P1, Microsoft.Xna.Framework.Vector2 P2) { return (P1.X - P0.X) * (P2.Y - P0.Y) - (P2.X - P0.X) * (P1.Y - P0.Y); } //=================================================================== // EventQueue Class // Event element data struct private class Event { public int Edge; // polygon edge i is V[i] to V[i+1] public EventType EventType; // event type: LEFT or RIGHT vertex public Microsoft.Xna.Framework.Vector2 Vertex; // event vertex }; private static int EventComparison(Event v1, Event v2) // qsort compare two events { return XYOrder(v1.Vertex, v2.Vertex); } // the EventQueue is a presorted array (no insertions needed) private class EventQueue { private int eventCount; // total number of events in array private int nextIndex; // index of next event on queue private List<Event> events = new List<Event>(); // array of all events private List<Event> sortedEvents = new List<Event>(); // sorted list of event pointers public EventQueue(Polygon polygon) { nextIndex = 0; eventCount = 2 * polygon.Count; // 2 vertex events for each edge events.AddRange(Enumerable.Range(0, eventCount).Select(i => new Event())); sortedEvents.AddRange(events); // Initialize event queue with edge segment endpoints for (int i = 0; i < polygon.Count; i++) { // Initialize data for edge i // The original C code had either an issue or an undocumented assumption here: // they used polygon[i + 1] which could result in an out of memory error, unless // the next point was automatically returned. sortedEvents[2 * i].Edge = i; sortedEvents[2 * i + 1].Edge = i; sortedEvents[2 * i].Vertex = polygon.At(i); sortedEvents[2 * i + 1].Vertex = polygon.At(i + 1); // determine type if (XYOrder(polygon.At(i), polygon.At(i + 1)) <= 0) { sortedEvents[2 * i].EventType = EventType.Left; sortedEvents[2 * i + 1].EventType = EventType.Right; } else { sortedEvents[2 * i].EventType = EventType.Right; sortedEvents[2 * i + 1].EventType = EventType.Left; } } // Sort Eq[] by increasing x and y sortedEvents.Sort(EventComparison); } public Event Next() { if (nextIndex >= eventCount) { return null; } return sortedEvents[nextIndex++]; } } // SweepLine Class // SweepLine segment data struct private class SweepLineSegment { public int Edge; // polygon edge i is V[i] to V[i+1] public Microsoft.Xna.Framework.Vector2 LeftVertex; // leftmost vertex point public Microsoft.Xna.Framework.Vector2 RightVertex; // rightmost vertex point public SweepLineSegment Above; // segment above this one public SweepLineSegment Below; // segment below this one public override string ToString() { return $"Edge: {Edge}, Left: {LeftVertex}, Right: {RightVertex}"; } }; private static int SLsegComparison(SweepLineSegment a, SweepLineSegment b) { return a.Edge.CompareTo(b.Edge); } // the Sweep Line itself private class SweepLine { /// <summary> /// Initial Polygon /// </summary> private readonly Polygon polygon; /// <summary> /// Balanced binary tree /// </summary> private readonly BinaryTree<SweepLineSegment> tree = new BinaryTree<SweepLineSegment>(SLsegComparison) { AutoBalance = true }; public SweepLine(Polygon polygon) // constructor { this.polygon = polygon; } public SweepLineSegment Add(Event E) { SweepLineSegment segToAdd = new SweepLineSegment { Edge = E.Edge }; // if it is being added, then it must be a LEFT edge event // but need to determine which endpoint is the left one Microsoft.Xna.Framework.Vector2 v1 = polygon.At(segToAdd.Edge); Microsoft.Xna.Framework.Vector2 v2 = polygon.At(segToAdd.Edge + 1); // determine which is leftmost if (XYOrder(v1, v2) < 0) { segToAdd.LeftVertex = v1; segToAdd.RightVertex = v2; } else { segToAdd.LeftVertex = v2; segToAdd.RightVertex = v1; } segToAdd.Above = null; segToAdd.Below = null; // add a node to the balanced binary tree BinaryTreeNode<SweepLineSegment> nd = tree.Add(segToAdd); BinaryTreeNode<SweepLineSegment> nx = nd.Next(); BinaryTreeNode<SweepLineSegment> np = nd.Previous(); if (nx != null) { segToAdd.Above = nx.Value; segToAdd.Above.Below = segToAdd; } if (np != null) { segToAdd.Below = np.Value; segToAdd.Below.Above = segToAdd; } return segToAdd; } public SweepLineSegment Find(Event E) { // need a segment to find it in the tree SweepLineSegment s = new SweepLineSegment { Edge = E.Edge, Above = null, Below = null }; BinaryTreeNode<SweepLineSegment> nd = tree.Find(s); return nd?.Value; } // test intersect of 2 segments and return: 0=none, 1=intersect public bool Intersect(SweepLineSegment s1, SweepLineSegment s2) { // no intersect if either segment doesn't exist if (s1 == null || s2 == null) { return false; } // check for consecutive edges in polygon int e1 = s1.Edge; int e2 = s2.Edge; if (((e1 + 1) % polygon.Count == e2) || (e1 == (e2 + 1) % polygon.Count)) { return false; // no non-simple intersect since consecutive } // test for existence of an intersect point double lsign, rsign; lsign = IsLeft(s1.LeftVertex, s1.RightVertex, s2.LeftVertex); // s2 left point sign rsign = IsLeft(s1.LeftVertex, s1.RightVertex, s2.RightVertex); // s2 right point sign if (lsign * rsign > 0) // s2 endpoints have same sign relative to s1 { return false; // => on same side => no intersect is possible } lsign = IsLeft(s2.LeftVertex, s2.RightVertex, s1.LeftVertex); // s1 left point sign rsign = IsLeft(s2.LeftVertex, s2.RightVertex, s1.RightVertex); // s1 right point sign if (lsign * rsign > 0) // s1 endpoints have same sign relative to s2 { return false; // => on same side => no intersect is possible } // the segments s1 and s2 straddle each other return true; // => an intersect exists } public void Remove(SweepLineSegment s) { // remove the node from the balanced binary tree BinaryTreeNode<SweepLineSegment> nd = tree.Find(s); if (nd == null) { return; // not there } // get the above and below segments pointing to each other BinaryTreeNode<SweepLineSegment> nx = nd.Next(); if (nx != null) { SweepLineSegment sx = nx.Value; sx.Below = s.Below; } BinaryTreeNode<SweepLineSegment> np = nd.Previous(); if (np != null) { SweepLineSegment sp = np.Value; sp.Above = s.Above; } tree.Remove(nd); // now can safely remove it } } /// <summary> /// simple_Polygon(): test if a Polygon is simple or not /// Input: Pn = a polygon with n vertices V[] /// Return: false(0) = is NOT simple /// true(1) = IS simple /// </summary> /// <param name="polygon"></param> /// <returns></returns> public bool IsSimple(Polygon polygon) { Require.ArgumentNotNull(polygon, nameof(polygon)); EventQueue eventQueue = new EventQueue(polygon); SweepLine sweepLine = new SweepLine(polygon); Event currentEvent; // the current event // This loop processes all events in the sorted queue // Events are only left or right vertices since // No new events will be added (an intersect => Done) while ((currentEvent = eventQueue.Next()) != null) { // while there are events if (currentEvent.EventType == EventType.Left) { // process a left vertex var currentSegment = sweepLine.Add(currentEvent); // add it to the sweep line if (sweepLine.Intersect(currentSegment, currentSegment.Above)) { return false; // Pn is NOT simple } if (sweepLine.Intersect(currentSegment, currentSegment.Below)) { return false; // Pn is NOT simple } } else { // processs a right vertex var currentSegment = sweepLine.Find(currentEvent); if (sweepLine.Intersect(currentSegment.Above, currentSegment.Below)) { return false; // Pn is NOT simple } sweepLine.Remove(currentSegment); // remove it from the sweep line } } return true; // Pn IS simple } } }
// // Options.cs // // Authors: // Jonathan Pryor <jpryor@novell.com> // // Copyright (C) 2008 Novell (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Compile With: // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll // // The LINQ version just changes the implementation of // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. // // A Getopt::Long-inspired option parsing library for C#. // // NDesk.Options.OptionSet is built upon a key/value table, where the // key is a option format string and the value is a delegate that is // invoked when the format string is matched. // // Option format strings: // Regex-like BNF Grammar: // name: .+ // type: [=:] // sep: ( [^{}]+ | '{' .+ '}' )? // aliases: ( name type sep ) ( '|' name type sep )* // // Each '|'-delimited name is an alias for the associated action. If the // format string ends in a '=', it has a required value. If the format // string ends in a ':', it has an optional value. If neither '=' or ':' // is present, no value is supported. `=' or `:' need only be defined on one // alias, but if they are provided on more than one they must be consistent. // // Each alias portion may also end with a "key/value separator", which is used // to split option values if the option accepts > 1 value. If not specified, // it defaults to '=' and ':'. If specified, it can be any character except // '{' and '}' OR the *string* between '{' and '}'. If no separator should be // used (i.e. the separate values should be distinct arguments), then "{}" // should be used as the separator. // // Options are extracted either from the current option by looking for // the option name followed by an '=' or ':', or is taken from the // following option IFF: // - The current option does not contain a '=' or a ':' // - The current option requires a value (i.e. not a Option type of ':') // // The `name' used in the option format string does NOT include any leading // option indicator, such as '-', '--', or '/'. All three of these are // permitted/required on any named option. // // Option bundling is permitted so long as: // - '-' is used to start the option group // - all of the bundled options are a single character // - at most one of the bundled options accepts a value, and the value // provided starts from the next character to the end of the string. // // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' // as '-Dname=value'. // // Option processing is disabled by specifying "--". All options after "--" // are returned by OptionSet.Parse() unchanged and unprocessed. // // Unprocessed options are returned from OptionSet.Parse(). // // Examples: // int verbose = 0; // OptionSet p = new OptionSet () // .Add ("v", v => ++verbose) // .Add ("name=|value=", v => Console.WriteLine (v)); // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); // // The above would parse the argument string array, and would invoke the // lambda expression three times, setting `verbose' to 3 when complete. // It would also print out "A" and "B" to standard output. // The returned array would contain the string "extra". // // C# 3.0 collection initializers are supported and encouraged: // var p = new OptionSet () { // { "h|?|help", v => ShowHelp () }, // }; // // System.ComponentModel.TypeConverter is also supported, allowing the use of // custom data types in the callback type; TypeConverter.ConvertFromString() // is used to convert the value option to an instance of the specified // type: // // var p = new OptionSet () { // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, // }; // // Random other tidbits: // - Boolean options (those w/o '=' or ':' in the option format string) // are explicitly enabled if they are followed with '+', and explicitly // disabled if they are followed with '-': // string a = null; // var p = new OptionSet () { // { "a", s => a = s }, // }; // p.Parse (new string[]{"-a"}); // sets v != null // p.Parse (new string[]{"-a+"}); // sets v != null // p.Parse (new string[]{"-a-"}); // sets v == null // #define LINQ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; #if LINQ #endif namespace Std.ServicesKit { public class OptionValueCollection : IList, IList<string> { List<string> values = new List<string> (); OptionContext c; internal OptionValueCollection (OptionContext c) { this.c = c; } #region ICollection void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}} object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}} #endregion #region ICollection<T> public void Add (string item) {values.Add (item);} public void Clear () {values.Clear ();} public bool Contains (string item) {return values.Contains (item);} public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} public bool Remove (string item) {return values.Remove (item);} public int Count {get {return values.Count;}} public bool IsReadOnly {get {return false;}} #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} #endregion #region IEnumerable<T> public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();} #endregion #region IList int IList.Add (object value) {return (values as IList).Add (value);} bool IList.Contains (object value) {return (values as IList).Contains (value);} int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} void IList.Remove (object value) {(values as IList).Remove (value);} void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} bool IList.IsFixedSize {get {return false;}} object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}} #endregion #region IList<T> public int IndexOf (string item) {return values.IndexOf (item);} public void Insert (int index, string item) {values.Insert (index, item);} public void RemoveAt (int index) {values.RemoveAt (index);} private void AssertValid (int index) { if (c.Option == null) throw new InvalidOperationException ("OptionContext.Option is null."); if (index >= c.Option.MaxValueCount) throw new ArgumentOutOfRangeException ("index"); if (c.Option.OptionValueType == OptionValueType.Required && index >= values.Count) throw new OptionException (string.Format ( c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), c.OptionName); } public string this [int index] { get { AssertValid (index); return index >= values.Count ? null : values [index]; } set { values [index] = value; } } #endregion public List<string> ToList () { return new List<string> (values); } public string[] ToArray () { return values.ToArray (); } public override string ToString () { return string.Join (", ", values.ToArray ()); } } public class OptionContext { private Option option; private string name; private int index; private OptionSet set; private OptionValueCollection c; public OptionContext (OptionSet set) { this.set = set; this.c = new OptionValueCollection (this); } public Option Option { get {return option;} set {option = value;} } public string OptionName { get {return name;} set {name = value;} } public int OptionIndex { get {return index;} set {index = value;} } public OptionSet OptionSet { get {return set;} } public OptionValueCollection OptionValues { get {return c;} } } public enum OptionValueType { None, Optional, Required, } public abstract class Option { string prototype, description; string[] names; OptionValueType type; int count; string[] separators; protected Option (string prototype, string description) : this (prototype, description, 1) { } protected Option (string prototype, string description, int maxValueCount) { if (prototype == null) throw new ArgumentNullException ("prototype"); if (prototype.Length == 0) throw new ArgumentException ("Cannot be the empty string.", "prototype"); if (maxValueCount < 0) throw new ArgumentOutOfRangeException ("maxValueCount"); this.prototype = prototype; this.names = prototype.Split ('|'); this.description = description; this.count = maxValueCount; this.type = ParsePrototype (); if (this.count == 0 && type != OptionValueType.None) throw new ArgumentException ( "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + "OptionValueType.Optional.", "maxValueCount"); if (this.type == OptionValueType.None && maxValueCount > 1) throw new ArgumentException ( string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), "maxValueCount"); if (Array.IndexOf (names, "<>") >= 0 && ((names.Length == 1 && this.type != OptionValueType.None) || (names.Length > 1 && this.MaxValueCount > 1))) throw new ArgumentException ( "The default option handler '<>' cannot require values.", "prototype"); } public string Prototype {get {return prototype;}} public string Description {get {return description;}} public OptionValueType OptionValueType {get {return type;}} public int MaxValueCount {get {return count;}} public string[] GetNames () { return (string[]) names.Clone (); } public string[] GetValueSeparators () { if (separators == null) return new string [0]; return (string[]) separators.Clone (); } protected static T Parse<T> (string value, OptionContext c) { Type tt = typeof (T); bool nullable = tt.IsValueType && tt.IsGenericType && !tt.IsGenericTypeDefinition && tt.GetGenericTypeDefinition () == typeof (Nullable<>); Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T); TypeConverter conv = TypeDescriptor.GetConverter (targetType); T t = default (T); try { if (value != null) t = (T) conv.ConvertFromString (value); } catch (Exception e) { throw new OptionException ( string.Format ( c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."), value, targetType.Name, c.OptionName), c.OptionName, e); } return t; } internal string[] Names {get {return names;}} internal string[] ValueSeparators {get {return separators;}} static readonly char[] NameTerminator = new char[]{'=', ':'}; private OptionValueType ParsePrototype () { char type = '\0'; List<string> seps = new List<string> (); for (int i = 0; i < names.Length; ++i) { string name = names [i]; if (name.Length == 0) throw new ArgumentException ("Empty option names are not supported.", "prototype"); int end = name.IndexOfAny (NameTerminator); if (end == -1) continue; names [i] = name.Substring (0, end); if (type == '\0' || type == name [end]) type = name [end]; else throw new ArgumentException ( string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]), "prototype"); AddSeparators (name, end, seps); } if (type == '\0') return OptionValueType.None; if (count <= 1 && seps.Count != 0) throw new ArgumentException ( string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count), "prototype"); if (count > 1) { if (seps.Count == 0) this.separators = new string[]{":", "="}; else if (seps.Count == 1 && seps [0].Length == 0) this.separators = null; else this.separators = seps.ToArray (); } return type == '=' ? OptionValueType.Required : OptionValueType.Optional; } private static void AddSeparators (string name, int end, ICollection<string> seps) { int start = -1; for (int i = end+1; i < name.Length; ++i) { switch (name [i]) { case '{': if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); start = i+1; break; case '}': if (start == -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); seps.Add (name.Substring (start, i-start)); start = -1; break; default: if (start == -1) seps.Add (name [i].ToString ()); break; } } if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); } public void Invoke (OptionContext c) { OnParseComplete (c); c.OptionName = null; c.Option = null; c.OptionValues.Clear (); } protected abstract void OnParseComplete (OptionContext c); public override string ToString () { return Prototype; } } [Serializable] public class OptionException : Exception { private string option; public OptionException () { } public OptionException (string message, string optionName) : base (message) { this.option = optionName; } public OptionException (string message, string optionName, Exception innerException) : base (message, innerException) { this.option = optionName; } protected OptionException (SerializationInfo info, StreamingContext context) : base (info, context) { this.option = info.GetString ("OptionName"); } public string OptionName { get {return this.option;} } [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] public override void GetObjectData (SerializationInfo info, StreamingContext context) { base.GetObjectData (info, context); info.AddValue ("OptionName", option); } } public delegate void OptionAction<TKey, TValue> (TKey key, TValue value); [Serializable] public class OptionSet : KeyedCollection<string, Option> { public OptionSet () : this (delegate (string f) {return f;}) { } public OptionSet (Converter<string, string> localizer) { this.localizer = localizer; } Converter<string, string> localizer; public Converter<string, string> MessageLocalizer { get {return localizer;} } protected override string GetKeyForItem (Option item) { if (item == null) throw new ArgumentNullException ("option"); if (item.Names != null && item.Names.Length > 0) return item.Names [0]; // This should never happen, as it's invalid for Option to be // constructed w/o any names. throw new InvalidOperationException ("Option has no names!"); } // [Obsolete ("Use KeyedCollection.this[string]")] protected Option GetOptionForName (string option) { if (option == null) throw new ArgumentNullException ("option"); if (!base.Contains(option)) { return null; } try { return base [option]; } catch (KeyNotFoundException) { return null; } } protected override void InsertItem (int index, Option item) { base.InsertItem (index, item); AddImpl (item); } protected override void RemoveItem (int index) { base.RemoveItem (index); Option p = Items [index]; // KeyedCollection.RemoveItem() handles the 0th item for (int i = 1; i < p.Names.Length; ++i) { Dictionary.Remove (p.Names [i]); } } protected override void SetItem (int index, Option item) { base.SetItem (index, item); RemoveItem (index); AddImpl (item); } private void AddImpl (Option option) { if (option == null) throw new ArgumentNullException ("option"); List<string> added = new List<string> (option.Names.Length); try { // KeyedCollection.InsertItem/SetItem handle the 0th name. for (int i = 1; i < option.Names.Length; ++i) { Dictionary.Add (option.Names [i], option); added.Add (option.Names [i]); } } catch (Exception) { foreach (string name in added) Dictionary.Remove (name); throw; } } public new OptionSet Add (Option option) { base.Add (option); return this; } sealed class ActionOption : Option { Action<OptionValueCollection> action; public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action) : base (prototype, description, count) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (c.OptionValues); } } public OptionSet Add (string prototype, Action<string> action) { return Add (prototype, null, action); } public OptionSet Add(string prototype, string description, Action action) { var option = new SwitchOption(prototype, description, action); Add(option); return this; } public OptionSet Add(string prototype, Action action) { var option = new SwitchOption(prototype, null, action); Add(option); return this; } public OptionSet Add(string prototype, string description, Action<string> action) { if (action == null) throw new ArgumentNullException ("action"); Option p = new ActionOption (prototype, description, 1, delegate (OptionValueCollection v) { action (v [0]); }); base.Add (p); return this; } public OptionSet Add (string prototype, OptionAction<string, string> action) { return Add (prototype, null, action); } public OptionSet Add (string prototype, string description, OptionAction<string, string> action) { if (action == null) throw new ArgumentNullException ("action"); Option p = new ActionOption (prototype, description, 2, delegate (OptionValueCollection v) {action (v [0], v [1]);}); base.Add (p); return this; } sealed class ActionOption<T> : Option { Action<T> action; public ActionOption (string prototype, string description, Action<T> action) : base (prototype, description, 1) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (Parse<T> (c.OptionValues [0], c)); } } sealed class SwitchOption : Option { Action action; public SwitchOption(string prototype, string description, Action action) : base(prototype, description, 1) { if (action == null) throw new ArgumentNullException("action"); this.action = action; } protected override void OnParseComplete(OptionContext c) { action(); } } sealed class ActionOption<TKey, TValue> : Option { OptionAction<TKey, TValue> action; public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action) : base (prototype, description, 2) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action ( Parse<TKey> (c.OptionValues [0], c), Parse<TValue> (c.OptionValues [1], c)); } } public OptionSet Add<T> (string prototype, Action<T> action) { return Add (prototype, null, action); } public OptionSet Add<T> (string prototype, string description, Action<T> action) { return Add (new ActionOption<T> (prototype, description, action)); } public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action) { return Add (prototype, null, action); } public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action) { return Add (new ActionOption<TKey, TValue> (prototype, description, action)); } protected virtual OptionContext CreateOptionContext () { return new OptionContext (this); } enum ParseMode { Unknown, Text, Arg, String } private static string[] GetArgs() { var cmdline = Environment.CommandLine; var mode = ParseMode.Text; var argBuilder = new StringBuilder(); var args = new List<string>(); var prevChr = '\0'; foreach (var chr in cmdline) { switch (mode) { case ParseMode.Text: if (chr == '"') { mode = ParseMode.String; } else if (chr == '-' || chr == '/') { mode = ParseMode.Arg; if (argBuilder.Length > 0) { args.Add(argBuilder.ToString().Trim()); argBuilder.Length = 0; } argBuilder.Append(chr); } else if (char.IsWhiteSpace(chr)) { if (argBuilder.Length > 0) { args.Add(argBuilder.ToString().Trim()); argBuilder.Length = 0; } } else { argBuilder.Append(chr); } break; case ParseMode.Arg: if (char.IsWhiteSpace(chr)) { if (argBuilder.Length > 0) { args.Add(argBuilder.ToString().Trim()); argBuilder.Length = 0; } mode = ParseMode.Text; } else if (chr == '"') { mode = ParseMode.String; } else { argBuilder.Append(chr); } break; case ParseMode.String: if (chr == '"' && prevChr != '"') { mode = ParseMode.Text; } else { argBuilder.Append(chr); } break; } prevChr = chr; } if (argBuilder.Length > 0) { args.Add(argBuilder.ToString().Trim()); } if (args.Count > 0 && !args[0].StartsWith("-") && !args[0].StartsWith("/")) { args.RemoveAt(0); } return args.ToArray(); } public List<string> Parse() { var args = GetArgs(); return Parse(args); } #if LINQ public List<string> Parse (IEnumerable<string> arguments) { bool process = true; OptionContext c = CreateOptionContext (); c.OptionIndex = -1; var def = GetOptionForName ("<>"); var unprocessed = from argument in arguments where ++c.OptionIndex >= 0 && (process || def != null) ? process ? argument == "--" ? (process = false) : !Parse (argument, c) ? def != null ? Unprocessed (null, def, c, argument) : true : false : def != null ? Unprocessed (null, def, c, argument) : true : true select argument; List<string> r = unprocessed.ToList (); if (c.Option != null) c.Option.Invoke (c); return r; } #else public List<string> Parse (IEnumerable<string> arguments) { OptionContext c = CreateOptionContext (); c.OptionIndex = -1; bool process = true; List<string> unprocessed = new List<string> (); Option def = Contains ("<>") ? this ["<>"] : null; foreach (string argument in arguments) { ++c.OptionIndex; if (argument == "--") { process = false; continue; } if (!process) { Unprocessed (unprocessed, def, c, argument); continue; } if (!Parse (argument, c)) Unprocessed (unprocessed, def, c, argument); } if (c.Option != null) c.Option.Invoke (c); return unprocessed; } #endif private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument) { if (def == null) { extra.Add (argument); return false; } c.OptionValues.Add (argument); c.Option = def; c.Option.Invoke (c); return false; } private readonly Regex ValueOption = new Regex ( @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$"); protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) { if (argument == null) throw new ArgumentNullException ("argument"); flag = name = sep = value = null; Match m = ValueOption.Match (argument); if (!m.Success) { return false; } flag = m.Groups ["flag"].Value; name = m.Groups ["name"].Value; if (m.Groups ["sep"].Success && m.Groups ["value"].Success) { sep = m.Groups ["sep"].Value; value = m.Groups ["value"].Value; } return true; } protected virtual bool Parse (string argument, OptionContext c) { if (c.Option != null) { ParseValue (argument, c); return true; } string f, n, s, v; if (!GetOptionParts (argument, out f, out n, out s, out v)) return false; Option p; if (Contains (n)) { p = this [n]; c.OptionName = f + n; c.Option = p; switch (p.OptionValueType) { case OptionValueType.None: c.OptionValues.Add (n); c.Option.Invoke (c); break; case OptionValueType.Optional: case OptionValueType.Required: ParseValue (v, c); break; } return true; } // no match; is it a bool option? if (ParseBool (argument, n, c)) return true; // is it a bundled option? if (ParseBundledValue (f, string.Concat (n + s + v), c)) return true; return false; } private void ParseValue (string option, OptionContext c) { if (option != null) foreach (string o in c.Option.ValueSeparators != null ? option.Split (c.Option.ValueSeparators, StringSplitOptions.None) : new string[]{option}) { c.OptionValues.Add (o); } if (c.OptionValues.Count == c.Option.MaxValueCount || c.Option.OptionValueType == OptionValueType.Optional) c.Option.Invoke (c); else if (c.OptionValues.Count > c.Option.MaxValueCount) { throw new OptionException (localizer (string.Format ( "Error: Found {0} option values when expecting {1}.", c.OptionValues.Count, c.Option.MaxValueCount)), c.OptionName); } } private bool ParseBool (string option, string n, OptionContext c) { Option p; string rn; if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') && Contains ((rn = n.Substring (0, n.Length-1)))) { p = this [rn]; string v = n [n.Length-1] == '+' ? option : null; c.OptionName = option; c.Option = p; c.OptionValues.Add (v); p.Invoke (c); return true; } return false; } private bool ParseBundledValue (string f, string n, OptionContext c) { if (f != "-") return false; for (int i = 0; i < n.Length; ++i) { Option p; string opt = f + n [i].ToString (); string rn = n [i].ToString (); if (!Contains (rn)) { if (i == 0) return false; throw new OptionException (string.Format (localizer ( "Cannot bundle unregistered option '{0}'."), opt), opt); } p = this [rn]; switch (p.OptionValueType) { case OptionValueType.None: Invoke (c, opt, n, p); break; case OptionValueType.Optional: case OptionValueType.Required: { string v = n.Substring (i+1); c.Option = p; c.OptionName = opt; ParseValue (v.Length != 0 ? v : null, c); return true; } default: throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType); } } return true; } private static void Invoke (OptionContext c, string name, string value, Option option) { c.OptionName = name; c.Option = option; c.OptionValues.Add (value); option.Invoke (c); } private const int OptionWidth = 29; public void WriteOptionDescriptions (TextWriter o) { foreach (Option p in this) { int written = 0; if (!WriteOptionPrototype (o, p, ref written)) continue; if (written < OptionWidth) o.Write (new string (' ', OptionWidth - written)); else { o.WriteLine (); o.Write (new string (' ', OptionWidth)); } bool indent = false; string prefix = new string (' ', OptionWidth+2); foreach (string line in GetLines (localizer (GetDescription (p.Description)))) { if (indent) o.Write (prefix); o.WriteLine (line); indent = true; } } } bool WriteOptionPrototype (TextWriter o, Option p, ref int written) { string[] names = p.Names; int i = GetNextOptionIndex (names, 0); if (i == names.Length) return false; if (names [i].Length == 1) { Write (o, ref written, " -"); Write (o, ref written, names [0]); } else { Write (o, ref written, " --"); Write (o, ref written, names [0]); } for ( i = GetNextOptionIndex (names, i+1); i < names.Length; i = GetNextOptionIndex (names, i+1)) { Write (o, ref written, ", "); Write (o, ref written, names [i].Length == 1 ? "-" : "--"); Write (o, ref written, names [i]); } if (p.OptionValueType == OptionValueType.Optional || p.OptionValueType == OptionValueType.Required) { if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, localizer ("[")); } Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 ? p.ValueSeparators [0] : " "; for (int c = 1; c < p.MaxValueCount; ++c) { Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); } if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, localizer ("]")); } } return true; } static int GetNextOptionIndex (string[] names, int i) { while (i < names.Length && names [i] == "<>") { ++i; } return i; } static void Write (TextWriter o, ref int n, string s) { n += s.Length; o.Write (s); } private static string GetArgumentName (int index, int maxIndex, string description) { if (description == null) return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); string[] nameStart; if (maxIndex == 1) nameStart = new string[]{"{0:", "{"}; else nameStart = new string[]{"{" + index + ":"}; for (int i = 0; i < nameStart.Length; ++i) { int start, j = 0; do { start = description.IndexOf (nameStart [i], j); } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false); if (start == -1) continue; int end = description.IndexOf ("}", start); if (end == -1) continue; return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length); } return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); } private static string GetDescription (string description) { if (description == null) return string.Empty; StringBuilder sb = new StringBuilder (description.Length); int start = -1; for (int i = 0; i < description.Length; ++i) { switch (description [i]) { case '{': if (i == start) { sb.Append ('{'); start = -1; } else if (start < 0) start = i + 1; break; case '}': if (start < 0) { if ((i+1) == description.Length || description [i+1] != '}') throw new InvalidOperationException ("Invalid option description: " + description); ++i; sb.Append ("}"); } else { sb.Append (description.Substring (start, i - start)); start = -1; } break; case ':': if (start < 0) goto default; start = i + 1; break; default: if (start < 0) sb.Append (description [i]); break; } } return sb.ToString (); } private static IEnumerable<string> GetLines (string description) { if (string.IsNullOrEmpty (description)) { yield return string.Empty; yield break; } int length = 80 - OptionWidth - 1; int start = 0, end; do { end = GetLineEnd (start, length, description); char c = description [end-1]; if (char.IsWhiteSpace (c)) --end; bool writeContinuation = end != description.Length && !IsEolChar (c); string line = description.Substring (start, end - start) + (writeContinuation ? "-" : ""); yield return line; start = end; if (char.IsWhiteSpace (c)) ++start; length = 80 - OptionWidth - 2 - 1; } while (end < description.Length); } private static bool IsEolChar (char c) { return !char.IsLetterOrDigit (c); } private static int GetLineEnd (int start, int length, string description) { int end = System.Math.Min (start + length, description.Length); int sep = -1; for (int i = start; i < end; ++i) { if (description [i] == '\n') return i+1; if (IsEolChar (description [i])) sep = i+1; } if (sep == -1 || end == description.Length) return end; return sep; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; namespace System.Numerics { /// <summary> /// A structure encapsulating a 3x2 matrix. /// </summary> public struct Matrix3x2 : IEquatable<Matrix3x2> { #region Public Fields /// <summary> /// The first element of the first row /// </summary> public float M11; /// <summary> /// The second element of the first row /// </summary> public float M12; /// <summary> /// The first element of the second row /// </summary> public float M21; /// <summary> /// The second element of the second row /// </summary> public float M22; /// <summary> /// The first element of the third row /// </summary> public float M31; /// <summary> /// The second element of the third row /// </summary> public float M32; #endregion Public Fields private static readonly Matrix3x2 _identity = new Matrix3x2 ( 1f, 0f, 0f, 1f, 0f, 0f ); /// <summary> /// Returns the multiplicative identity matrix. /// </summary> public static Matrix3x2 Identity { get { return _identity; } } /// <summary> /// Returns whether the matrix is the identity matrix. /// </summary> public bool IsIdentity { get { return M11 == 1f && M22 == 1f && // Check diagonal element first for early out. M12 == 0f && M21 == 0f && M31 == 0f && M32 == 0f; } } /// <summary> /// Gets or sets the translation component of this matrix. /// </summary> public Vector2 Translation { get { return new Vector2(M31, M32); } set { M31 = value.X; M32 = value.Y; } } /// <summary> /// Constructs a Matrix3x2 from the given components. /// </summary> public Matrix3x2(float m11, float m12, float m21, float m22, float m31, float m32) { this.M11 = m11; this.M12 = m12; this.M21 = m21; this.M22 = m22; this.M31 = m31; this.M32 = m32; } /// <summary> /// Creates a translation matrix from the given vector. /// </summary> /// <param name="position">The translation position.</param> /// <returns>A translation matrix.</returns> public static Matrix3x2 CreateTranslation(Vector2 position) { Matrix3x2 result; result.M11 = 1.0f; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = 1.0f; result.M31 = position.X; result.M32 = position.Y; return result; } /// <summary> /// Creates a translation matrix from the given X and Y components. /// </summary> /// <param name="xPosition">The X position.</param> /// <param name="yPosition">The Y position.</param> /// <returns>A translation matrix.</returns> public static Matrix3x2 CreateTranslation(float xPosition, float yPosition) { Matrix3x2 result; result.M11 = 1.0f; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = 1.0f; result.M31 = xPosition; result.M32 = yPosition; return result; } /// <summary> /// Creates a scale matrix from the given X and Y components. /// </summary> /// <param name="xScale">Value to scale by on the X-axis.</param> /// <param name="yScale">Value to scale by on the Y-axis.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(float xScale, float yScale) { Matrix3x2 result; result.M11 = xScale; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = yScale; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a scale matrix that is offset by a given center point. /// </summary> /// <param name="xScale">Value to scale by on the X-axis.</param> /// <param name="yScale">Value to scale by on the Y-axis.</param> /// <param name="centerPoint">The center point.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(float xScale, float yScale, Vector2 centerPoint) { Matrix3x2 result; float tx = centerPoint.X * (1 - xScale); float ty = centerPoint.Y * (1 - yScale); result.M11 = xScale; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = yScale; result.M31 = tx; result.M32 = ty; return result; } /// <summary> /// Creates a scale matrix from the given vector scale. /// </summary> /// <param name="scales">The scale to use.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(Vector2 scales) { Matrix3x2 result; result.M11 = scales.X; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = scales.Y; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a scale matrix from the given vector scale with an offset from the given center point. /// </summary> /// <param name="scales">The scale to use.</param> /// <param name="centerPoint">The center offset.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(Vector2 scales, Vector2 centerPoint) { Matrix3x2 result; float tx = centerPoint.X * (1 - scales.X); float ty = centerPoint.Y * (1 - scales.Y); result.M11 = scales.X; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = scales.Y; result.M31 = tx; result.M32 = ty; return result; } /// <summary> /// Creates a scale matrix that scales uniformly with the given scale. /// </summary> /// <param name="scale">The uniform scale to use.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(float scale) { Matrix3x2 result; result.M11 = scale; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = scale; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a scale matrix that scales uniformly with the given scale with an offset from the given center. /// </summary> /// <param name="scale">The uniform scale to use.</param> /// <param name="centerPoint">The center offset.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(float scale, Vector2 centerPoint) { Matrix3x2 result; float tx = centerPoint.X * (1 - scale); float ty = centerPoint.Y * (1 - scale); result.M11 = scale; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = scale; result.M31 = tx; result.M32 = ty; return result; } /// <summary> /// Creates a skew matrix from the given angles in radians. /// </summary> /// <param name="radiansX">The X angle, in radians.</param> /// <param name="radiansY">The Y angle, in radians.</param> /// <returns>A skew matrix.</returns> public static Matrix3x2 CreateSkew(float radiansX, float radiansY) { Matrix3x2 result; float xTan = (float)Math.Tan(radiansX); float yTan = (float)Math.Tan(radiansY); result.M11 = 1.0f; result.M12 = yTan; result.M21 = xTan; result.M22 = 1.0f; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a skew matrix from the given angles in radians and a center point. /// </summary> /// <param name="radiansX">The X angle, in radians.</param> /// <param name="radiansY">The Y angle, in radians.</param> /// <param name="centerPoint">The center point.</param> /// <returns>A skew matrix.</returns> public static Matrix3x2 CreateSkew(float radiansX, float radiansY, Vector2 centerPoint) { Matrix3x2 result; float xTan = (float)Math.Tan(radiansX); float yTan = (float)Math.Tan(radiansY); float tx = -centerPoint.Y * xTan; float ty = -centerPoint.X * yTan; result.M11 = 1.0f; result.M12 = yTan; result.M21 = xTan; result.M22 = 1.0f; result.M31 = tx; result.M32 = ty; return result; } /// <summary> /// Creates a rotation matrix using the given rotation in radians. /// </summary> /// <param name="radians">The amount of rotation, in radians.</param> /// <returns>A rotation matrix.</returns> public static Matrix3x2 CreateRotation(float radians) { Matrix3x2 result; radians = (float)Math.IEEERemainder(radians, Math.PI * 2); float c, s; const float epsilon = 0.001f * (float)Math.PI / 180f; // 0.1% of a degree if (radians > -epsilon && radians < epsilon) { // Exact case for zero rotation. c = 1; s = 0; } else if (radians > Math.PI / 2 - epsilon && radians < Math.PI / 2 + epsilon) { // Exact case for 90 degree rotation. c = 0; s = 1; } else if (radians < -Math.PI + epsilon || radians > Math.PI - epsilon) { // Exact case for 180 degree rotation. c = -1; s = 0; } else if (radians > -Math.PI / 2 - epsilon && radians < -Math.PI / 2 + epsilon) { // Exact case for 270 degree rotation. c = 0; s = -1; } else { // Arbitrary rotation. c = (float)Math.Cos(radians); s = (float)Math.Sin(radians); } // [ c s ] // [ -s c ] // [ 0 0 ] result.M11 = c; result.M12 = s; result.M21 = -s; result.M22 = c; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a rotation matrix using the given rotation in radians and a center point. /// </summary> /// <param name="radians">The amount of rotation, in radians.</param> /// <param name="centerPoint">The center point.</param> /// <returns>A rotation matrix.</returns> public static Matrix3x2 CreateRotation(float radians, Vector2 centerPoint) { Matrix3x2 result; radians = (float)Math.IEEERemainder(radians, Math.PI * 2); float c, s; const float epsilon = 0.001f * (float)Math.PI / 180f; // 0.1% of a degree if (radians > -epsilon && radians < epsilon) { // Exact case for zero rotation. c = 1; s = 0; } else if (radians > Math.PI / 2 - epsilon && radians < Math.PI / 2 + epsilon) { // Exact case for 90 degree rotation. c = 0; s = 1; } else if (radians < -Math.PI + epsilon || radians > Math.PI - epsilon) { // Exact case for 180 degree rotation. c = -1; s = 0; } else if (radians > -Math.PI / 2 - epsilon && radians < -Math.PI / 2 + epsilon) { // Exact case for 270 degree rotation. c = 0; s = -1; } else { // Arbitrary rotation. c = (float)Math.Cos(radians); s = (float)Math.Sin(radians); } float x = centerPoint.X * (1 - c) + centerPoint.Y * s; float y = centerPoint.Y * (1 - c) - centerPoint.X * s; // [ c s ] // [ -s c ] // [ x y ] result.M11 = c; result.M12 = s; result.M21 = -s; result.M22 = c; result.M31 = x; result.M32 = y; return result; } /// <summary> /// Calculates the determinant for this matrix. /// The determinant is calculated by expanding the matrix with a third column whose values are (0,0,1). /// </summary> /// <returns>The determinant.</returns> public float GetDeterminant() { // There isn't actually any such thing as a determinant for a non-square matrix, // but this 3x2 type is really just an optimization of a 3x3 where we happen to // know the rightmost column is always (0, 0, 1). So we expand to 3x3 format: // // [ M11, M12, 0 ] // [ M21, M22, 0 ] // [ M31, M32, 1 ] // // Sum the diagnonal products: // (M11 * M22 * 1) + (M12 * 0 * M31) + (0 * M21 * M32) // // Subtract the opposite diagonal products: // (M31 * M22 * 0) + (M32 * 0 * M11) + (1 * M21 * M12) // // Collapse out the constants and oh look, this is just a 2x2 determinant! return (M11 * M22) - (M21 * M12); } /// <summary> /// Attempts to invert the given matrix. If the operation succeeds, the inverted matrix is stored in the result parameter. /// </summary> /// <param name="matrix">The source matrix.</param> /// <param name="result">The output matrix.</param> /// <returns>True if the operation succeeded, False otherwise.</returns> public static bool Invert(Matrix3x2 matrix, out Matrix3x2 result) { float det = (matrix.M11 * matrix.M22) - (matrix.M21 * matrix.M12); if (Math.Abs(det) < float.Epsilon) { result = new Matrix3x2(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN); return false; } float invDet = 1.0f / det; result.M11 = matrix.M22 * invDet; result.M12 = -matrix.M12 * invDet; result.M21 = -matrix.M21 * invDet; result.M22 = matrix.M11 * invDet; result.M31 = (matrix.M21 * matrix.M32 - matrix.M31 * matrix.M22) * invDet; result.M32 = (matrix.M31 * matrix.M12 - matrix.M11 * matrix.M32) * invDet; return true; } /// <summary> /// Linearly interpolates from matrix1 to matrix2, based on the third parameter. /// </summary> /// <param name="matrix1">The first source matrix.</param> /// <param name="matrix2">The second source matrix.</param> /// <param name="amount">The relative weighting of matrix2.</param> /// <returns>The interpolated matrix.</returns> public static Matrix3x2 Lerp(Matrix3x2 matrix1, Matrix3x2 matrix2, float amount) { Matrix3x2 result; // First row result.M11 = matrix1.M11 + (matrix2.M11 - matrix1.M11) * amount; result.M12 = matrix1.M12 + (matrix2.M12 - matrix1.M12) * amount; // Second row result.M21 = matrix1.M21 + (matrix2.M21 - matrix1.M21) * amount; result.M22 = matrix1.M22 + (matrix2.M22 - matrix1.M22) * amount; // Third row result.M31 = matrix1.M31 + (matrix2.M31 - matrix1.M31) * amount; result.M32 = matrix1.M32 + (matrix2.M32 - matrix1.M32) * amount; return result; } /// <summary> /// Negates the given matrix by multiplying all values by -1. /// </summary> /// <param name="value">The source matrix.</param> /// <returns>The negated matrix.</returns> public static Matrix3x2 Negate(Matrix3x2 value) { Matrix3x2 result; result.M11 = -value.M11; result.M12 = -value.M12; result.M21 = -value.M21; result.M22 = -value.M22; result.M31 = -value.M31; result.M32 = -value.M32; return result; } /// <summary> /// Adds each matrix element in value1 with its corresponding element in value2. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The matrix containing the summed values.</returns> public static Matrix3x2 Add(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result; result.M11 = value1.M11 + value2.M11; result.M12 = value1.M12 + value2.M12; result.M21 = value1.M21 + value2.M21; result.M22 = value1.M22 + value2.M22; result.M31 = value1.M31 + value2.M31; result.M32 = value1.M32 + value2.M32; return result; } /// <summary> /// Subtracts each matrix element in value2 from its corresponding element in value1. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The matrix containing the resulting values.</returns> public static Matrix3x2 Subtract(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result; result.M11 = value1.M11 - value2.M11; result.M12 = value1.M12 - value2.M12; result.M21 = value1.M21 - value2.M21; result.M22 = value1.M22 - value2.M22; result.M31 = value1.M31 - value2.M31; result.M32 = value1.M32 - value2.M32; return result; } /// <summary> /// Multiplies two matrices together and returns the resulting matrix. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The product matrix.</returns> public static Matrix3x2 Multiply(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result; // First row result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21; result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22; // Second row result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21; result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22; // Third row result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31; result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32; return result; } /// <summary> /// Scales all elements in a matrix by the given scalar factor. /// </summary> /// <param name="value1">The source matrix.</param> /// <param name="value2">The scaling value to use.</param> /// <returns>The resulting matrix.</returns> public static Matrix3x2 Multiply(Matrix3x2 value1, float value2) { Matrix3x2 result; result.M11 = value1.M11 * value2; result.M12 = value1.M12 * value2; result.M21 = value1.M21 * value2; result.M22 = value1.M22 * value2; result.M31 = value1.M31 * value2; result.M32 = value1.M32 * value2; return result; } /// <summary> /// Negates the given matrix by multiplying all values by -1. /// </summary> /// <param name="value">The source matrix.</param> /// <returns>The negated matrix.</returns> public static Matrix3x2 operator -(Matrix3x2 value) { Matrix3x2 m; m.M11 = -value.M11; m.M12 = -value.M12; m.M21 = -value.M21; m.M22 = -value.M22; m.M31 = -value.M31; m.M32 = -value.M32; return m; } /// <summary> /// Adds each matrix element in value1 with its corresponding element in value2. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The matrix containing the summed values.</returns> public static Matrix3x2 operator +(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 m; m.M11 = value1.M11 + value2.M11; m.M12 = value1.M12 + value2.M12; m.M21 = value1.M21 + value2.M21; m.M22 = value1.M22 + value2.M22; m.M31 = value1.M31 + value2.M31; m.M32 = value1.M32 + value2.M32; return m; } /// <summary> /// Subtracts each matrix element in value2 from its corresponding element in value1. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The matrix containing the resulting values.</returns> public static Matrix3x2 operator -(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 m; m.M11 = value1.M11 - value2.M11; m.M12 = value1.M12 - value2.M12; m.M21 = value1.M21 - value2.M21; m.M22 = value1.M22 - value2.M22; m.M31 = value1.M31 - value2.M31; m.M32 = value1.M32 - value2.M32; return m; } /// <summary> /// Multiplies two matrices together and returns the resulting matrix. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The product matrix.</returns> public static Matrix3x2 operator *(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 m; // First row m.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21; m.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22; // Second row m.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21; m.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22; // Third row m.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31; m.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32; return m; } /// <summary> /// Scales all elements in a matrix by the given scalar factor. /// </summary> /// <param name="value1">The source matrix.</param> /// <param name="value2">The scaling value to use.</param> /// <returns>The resulting matrix.</returns> public static Matrix3x2 operator *(Matrix3x2 value1, float value2) { Matrix3x2 m; m.M11 = value1.M11 * value2; m.M12 = value1.M12 * value2; m.M21 = value1.M21 * value2; m.M22 = value1.M22 * value2; m.M31 = value1.M31 * value2; m.M32 = value1.M32 * value2; return m; } /// <summary> /// Returns a boolean indicating whether the given matrices are equal. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>True if the matrices are equal; False otherwise.</returns> public static bool operator ==(Matrix3x2 value1, Matrix3x2 value2) { return (value1.M11 == value2.M11 && value1.M22 == value2.M22 && // Check diagonal element first for early out. value1.M12 == value2.M12 && value1.M21 == value2.M21 && value1.M31 == value2.M31 && value1.M32 == value2.M32); } /// <summary> /// Returns a boolean indicating whether the given matrices are not equal. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>True if the matrices are not equal; False if they are equal.</returns> public static bool operator !=(Matrix3x2 value1, Matrix3x2 value2) { return (value1.M11 != value2.M11 || value1.M12 != value2.M12 || value1.M21 != value2.M21 || value1.M22 != value2.M22 || value1.M31 != value2.M31 || value1.M32 != value2.M32); } /// <summary> /// Returns a boolean indicating whether the matrix is equal to the other given matrix. /// </summary> /// <param name="other">The other matrix to test equality against.</param> /// <returns>True if this matrix is equal to other; False otherwise.</returns> public bool Equals(Matrix3x2 other) { return (M11 == other.M11 && M22 == other.M22 && // Check diagonal element first for early out. M12 == other.M12 && M21 == other.M21 && M31 == other.M31 && M32 == other.M32); } /// <summary> /// Returns a boolean indicating whether the given Object is equal to this matrix instance. /// </summary> /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this matrix; False otherwise.</returns> public override bool Equals(object obj) { if (obj is Matrix3x2) { return Equals((Matrix3x2)obj); } return false; } /// <summary> /// Returns a String representing this matrix instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() { CultureInfo ci = CultureInfo.CurrentCulture; return String.Format(ci, "{{ {{M11:{0} M12:{1}}} {{M21:{2} M22:{3}}} {{M31:{4} M32:{5}}} }}", M11.ToString(ci), M12.ToString(ci), M21.ToString(ci), M22.ToString(ci), M31.ToString(ci), M32.ToString(ci)); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { return M11.GetHashCode() + M12.GetHashCode() + M21.GetHashCode() + M22.GetHashCode() + M31.GetHashCode() + M32.GetHashCode(); } } }
using System; using System.Linq; using Ductus.FluentDocker.Commands; using Ductus.FluentDocker.Extensions; using Ductus.FluentDocker.Services; using Ductus.FluentDocker.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Ductus.FluentDocker.Tests.ServiceTests { [TestClass] public sealed class NetworkServiceTests { private static IHostService _host; private static bool _createdHost; [ClassInitialize] public static void Initialize(TestContext ctx) { var hosts = new Hosts().Discover(); _host = hosts.FirstOrDefault(x => x.IsNative) ?? hosts.FirstOrDefault(x => x.Name == "default"); if (null != _host && _host.State != ServiceRunningState.Running) { _host.Start(); _host.Host.LinuxMode(_host.Certificates); return; } if (null == _host && hosts.Count > 0) _host = hosts.First(); if (null == _host) { if (_createdHost) throw new Exception("Failed to initialize the test class, tried to create a docker host but failed"); var res = "test-machine".Create(1024, 20000, 1); Assert.AreEqual(true, res.Success); var start = "test-machine".Start(); Assert.AreEqual(true, start.Success); _createdHost = true; Initialize(ctx); } } [ClassCleanup] public static void TearDown() { if (_createdHost) "test-machine".Delete(true /*force*/); } [TestMethod] public void DiscoverNetworksShallWork() { var networks = _host.GetNetworks(); Assert.IsTrue(networks.Count > 0); Assert.IsTrue(networks.Count(x => x.Name == "bridge") == 1); Assert.IsTrue(networks.Count(x => x.Name == "host") == 1); } [TestMethod] public void NetworkIsDeletedWhenDisposedAndFlagIsSet() { using (var nw = _host.CreateNetwork("unit-test-network", removeOnDispose: true)) { Assert.IsTrue(nw.Id.Length > 0); Assert.AreEqual("unit-test-network", nw.Name); } var networks = _host.GetNetworks(); Assert.IsTrue(networks.Count(x => x.Name == "unit-test-network") == 0); } [TestMethod] public void AttachWithAliasShallWorkWithIContainerService() { using (var nw = _host.CreateNetwork("unit-test-network", removeOnDispose: true)) { var alias = "hello"; var testerImageName = "hello-world-tester"; var helloContainerBuilder = new Builders.Builder().UseContainer() .UseImage("crccheck/hello-world"); var testerImageBuilder = new Builders.Builder().DefineImage(testerImageName) .From("alpine") .Run( "apk add curl" ) .Command( "curl", $"http://{alias}:8000" ); var testerContainerBuilder = new Builders.Builder().UseContainer() .UseNetwork(nw) .UseImage(testerImageName); using (var helloContainer = helloContainerBuilder.Build()) using (var testerImage = testerImageBuilder.Build()) using (var testerContainer = testerContainerBuilder.Build()) { helloContainer.Start(); nw.Attach(helloContainer, true, alias); testerContainer.Start(); var logs = string.Join( "\n", testerContainer.DockerHost.Logs(testerContainer.Id).ReadToEnd()); Assert.IsTrue(logs.IndexOf("Hello World") >= 0); } } } [TestMethod] public void AttachWithAliasShallWorkWithContainerId() { using (var nw = _host.CreateNetwork("unit-test-network", removeOnDispose: true)) { var alias = "hello"; var testerImageName = "hello-world-tester"; var helloContainerBuilder = new Builders.Builder().UseContainer() .UseImage("crccheck/hello-world"); var testerImageBuilder = new Builders.Builder().DefineImage(testerImageName) .From("alpine") .Run( "apk add curl" ) .Command( "curl", $"http://{alias}:8000" ); var testerContainerBuilder = new Builders.Builder().UseContainer() .UseNetwork(nw) .UseImage(testerImageName); using (var helloContainer = helloContainerBuilder.Build()) using (var testerImage = testerImageBuilder.Build()) using (var testerContainer = testerContainerBuilder.Build()) { helloContainer.Start(); nw.Attach(helloContainer.Id, true, alias); testerContainer.Start(); var logs = string.Join( "\n", testerContainer.DockerHost.Logs(testerContainer.Id).ReadToEnd()); Assert.IsTrue(logs.IndexOf("Hello World") >= 0); } } } [TestMethod] public void UseNetworkWithAliasShallWorkWithINetworkService() { using (var nw = _host.CreateNetwork("unit-test-network", removeOnDispose: true)) { var alias = "hello"; var testerImageName = "hello-world-tester"; var helloContainerBuilder = new Builders.Builder().UseContainer() .UseImage("crccheck/hello-world") .UseNetworksWithAlias(alias, nw); var testerImageBuilder = new Builders.Builder().DefineImage(testerImageName) .From("alpine") .Run( "apk add curl" ) .Command( "curl", $"http://{alias}:8000" ); var testerContainerBuilder = new Builders.Builder().UseContainer() .UseNetwork(nw) .UseImage(testerImageName); using (var helloContainer = helloContainerBuilder.Build()) using (var testerImage = testerImageBuilder.Build()) using (var testerContainer = testerContainerBuilder.Build()) { helloContainer.Start(); testerContainer.Start(); var logs = string.Join( "\n", testerContainer.DockerHost.Logs(testerContainer.Id).ReadToEnd()); Assert.IsTrue(logs.IndexOf("Hello World") >= 0); } } } [TestMethod] public void UseNetworkWithAliasShallWorkWithString() { using (var nw = _host.CreateNetwork("unit-test-network", removeOnDispose: true)) { var alias = "hello"; var testerImageName = "hello-world-tester"; var helloContainerBuilder = new Builders.Builder().UseContainer() .UseImage("crccheck/hello-world") .UseNetworksWithAlias(alias, nw.Name); var testerImageBuilder = new Builders.Builder().DefineImage(testerImageName) .From("alpine") .Run( "apk add curl" ) .Command( "curl", $"http://{alias}:8000" ); var testerContainerBuilder = new Builders.Builder().UseContainer() .UseNetwork(nw) .UseImage(testerImageName); using (var helloContainer = helloContainerBuilder.Build()) using (var testerImage = testerImageBuilder.Build()) using (var testerContainer = testerContainerBuilder.Build()) { helloContainer.Start(); testerContainer.Start(); var logs = string.Join( "\n", testerContainer.DockerHost.Logs(testerContainer.Id).ReadToEnd()); Assert.IsTrue(logs.IndexOf("Hello World") >= 0); } } } [TestMethod] public void MultipleUseNetworkWithAliasShallWorkWithINetworkService() { using (var nw1 = _host.CreateNetwork("unit-test-network-1", removeOnDispose: true)) using (var nw2 = _host.CreateNetwork("unit-test-network-2", removeOnDispose: true)) { var alias1 = "first-hello"; var alias2 = "second-hello"; var testerImageAlias1Name = $"hello-world-tester-{alias1}"; var testerImageAlias2Name = $"hello-world-tester-{alias2}"; var helloContainerBuilder = new Builders.Builder().UseContainer() .UseImage("crccheck/hello-world") .UseNetworksWithAlias(alias1, nw1) .UseNetworksWithAlias(alias2, nw2); var testerImageAlias1Builder = new Builders.Builder().DefineImage(testerImageAlias1Name) .From("alpine") .Run( "apk add curl" ) .Command( "curl", $"http://{alias1}:8000" ); var testerImageAlias2Builder = new Builders.Builder().DefineImage(testerImageAlias2Name) .From("alpine") .Run( "apk add curl" ) .Command( "curl", $"http://{alias2}:8000" ); var testerContainerAlias1Builder = new Builders.Builder().UseContainer() .UseNetwork(nw1) .UseImage(testerImageAlias1Name); var testerContainerAlias2Builder = new Builders.Builder().UseContainer() .UseNetwork(nw2) .UseImage(testerImageAlias2Name); using (var helloContainer = helloContainerBuilder.Build()) using (var testerImageAlias1Image = testerImageAlias1Builder.Build()) using (var testerImageAlias2Image = testerImageAlias2Builder.Build()) using (var testerContainerAlias1 = testerContainerAlias1Builder.Build()) using (var testerContainerAlias2 = testerContainerAlias2Builder.Build()) { helloContainer.Start(); testerContainerAlias1.Start(); var logsAlias1 = string.Join( "\n", testerContainerAlias1.DockerHost.Logs(testerContainerAlias1.Id).ReadToEnd()); Assert.IsTrue(logsAlias1.IndexOf("Hello World") >= 0); testerContainerAlias2.Start(); var logsAlias2 = string.Join( "\n", testerContainerAlias2.DockerHost.Logs(testerContainerAlias2.Id).ReadToEnd()); Assert.IsTrue(logsAlias2.IndexOf("Hello World") >= 0); } } } [TestMethod] public void MultipleUseNetworkWithAliasShallWorkWithString() { using (var nw1 = _host.CreateNetwork("unit-test-network-1", removeOnDispose: true)) using (var nw2 = _host.CreateNetwork("unit-test-network-2", removeOnDispose: true)) { var alias1 = "first-hello"; var alias2 = "second-hello"; var testerImageAlias1Name = $"hello-world-tester-{alias1}"; var testerImageAlias2Name = $"hello-world-tester-{alias2}"; var helloContainerBuilder = new Builders.Builder().UseContainer() .UseImage("crccheck/hello-world") .UseNetworksWithAlias(alias1, nw1.Name) .UseNetworksWithAlias(alias2, nw2.Name); var testerImageAlias1Builder = new Builders.Builder().DefineImage(testerImageAlias1Name) .From("alpine") .Run( "apk add curl" ) .Command( "curl", $"http://{alias1}:8000" ); var testerImageAlias2Builder = new Builders.Builder().DefineImage(testerImageAlias2Name) .From("alpine") .Run( "apk add curl" ) .Command( "curl", $"http://{alias2}:8000" ); var testerContainerAlias1Builder = new Builders.Builder().UseContainer() .UseNetwork(nw1) .UseImage(testerImageAlias1Name); var testerContainerAlias2Builder = new Builders.Builder().UseContainer() .UseNetwork(nw2) .UseImage(testerImageAlias2Name); using (var helloContainer = helloContainerBuilder.Build()) using (var testerImageAlias1Image = testerImageAlias1Builder.Build()) using (var testerImageAlias2Image = testerImageAlias2Builder.Build()) using (var testerContainerAlias1 = testerContainerAlias1Builder.Build()) using (var testerContainerAlias2 = testerContainerAlias2Builder.Build()) { helloContainer.Start(); testerContainerAlias1.Start(); var logsAlias1 = string.Join( "\n", testerContainerAlias1.DockerHost.Logs(testerContainerAlias1.Id).ReadToEnd()); Assert.IsTrue(logsAlias1.IndexOf("Hello World") >= 0); testerContainerAlias2.Start(); var logsAlias2 = string.Join( "\n", testerContainerAlias2.DockerHost.Logs(testerContainerAlias2.Id).ReadToEnd()); Assert.IsTrue(logsAlias2.IndexOf("Hello World") >= 0); } } } [TestMethod] public void MultipleUseNetworkWithSameAliasShallWorkWithINetworkService() { using (var nw1 = _host.CreateNetwork("unit-test-network-1", removeOnDispose: true)) using (var nw2 = _host.CreateNetwork("unit-test-network-2", removeOnDispose: true)) { var alias = "hello"; var testerImageName = $"hello-world-tester"; var helloContainerBuilder = new Builders.Builder().UseContainer() .UseImage("crccheck/hello-world") .UseNetworksWithAlias(alias, nw1, nw2); var testerImageBuilder = new Builders.Builder().DefineImage(testerImageName) .From("alpine") .Run( "apk add curl" ) .Command( "curl", $"http://{alias}:8000" ); var testerContainerBuilder1 = new Builders.Builder().UseContainer() .UseNetwork(nw1) .UseImage(testerImageName); var testerContainerBuilder2 = new Builders.Builder().UseContainer() .UseNetwork(nw2) .UseImage(testerImageName); using (var helloContainer = helloContainerBuilder.Build()) using (var testerImage = testerImageBuilder.Build()) using (var testerContainer1 = testerContainerBuilder1.Build()) using (var testerContainer2 = testerContainerBuilder2.Build()) { helloContainer.Start(); testerContainer1.Start(); var logsAlias1 = string.Join( "\n", testerContainer1.DockerHost.Logs(testerContainer1.Id).ReadToEnd()); Assert.IsTrue(logsAlias1.IndexOf("Hello World") >= 0); testerContainer2.Start(); var logsAlias2 = string.Join( "\n", testerContainer2.DockerHost.Logs(testerContainer2.Id).ReadToEnd()); Assert.IsTrue(logsAlias2.IndexOf("Hello World") >= 0); } } } [TestMethod] public void MultipleUseNetworkWithSameAliasShallWorkWithString() { using (var nw1 = _host.CreateNetwork("unit-test-network-1", removeOnDispose: true)) using (var nw2 = _host.CreateNetwork("unit-test-network-2", removeOnDispose: true)) { var alias = "hello"; var testerImageName = $"hello-world-tester"; var helloContainerBuilder = new Builders.Builder().UseContainer() .UseImage("crccheck/hello-world") .UseNetworksWithAlias(alias, nw1.Name, nw2.Name); var testerImageBuilder = new Builders.Builder().DefineImage(testerImageName) .From("alpine") .Run( "apk add curl" ) .Command( "curl", $"http://{alias}:8000" ); var testerContainerBuilder1 = new Builders.Builder().UseContainer() .UseNetwork(nw1) .UseImage(testerImageName); var testerContainerBuilder2 = new Builders.Builder().UseContainer() .UseNetwork(nw2) .UseImage(testerImageName); using (var helloContainer = helloContainerBuilder.Build()) using (var testerImage = testerImageBuilder.Build()) using (var testerContainer1 = testerContainerBuilder1.Build()) using (var testerContainer2 = testerContainerBuilder2.Build()) { helloContainer.Start(); testerContainer1.Start(); var logsAlias1 = string.Join( "\n", testerContainer1.DockerHost.Logs(testerContainer1.Id).ReadToEnd()); Assert.IsTrue(logsAlias1.IndexOf("Hello World") >= 0); testerContainer2.Start(); var logsAlias2 = string.Join( "\n", testerContainer2.DockerHost.Logs(testerContainer2.Id).ReadToEnd()); Assert.IsTrue(logsAlias2.IndexOf("Hello World") >= 0); } } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Collections; using System.Diagnostics; using System.Runtime.Serialization; using System.Reflection; using IServiceProvider = System.IServiceProvider; using Microsoft.VisualStudio.OLE.Interop; using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.FSharp.ProjectSystem; using Microsoft.VisualStudio.FSharp.LanguageService; namespace Microsoft.VisualStudio.FSharp.ProjectSystem.Automation { /// <summary> /// This can navigate a collection object only (partial implementation of ProjectItems interface) /// </summary> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ComVisible(true), CLSCompliant(false)] public class OANavigableProjectItems : EnvDTE.ProjectItems { private OAProject project; private IList<EnvDTE.ProjectItem> items; private HierarchyNode nodeWithItems; /// <summary> /// Defines an public list of project items /// </summary> public IList<EnvDTE.ProjectItem> Items { get { return this.items; } } /// <summary> /// Defines a relationship to the associated project. /// </summary> public OAProject Project { get { return this.project; } } /// <summary> /// Defines the node that contains the items /// </summary> public HierarchyNode NodeWithItems { get { return this.nodeWithItems; } } /// <summary> /// Constructor. /// </summary> /// <param name="project">The associated project.</param> /// <param name="nodeWithItems">The node that defines the items.</param> internal OANavigableProjectItems(OAProject project, HierarchyNode nodeWithItems) { this.project = project; this.nodeWithItems = nodeWithItems; this.items = this.GetListOfProjectItems(); } /// <summary> /// Constructor. /// </summary> /// <param name="project">The associated project.</param> /// <param name="items">A list of items that will make up the items defined by this object.</param> /// <param name="nodeWithItems">The node that defines the items.</param> internal OANavigableProjectItems(OAProject project, IList<EnvDTE.ProjectItem> items, HierarchyNode nodeWithItems) { this.items = items; this.project = project; this.nodeWithItems = nodeWithItems; } /// <summary> /// Gets a value indicating the number of objects in the collection. /// </summary> public virtual int Count { get { return items.Count; } } public virtual object Parent { get { return this.nodeWithItems.GetAutomationObject(); } } /// <summary> /// Gets an enumeration indicating the type of object. /// </summary> public virtual string Kind { get { // TODO: Add OAProjectItems.Kind getter implementation return null; } } /// <summary> /// Gets the top-level extensibility object. /// </summary> public virtual EnvDTE.DTE DTE { get { return (EnvDTE.DTE)this.project.DTE; } } /// <summary> /// Gets the project hosting the project item or items. /// </summary> public virtual EnvDTE.Project ContainingProject { get { return this.project; } } /// <summary> /// Adds one or more ProjectItem objects from a directory to the ProjectItems collection. /// </summary> /// <param name="directory">The directory from which to add the project item.</param> /// <returns>A ProjectItem object.</returns> public virtual EnvDTE.ProjectItem AddFromDirectory(string directory) { throw new NotImplementedException(); } /// <summary> /// Creates a new project item from an existing item template file and adds it to the project. /// </summary> /// <param name="fileName">The full path and file name of the template project file.</param> /// <param name="name">The file name to use for the new project item.</param> /// <returns>A ProjectItem object. </returns> public virtual EnvDTE.ProjectItem AddFromTemplate(string fileName, string name) { throw new NotImplementedException(); } /// <summary> /// Creates a new folder in Solution Explorer. /// </summary> /// <param name="name">The name of the folder node in Solution Explorer.</param> /// <param name="kind">The type of folder to add. The available values are based on vsProjectItemsKindConstants and vsProjectItemKindConstants</param> /// <returns>A ProjectItem object.</returns> public virtual EnvDTE.ProjectItem AddFolder(string name, string kind) { throw new NotImplementedException(); } /// <summary> /// Copies a source file and adds it to the project. /// </summary> /// <param name="filePath">The path and file name of the project item to be added.</param> /// <returns>A ProjectItem object. </returns> public virtual EnvDTE.ProjectItem AddFromFileCopy(string filePath) { throw new NotImplementedException(); } /// <summary> /// Adds a project item from a file that is installed in a project directory structure. /// </summary> /// <param name="fileName">The file name of the item to add as a project item. </param> /// <returns>A ProjectItem object. </returns> public virtual EnvDTE.ProjectItem AddFromFile(string fileName) { throw new NotImplementedException(); } /// <summary> /// Get Project Item from index /// </summary> /// <param name="index">Either index by number (1-based) or by name can be used to get the item</param> /// <returns>Project Item. null is return if invalid index is specified</returns> public virtual EnvDTE.ProjectItem Item(object index) { if (index is int) { int realIndex = (int)index - 1; if (realIndex >= 0 && realIndex < this.items.Count) { return (EnvDTE.ProjectItem)items[realIndex]; } return null; } else if (index is string) { string name = (string)index; foreach (EnvDTE.ProjectItem item in items) { if (String.Compare(item.Name, name, StringComparison.OrdinalIgnoreCase) == 0) { return item; } } } return null; } public virtual IEnumerator GetEnumerator() { if (this.items == null) { yield return null; yield break; } int count = items.Count; for (int i = 0; i < count; i++) { yield return items[i]; } } /// <summary> /// Retrives a list of items associated with the current node. /// </summary> /// <returns>A List of project items</returns> public IList<EnvDTE.ProjectItem> GetListOfProjectItems() { return UIThread.DoOnUIThread(delegate() { List<EnvDTE.ProjectItem> list = new List<EnvDTE.ProjectItem>(); for (HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling) { if (!(child is ReferenceContainerNode)) // skip 'references' node when navigating over project items, to behave more like C#/VB { EnvDTE.ProjectItem item = child.GetAutomationObject() as EnvDTE.ProjectItem; if (null != item) { list.Add(item); } } } return list; }); } } }
// // System.Data.SqlTypes.SqlInt64 // // Author: // Tim Coleman <tim@timcoleman.com> // Ville Palo <vi64pa@koti.soon.fi> // // (C) Copyright 2002 Tim Coleman // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; namespace System.Data.SqlTypes { public struct SqlInt64 : INullable, IComparable { #region Fields long value; private bool notNull; public static readonly SqlInt64 MaxValue = new SqlInt64 (9223372036854775807); public static readonly SqlInt64 MinValue = new SqlInt64 (-9223372036854775808); public static readonly SqlInt64 Null; public static readonly SqlInt64 Zero = new SqlInt64 (0); #endregion #region Constructors public SqlInt64 (long value) { this.value = value; notNull = true; } #endregion #region Properties public bool IsNull { get { return !notNull; } } public long Value { get { if (this.IsNull) throw new SqlNullValueException (); else return value; } } #endregion #region Methods public static SqlInt64 Add (SqlInt64 x, SqlInt64 y) { return (x + y); } public static SqlInt64 BitwiseAnd (SqlInt64 x, SqlInt64 y) { return (x & y); } public static SqlInt64 BitwiseOr (SqlInt64 x, SqlInt64 y) { return (x | y); } public int CompareTo (object value) { if (value == null) return 1; else if (!(value is SqlInt64)) throw new ArgumentException (Locale.GetText ("Value is not a System.Data.SqlTypes.SqlInt64")); return CompareSqlInt64 ((SqlInt64) value); } #if NET_2_0 public int CompareTo (SqlInt64 value) { return CompareSqlInt64 ((SqlInt64) value); } #endif private int CompareSqlInt64 (SqlInt64 value) { if (value.IsNull) return 1; else return this.value.CompareTo (value.Value); } public static SqlInt64 Divide (SqlInt64 x, SqlInt64 y) { return (x / y); } public override bool Equals (object value) { if (!(value is SqlInt64)) return false; else if (this.IsNull && ((SqlInt64)value).IsNull) return true; else if (((SqlInt64)value).IsNull) return false; else return (bool) (this == (SqlInt64)value); } public static SqlBoolean Equals (SqlInt64 x, SqlInt64 y) { return (x == y); } public override int GetHashCode () { return (int)(value & 0xffffffff) ^ (int)(value >> 32); } public static SqlBoolean GreaterThan (SqlInt64 x, SqlInt64 y) { return (x > y); } public static SqlBoolean GreaterThanOrEqual (SqlInt64 x, SqlInt64 y) { return (x >= y); } public static SqlBoolean LessThan (SqlInt64 x, SqlInt64 y) { return (x < y); } public static SqlBoolean LessThanOrEqual (SqlInt64 x, SqlInt64 y) { return (x <= y); } public static SqlInt64 Mod (SqlInt64 x, SqlInt64 y) { return (x % y); } #if NET_2_0 public static SqlInt64 Modulus (SqlInt64 x, SqlInt64 y) { return (x % y); } #endif public static SqlInt64 Multiply (SqlInt64 x, SqlInt64 y) { return (x * y); } public static SqlBoolean NotEquals (SqlInt64 x, SqlInt64 y) { return (x != y); } public static SqlInt64 OnesComplement (SqlInt64 x) { if (x.IsNull) return Null; return ~x; } public static SqlInt64 Parse (string s) { checked { return new SqlInt64 (Int64.Parse (s)); } } public static SqlInt64 Subtract (SqlInt64 x, SqlInt64 y) { return (x - y); } public SqlBoolean ToSqlBoolean () { return ((SqlBoolean)this); } public SqlByte ToSqlByte () { return ((SqlByte)this); } public SqlDecimal ToSqlDecimal () { return ((SqlDecimal)this); } public SqlDouble ToSqlDouble () { return ((SqlDouble)this); } public SqlInt16 ToSqlInt16 () { return ((SqlInt16)this); } public SqlInt32 ToSqlInt32 () { return ((SqlInt32)this); } public SqlMoney ToSqlMoney () { return ((SqlMoney)this); } public SqlSingle ToSqlSingle () { return ((SqlSingle)this); } public SqlString ToSqlString () { return ((SqlString)this); } public override string ToString () { if (this.IsNull) return "Null"; return value.ToString (); } public static SqlInt64 Xor (SqlInt64 x, SqlInt64 y) { return (x ^ y); } public static SqlInt64 operator + (SqlInt64 x, SqlInt64 y) { checked { return new SqlInt64 (x.Value + y.Value); } } public static SqlInt64 operator & (SqlInt64 x, SqlInt64 y) { return new SqlInt64 (x.value & y.Value); } public static SqlInt64 operator | (SqlInt64 x, SqlInt64 y) { return new SqlInt64 (x.value | y.Value); } public static SqlInt64 operator / (SqlInt64 x, SqlInt64 y) { checked { return new SqlInt64 (x.Value / y.Value); } } public static SqlBoolean operator == (SqlInt64 x, SqlInt64 y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (x.Value == y.Value); } public static SqlInt64 operator ^ (SqlInt64 x, SqlInt64 y) { return new SqlInt64 (x.Value ^ y.Value); } public static SqlBoolean operator > (SqlInt64 x, SqlInt64 y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (x.Value > y.Value); } public static SqlBoolean operator >= (SqlInt64 x, SqlInt64 y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (x.Value >= y.Value); } public static SqlBoolean operator != (SqlInt64 x, SqlInt64 y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (!(x.Value == y.Value)); } public static SqlBoolean operator < (SqlInt64 x, SqlInt64 y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (x.Value < y.Value); } public static SqlBoolean operator <= (SqlInt64 x, SqlInt64 y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (x.Value <= y.Value); } public static SqlInt64 operator % (SqlInt64 x, SqlInt64 y) { return new SqlInt64(x.Value % y.Value); } public static SqlInt64 operator * (SqlInt64 x, SqlInt64 y) { checked { return new SqlInt64 (x.Value * y.Value); } } public static SqlInt64 operator ~ (SqlInt64 x) { if (x.IsNull) return SqlInt64.Null; return new SqlInt64 (~(x.Value)); } public static SqlInt64 operator - (SqlInt64 x, SqlInt64 y) { checked { return new SqlInt64 (x.Value - y.Value); } } public static SqlInt64 operator - (SqlInt64 n) { return new SqlInt64 (-(n.Value)); } public static explicit operator SqlInt64 (SqlBoolean x) { if (x.IsNull) return SqlInt64.Null; else return new SqlInt64 ((long)x.ByteValue); } public static explicit operator SqlInt64 (SqlDecimal x) { checked { if (x.IsNull) return SqlInt64.Null; else return new SqlInt64 ((long)x.Value); } } public static explicit operator SqlInt64 (SqlDouble x) { if (x.IsNull) return SqlInt64.Null; else { checked { return new SqlInt64 ((long)x.Value); } } } public static explicit operator long (SqlInt64 x) { return x.Value; } public static explicit operator SqlInt64 (SqlMoney x) { checked { if (x.IsNull) return SqlInt64.Null; else return new SqlInt64 ((long) Math.Round (x.Value)); } } public static explicit operator SqlInt64 (SqlSingle x) { if (x.IsNull) return SqlInt64.Null; else { checked { return new SqlInt64 ((long)x.Value); } } } public static explicit operator SqlInt64 (SqlString x) { checked { return SqlInt64.Parse (x.Value); } } public static implicit operator SqlInt64 (long x) { return new SqlInt64 (x); } public static implicit operator SqlInt64 (SqlByte x) { if (x.IsNull) return SqlInt64.Null; else return new SqlInt64 ((long)x.Value); } public static implicit operator SqlInt64 (SqlInt16 x) { if (x.IsNull) return SqlInt64.Null; else return new SqlInt64 ((long)x.Value); } public static implicit operator SqlInt64 (SqlInt32 x) { if (x.IsNull) return SqlInt64.Null; else return new SqlInt64 ((long)x.Value); } #endregion } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.IO; namespace NLog.UnitTests.Config { using NLog.Conditions; using NLog.Config; using NLog.LayoutRenderers; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; using System; using System.Globalization; using System.Text; using Xunit; public class TargetConfigurationTests : NLogTestBase { [Fact] public void SimpleTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='d' type='Debug' layout='${message}' /> </targets> </nlog>"); DebugTarget t = c.FindTargetByName("d") as DebugTarget; Assert.NotNull(t); Assert.Equal("d", t.Name); SimpleLayout l = t.Layout as SimpleLayout; Assert.Equal("${message}", l.Text); Assert.NotNull(t.Layout); Assert.Single(l.Renderers); Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]); } [Fact] public void SimpleElementSyntaxTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target type='Debug'> <name>d</name> <layout>${message}</layout> </target> </targets> </nlog>"); DebugTarget t = c.FindTargetByName("d") as DebugTarget; Assert.NotNull(t); Assert.Equal("d", t.Name); SimpleLayout l = t.Layout as SimpleLayout; Assert.Equal("${message}", l.Text); Assert.NotNull(t.Layout); Assert.Single(l.Renderers); Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]); } [Fact] public void NestedXmlConfigElementTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <extensions> <add type='" + typeof(StructuredDebugTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='StructuredDebugTarget'> <name>structuredTgt</name> <layout>${message}</layout> <config platform='any'> <parameter name='param1' /> </config> </target> </targets> </nlog>"); var t = c.FindTargetByName("structuredTgt") as StructuredDebugTarget; Assert.NotNull(t); Assert.Equal("any", t.Config.Platform); Assert.Equal("param1", t.Config.Parameter.Name); } [Fact] public void ArrayParameterTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target type='MethodCall' name='mct'> <parameter name='p1' layout='${message}' /> <parameter name='p2' layout='${level}' /> <parameter name='p3' layout='${logger}' /> </target> </targets> </nlog>"); var t = c.FindTargetByName("mct") as MethodCallTarget; Assert.NotNull(t); Assert.Equal(3, t.Parameters.Count); Assert.Equal("p1", t.Parameters[0].Name); Assert.Equal("'${message}'", t.Parameters[0].Layout.ToString()); Assert.Equal("p2", t.Parameters[1].Name); Assert.Equal("'${level}'", t.Parameters[1].Layout.ToString()); Assert.Equal("p3", t.Parameters[2].Name); Assert.Equal("'${logger}'", t.Parameters[2].Layout.ToString()); } [Fact] public void ArrayElementParameterTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target type='MethodCall' name='mct'> <parameter> <name>p1</name> <layout>${message}</layout> </parameter> <parameter> <name>p2</name> <layout type='CsvLayout'> <column name='x' layout='${message}' /> <column name='y' layout='${level}' /> </layout> </parameter> <parameter> <name>p3</name> <layout>${logger}</layout> </parameter> </target> </targets> </nlog>"); var t = c.FindTargetByName("mct") as MethodCallTarget; Assert.NotNull(t); Assert.Equal(3, t.Parameters.Count); Assert.Equal("p1", t.Parameters[0].Name); Assert.Equal("'${message}'", t.Parameters[0].Layout.ToString()); Assert.Equal("p2", t.Parameters[1].Name); CsvLayout csvLayout = t.Parameters[1].Layout as CsvLayout; Assert.NotNull(csvLayout); Assert.Equal(2, csvLayout.Columns.Count); Assert.Equal("x", csvLayout.Columns[0].Name); Assert.Equal("y", csvLayout.Columns[1].Name); Assert.Equal("p3", t.Parameters[2].Name); Assert.Equal("'${logger}'", t.Parameters[2].Layout.ToString()); } [Fact] public void SimpleTest2() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='d' type='Debug' layout='${message} ${level}' /> </targets> </nlog>"); DebugTarget t = c.FindTargetByName("d") as DebugTarget; Assert.NotNull(t); Assert.Equal("d", t.Name); SimpleLayout l = t.Layout as SimpleLayout; Assert.Equal("${message} ${level}", l.Text); Assert.NotNull(l); Assert.Equal(3, l.Renderers.Count); Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]); Assert.IsType<LiteralLayoutRenderer>(l.Renderers[1]); Assert.IsType<LevelLayoutRenderer>(l.Renderers[2]); Assert.Equal(" ", ((LiteralLayoutRenderer)l.Renderers[1]).Text); } [Fact] public void WrapperTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <wrapper-target name='b' type='BufferingWrapper' bufferSize='19'> <wrapper name='a' type='AsyncWrapper'> <target name='c' type='Debug' layout='${message}' /> </wrapper> </wrapper-target> </targets> </nlog>"); Assert.NotNull(c.FindTargetByName("a")); Assert.NotNull(c.FindTargetByName("b")); Assert.NotNull(c.FindTargetByName("c")); Assert.IsType<BufferingTargetWrapper>(c.FindTargetByName("b")); Assert.IsType<AsyncTargetWrapper>(c.FindTargetByName("a")); Assert.IsType<DebugTarget>(c.FindTargetByName("c")); BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper; AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper; DebugTarget dt = c.FindTargetByName("c") as DebugTarget; Assert.Same(atw, btw.WrappedTarget); Assert.Same(dt, atw.WrappedTarget); Assert.Equal(19, btw.BufferSize); } [Fact] public void WrapperRefTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='c' type='Debug' layout='${message}' /> <wrapper name='a' type='AsyncWrapper'> <target-ref name='c' /> </wrapper> <wrapper-target name='b' type='BufferingWrapper' bufferSize='19'> <wrapper-target-ref name='a' /> </wrapper-target> </targets> </nlog>"); Assert.NotNull(c.FindTargetByName("a")); Assert.NotNull(c.FindTargetByName("b")); Assert.NotNull(c.FindTargetByName("c")); Assert.IsType<BufferingTargetWrapper>(c.FindTargetByName("b")); Assert.IsType<AsyncTargetWrapper>(c.FindTargetByName("a")); Assert.IsType<DebugTarget>(c.FindTargetByName("c")); BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper; AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper; DebugTarget dt = c.FindTargetByName("c") as DebugTarget; Assert.Same(atw, btw.WrappedTarget); Assert.Same(dt, atw.WrappedTarget); Assert.Equal(19, btw.BufferSize); } [Fact] public void CompoundTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <compound-target name='rr' type='RoundRobinGroup'> <target name='d1' type='Debug' layout='${message}1' /> <target name='d2' type='Debug' layout='${message}2' /> <target name='d3' type='Debug' layout='${message}3' /> <target name='d4' type='Debug' layout='${message}4' /> </compound-target> </targets> </nlog>"); Assert.NotNull(c.FindTargetByName("rr")); Assert.NotNull(c.FindTargetByName("d1")); Assert.NotNull(c.FindTargetByName("d2")); Assert.NotNull(c.FindTargetByName("d3")); Assert.NotNull(c.FindTargetByName("d4")); Assert.IsType<RoundRobinGroupTarget>(c.FindTargetByName("rr")); Assert.IsType<DebugTarget>(c.FindTargetByName("d1")); Assert.IsType<DebugTarget>(c.FindTargetByName("d2")); Assert.IsType<DebugTarget>(c.FindTargetByName("d3")); Assert.IsType<DebugTarget>(c.FindTargetByName("d4")); RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget; DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget; DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget; DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget; DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget; Assert.Equal(4, rr.Targets.Count); Assert.Same(d1, rr.Targets[0]); Assert.Same(d2, rr.Targets[1]); Assert.Same(d3, rr.Targets[2]); Assert.Same(d4, rr.Targets[3]); Assert.Equal("${message}1", ((SimpleLayout)d1.Layout).Text); Assert.Equal("${message}2", ((SimpleLayout)d2.Layout).Text); Assert.Equal("${message}3", ((SimpleLayout)d3.Layout).Text); Assert.Equal("${message}4", ((SimpleLayout)d4.Layout).Text); } [Fact] public void CompoundRefTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='d1' type='Debug' layout='${message}1' /> <target name='d2' type='Debug' layout='${message}2' /> <target name='d3' type='Debug' layout='${message}3' /> <target name='d4' type='Debug' layout='${message}4' /> <compound-target name='rr' type='RoundRobinGroup'> <target-ref name='d1' /> <target-ref name='d2' /> <target-ref name='d3' /> <target-ref name='d4' /> </compound-target> </targets> </nlog>"); Assert.NotNull(c.FindTargetByName("rr")); Assert.NotNull(c.FindTargetByName("d1")); Assert.NotNull(c.FindTargetByName("d2")); Assert.NotNull(c.FindTargetByName("d3")); Assert.NotNull(c.FindTargetByName("d4")); Assert.IsType<RoundRobinGroupTarget>(c.FindTargetByName("rr")); Assert.IsType<DebugTarget>(c.FindTargetByName("d1")); Assert.IsType<DebugTarget>(c.FindTargetByName("d2")); Assert.IsType<DebugTarget>(c.FindTargetByName("d3")); Assert.IsType<DebugTarget>(c.FindTargetByName("d4")); RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget; DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget; DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget; DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget; DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget; Assert.Equal(4, rr.Targets.Count); Assert.Same(d1, rr.Targets[0]); Assert.Same(d2, rr.Targets[1]); Assert.Same(d3, rr.Targets[2]); Assert.Same(d4, rr.Targets[3]); Assert.Equal("${message}1", ((SimpleLayout)d1.Layout).Text); Assert.Equal("${message}2", ((SimpleLayout)d2.Layout).Text); Assert.Equal("${message}3", ((SimpleLayout)d3.Layout).Text); Assert.Equal("${message}4", ((SimpleLayout)d4.Layout).Text); } [Fact] public void AsyncWrappersTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets async='true'> <target type='Debug' name='d' /> <target type='Debug' name='d2' /> </targets> </nlog>"); var t = c.FindTargetByName("d") as AsyncTargetWrapper; Assert.NotNull(t); Assert.Equal("d", t.Name); var wrappedTarget = t.WrappedTarget as DebugTarget; Assert.NotNull(wrappedTarget); Assert.Equal("d_wrapped", wrappedTarget.Name); t = c.FindTargetByName("d2") as AsyncTargetWrapper; Assert.NotNull(t); Assert.Equal("d2", t.Name); wrappedTarget = t.WrappedTarget as DebugTarget; Assert.NotNull(wrappedTarget); Assert.Equal("d2_wrapped", wrappedTarget.Name); } [Fact] public void DefaultTargetParametersTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <default-target-parameters type='Debug' layout='x${message}x' /> <target type='Debug' name='d' /> <target type='Debug' name='d2' /> </targets> </nlog>"); var t = c.FindTargetByName("d") as DebugTarget; Assert.NotNull(t); Assert.Equal("'x${message}x'", t.Layout.ToString()); t = c.FindTargetByName("d2") as DebugTarget; Assert.NotNull(t); Assert.Equal("'x${message}x'", t.Layout.ToString()); } [Fact] public void DefaultTargetParametersOnWrappedTargetTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <default-target-parameters type='Debug' layout='x${message}x' /> <target type='BufferingWrapper' name='buf1'> <target type='Debug' name='d1' /> </target> </targets> </nlog>"); var wrap = c.FindTargetByName("buf1") as BufferingTargetWrapper; Assert.NotNull(wrap); Assert.NotNull(wrap.WrappedTarget); var t = wrap.WrappedTarget as DebugTarget; Assert.NotNull(t); Assert.Equal("'x${message}x'", t.Layout.ToString()); } [Fact] public void DefaultWrapperTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <default-wrapper type='BufferingWrapper'> <wrapper type='RetryingWrapper' /> </default-wrapper> <target type='Debug' name='d' layout='${level}' /> <target type='Debug' name='d2' layout='${level}' /> </targets> </nlog>"); var bufferingTargetWrapper = c.FindTargetByName("d") as BufferingTargetWrapper; Assert.NotNull(bufferingTargetWrapper); var retryingTargetWrapper = bufferingTargetWrapper.WrappedTarget as RetryingTargetWrapper; Assert.NotNull(retryingTargetWrapper); Assert.Null(retryingTargetWrapper.Name); var debugTarget = retryingTargetWrapper.WrappedTarget as DebugTarget; Assert.NotNull(debugTarget); Assert.Equal("d_wrapped", debugTarget.Name); Assert.Equal("'${level}'", debugTarget.Layout.ToString()); } [Fact] public void DontThrowExceptionWhenArchiveEverySetByDefaultParameters() { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <default-target-parameters type='File' concurrentWrites='true' keepFileOpen='true' maxArchiveFiles='5' archiveNumbering='Rolling' archiveEvery='Day' /> <target fileName='" + Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + @".log' name = 'file' type = 'File' layout = '${message}' /> </targets> <rules> <logger name='*' writeTo='file'/> </rules> </nlog> "); LogManager.Configuration = configuration; LogManager.GetLogger("TestLogger").Info("DefaultFileTargetParametersTests.DontThrowExceptionWhenArchiveEverySetByDefaultParameters is true"); } [Fact] public void DontThrowExceptionsWhenMissingRequiredParameters() { using (new NoThrowNLogExceptions()) { var configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target type='bufferingwrapper' name='mytarget'> <target type='unknowntargettype' name='badtarget' /> </target> </targets> <rules> <logger name='*' writeTo='mytarget'/> </rules> </nlog> "); LogManager.Configuration = configuration; LogManager.GetLogger(nameof(DontThrowExceptionsWhenMissingRequiredParameters)).Info("Test"); LogManager.Configuration = null; } } [Fact] public void DataTypesTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <extensions> <add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='MyTarget' name='myTarget' byteProperty='42' int16Property='42' int32Property='42' int64Property='42000000000' stringProperty='foobar' boolProperty='true' doubleProperty='3.14159' floatProperty='3.14159' enumProperty='Value3' flagsEnumProperty='Value1,Value3' encodingProperty='utf-8' cultureProperty='en-US' typeProperty='System.Int32' layoutProperty='${level}' conditionProperty=""starts-with(message, 'x')"" uriProperty='http://nlog-project.org' lineEndingModeProperty='default' /> </targets> </nlog>"); var myTarget = c.FindTargetByName("myTarget") as MyTarget; Assert.NotNull(myTarget); Assert.Equal((byte)42, myTarget.ByteProperty); Assert.Equal((short)42, myTarget.Int16Property); Assert.Equal(42, myTarget.Int32Property); Assert.Equal(42000000000L, myTarget.Int64Property); Assert.Equal("foobar", myTarget.StringProperty); Assert.True(myTarget.BoolProperty); Assert.Equal(3.14159, myTarget.DoubleProperty); Assert.Equal(3.14159f, myTarget.FloatProperty); Assert.Equal(MyEnum.Value3, myTarget.EnumProperty); Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty); Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty); Assert.Equal("en-US", myTarget.CultureProperty.Name); Assert.Equal(typeof(int), myTarget.TypeProperty); Assert.Equal("'${level}'", myTarget.LayoutProperty.ToString()); Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString()); Assert.Equal(new Uri("http://nlog-project.org"), myTarget.UriProperty); Assert.Equal(LineEndingMode.Default, myTarget.LineEndingModeProperty); } [Fact] public void NullableDataTypesTest() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <extensions> <add type='" + typeof(MyNullableTarget).AssemblyQualifiedName + @"' /> </extensions> <targets> <target type='MyNullableTarget' name='myTarget' byteProperty='42' int16Property='42' int32Property='42' int64Property='42000000000' stringProperty='foobar' boolProperty='true' doubleProperty='3.14159' floatProperty='3.14159' enumProperty='Value3' flagsEnumProperty='Value1,Value3' encodingProperty='utf-8' cultureProperty='en-US' typeProperty='System.Int32' layoutProperty='${level}' conditionProperty=""starts-with(message, 'x')"" /> </targets> </nlog>"); var myTarget = c.FindTargetByName("myTarget") as MyNullableTarget; Assert.NotNull(myTarget); Assert.Equal((byte)42, myTarget.ByteProperty); Assert.Equal((short)42, myTarget.Int16Property); Assert.Equal(42, myTarget.Int32Property); Assert.Equal(42000000000L, myTarget.Int64Property); Assert.Equal("foobar", myTarget.StringProperty); Assert.True(myTarget.BoolProperty); Assert.Equal(3.14159, myTarget.DoubleProperty); Assert.Equal(3.14159f, myTarget.FloatProperty); Assert.Equal(MyEnum.Value3, myTarget.EnumProperty); Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty); Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty); Assert.Equal("en-US", myTarget.CultureProperty.Name); Assert.Equal(typeof(int), myTarget.TypeProperty); Assert.Equal("'${level}'", myTarget.LayoutProperty.ToString()); Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString()); } [Target("MyTarget")] public class MyTarget : Target { public byte ByteProperty { get; set; } public short Int16Property { get; set; } public int Int32Property { get; set; } public long Int64Property { get; set; } public string StringProperty { get; set; } public bool BoolProperty { get; set; } public double DoubleProperty { get; set; } public float FloatProperty { get; set; } public MyEnum EnumProperty { get; set; } public MyFlagsEnum FlagsEnumProperty { get; set; } public Encoding EncodingProperty { get; set; } public CultureInfo CultureProperty { get; set; } public Type TypeProperty { get; set; } public Layout LayoutProperty { get; set; } public ConditionExpression ConditionProperty { get; set; } public Uri UriProperty { get; set; } public LineEndingMode LineEndingModeProperty { get; set; } public MyTarget() : base() { } public MyTarget(string name) : this() { Name = name; } } [Target("MyNullableTarget")] public class MyNullableTarget : Target { public byte? ByteProperty { get; set; } public short? Int16Property { get; set; } public int? Int32Property { get; set; } public long? Int64Property { get; set; } public string StringProperty { get; set; } public bool? BoolProperty { get; set; } public double? DoubleProperty { get; set; } public float? FloatProperty { get; set; } public MyEnum? EnumProperty { get; set; } public MyFlagsEnum? FlagsEnumProperty { get; set; } public Encoding EncodingProperty { get; set; } public CultureInfo CultureProperty { get; set; } public Type TypeProperty { get; set; } public Layout LayoutProperty { get; set; } public ConditionExpression ConditionProperty { get; set; } public MyNullableTarget() : base() { } public MyNullableTarget(string name) : this() { Name = name; } } public enum MyEnum { Value1, Value2, Value3, } [Flags] public enum MyFlagsEnum { Value1 = 1, Value2 = 2, Value3 = 4, } [Target("StructuredDebugTarget")] public class StructuredDebugTarget : TargetWithLayout { public StructuredDebugTargetConfig Config { get; set; } public StructuredDebugTarget() { Config = new StructuredDebugTargetConfig(); } } public class StructuredDebugTargetConfig { public string Platform { get; set; } public StructuredDebugTargetParameter Parameter { get; set; } public StructuredDebugTargetConfig() { Parameter = new StructuredDebugTargetParameter(); } } public class StructuredDebugTargetParameter { public string Name { get; set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Threading; namespace System.Net { internal sealed unsafe class HttpResponseStreamAsyncResult : LazyAsyncResult { private readonly ThreadPoolBoundHandle _boundHandle; internal NativeOverlapped* _pOverlapped; private Interop.HttpApi.HTTP_DATA_CHUNK[] _dataChunks; internal bool _sentHeaders; private static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(Callback); internal ushort dataChunkCount { get { if (_dataChunks == null) { return 0; } else { return (ushort)_dataChunks.Length; } } } internal Interop.HttpApi.HTTP_DATA_CHUNK* pDataChunks { get { if (_dataChunks == null) { return null; } else { return (Interop.HttpApi.HTTP_DATA_CHUNK*)(Marshal.UnsafeAddrOfPinnedArrayElement(_dataChunks, 0)); } } } internal HttpResponseStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback) : base(asyncObject, userState, callback) { } private static byte[] GetChunkHeader(int size, out int offset) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, $"size:{size}"); uint Mask = 0xf0000000; byte[] Header = new byte[10]; int i; offset = -1; // // Loop through the size, looking at each nibble. If it's not 0 // convert it to hex. Save the index of the first non-zero // byte. // for (i = 0; i < 8; i++, size <<= 4) { // // offset == -1 means that we haven't found a non-zero nibble // yet. If we haven't found one, and the current one is zero, // don't do anything. // if (offset == -1) { if ((size & Mask) == 0) { continue; } } // // Either we have a non-zero nibble or we're no longer skipping // leading zeros. Convert this nibble to ASCII and save it. // uint Temp = (uint)size >> 28; if (Temp < 10) { Header[i] = (byte)(Temp + '0'); } else { Header[i] = (byte)((Temp - 10) + 'A'); } // // If we haven't found a non-zero nibble yet, we've found one // now, so remember that. // if (offset == -1) { offset = i; } } Header[8] = (byte)'\r'; Header[9] = (byte)'\n'; if (NetEventSource.IsEnabled) NetEventSource.Exit(null); return Header; } private const string CRLF = "\r\n"; private static readonly byte[] s_CRLFArray = new byte[] { (byte)'\r', (byte)'\n' }; internal HttpResponseStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback, byte[] buffer, int offset, int size, bool chunked, bool sentHeaders, ThreadPoolBoundHandle boundHandle) : base(asyncObject, userState, callback) { _boundHandle = boundHandle; _sentHeaders = sentHeaders; if (size == 0) { _dataChunks = null; _pOverlapped = boundHandle.AllocateNativeOverlapped(s_IOCallback, state: this, pinData: null); } else { _dataChunks = new Interop.HttpApi.HTTP_DATA_CHUNK[chunked ? 3 : 1]; if (NetEventSource.IsEnabled) NetEventSource.Info(this, "m_pOverlapped:0x" + ((IntPtr)_pOverlapped).ToString("x8")); object[] objectsToPin = new object[1 + _dataChunks.Length]; objectsToPin[_dataChunks.Length] = _dataChunks; int chunkHeaderOffset = 0; byte[] chunkHeaderBuffer = null; if (chunked) { chunkHeaderBuffer = GetChunkHeader(size, out chunkHeaderOffset); _dataChunks[0] = new Interop.HttpApi.HTTP_DATA_CHUNK(); _dataChunks[0].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory; _dataChunks[0].BufferLength = (uint)(chunkHeaderBuffer.Length - chunkHeaderOffset); objectsToPin[0] = chunkHeaderBuffer; _dataChunks[1] = new Interop.HttpApi.HTTP_DATA_CHUNK(); _dataChunks[1].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory; _dataChunks[1].BufferLength = (uint)size; objectsToPin[1] = buffer; _dataChunks[2] = new Interop.HttpApi.HTTP_DATA_CHUNK(); _dataChunks[2].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory; _dataChunks[2].BufferLength = (uint)s_CRLFArray.Length; objectsToPin[2] = s_CRLFArray; } else { _dataChunks[0] = new Interop.HttpApi.HTTP_DATA_CHUNK(); _dataChunks[0].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory; _dataChunks[0].BufferLength = (uint)size; objectsToPin[0] = buffer; } // This call will pin needed memory _pOverlapped = boundHandle.AllocateNativeOverlapped(s_IOCallback, state: this, pinData: objectsToPin); if (chunked) { _dataChunks[0].pBuffer = (byte*)(Marshal.UnsafeAddrOfPinnedArrayElement(chunkHeaderBuffer, chunkHeaderOffset)); _dataChunks[1].pBuffer = (byte*)(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset)); _dataChunks[2].pBuffer = (byte*)(Marshal.UnsafeAddrOfPinnedArrayElement(s_CRLFArray, 0)); } else { _dataChunks[0].pBuffer = (byte*)(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset)); } } } internal void IOCompleted(uint errorCode, uint numBytes) { IOCompleted(this, errorCode, numBytes); } private static void IOCompleted(HttpResponseStreamAsyncResult asyncResult, uint errorCode, uint numBytes) { if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes}"); object result = null; try { if (errorCode != Interop.HttpApi.ERROR_SUCCESS && errorCode != Interop.HttpApi.ERROR_HANDLE_EOF) { asyncResult.ErrorCode = (int)errorCode; result = new HttpListenerException((int)errorCode); } else { // if we sent headers and body together, numBytes will be the total, but we need to only account for the data if (asyncResult._dataChunks == null) { result = (uint)0; if (NetEventSource.IsEnabled) { NetEventSource.DumpBuffer(null, IntPtr.Zero, 0); } } else { result = asyncResult._dataChunks.Length == 1 ? asyncResult._dataChunks[0].BufferLength : 0; if (NetEventSource.IsEnabled) { for (int i = 0; i < asyncResult._dataChunks.Length; i++) { NetEventSource.DumpBuffer(null, (IntPtr)asyncResult._dataChunks[0].pBuffer, (int)asyncResult._dataChunks[0].BufferLength); } } } } if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Calling Complete()"); } catch (Exception e) { result = e; } asyncResult.InvokeCallback(result); } private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { object state = ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); HttpResponseStreamAsyncResult asyncResult = state as HttpResponseStreamAsyncResult; if (NetEventSource.IsEnabled) NetEventSource.Info(null, "errorCode:0x" + errorCode.ToString("x8") + " numBytes:" + numBytes + " nativeOverlapped:0x" + ((IntPtr)nativeOverlapped).ToString("x8")); IOCompleted(asyncResult, errorCode, numBytes); } // Will be called from the base class upon InvokeCallback() protected override void Cleanup() { base.Cleanup(); if (_pOverlapped != null) { _boundHandle.FreeNativeOverlapped(_pOverlapped); } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// BackupOperationResultsOperations operations. /// </summary> internal partial class BackupOperationResultsOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IBackupOperationResultsOperations { /// <summary> /// Initializes a new instance of the BackupOperationResultsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal BackupOperationResultsOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Provides the status of the delete operations such as deleting backed up /// item. Once the operation has started, the status code in the response /// would be Accepted. It will continue to be in this state till it reaches /// completion. On successful completion, the status code will be OK. This /// method expects OperationID as an argument. OperationID is part of the /// Location header of the operation response. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='operationId'> /// OperationID which represents the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string operationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (vaultName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (operationId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "operationId"); } string apiVersion = "2016-06-01"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("operationId", operationId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupOperationResults/{operationId}").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.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) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Collections; using System.Collections.Specialized; using System.DirectoryServices.Interop; using System.ComponentModel; using INTPTR_INTPTRCAST = System.IntPtr; namespace System.DirectoryServices { /// <devdoc> /// Performs queries against the Active Directory hierarchy. /// </devdoc> public class DirectorySearcher : Component { private DirectoryEntry _searchRoot; private string _filter = defaultFilter; private StringCollection _propertiesToLoad; private bool _disposed = false; private static readonly TimeSpan s_minusOneSecond = new TimeSpan(0, 0, -1); // search preference variables private SearchScope _scope = System.DirectoryServices.SearchScope.Subtree; private bool _scopeSpecified = false; private int _sizeLimit = 0; private TimeSpan _serverTimeLimit = s_minusOneSecond; private TimeSpan _clientTimeout = s_minusOneSecond; private int _pageSize = 0; private TimeSpan _serverPageTimeLimit = s_minusOneSecond; private ReferralChasingOption _referralChasing = ReferralChasingOption.External; private SortOption _sort = new SortOption(); private bool _cacheResults = true; private bool _cacheResultsSpecified = false; private bool _rootEntryAllocated = false; // true: if a temporary entry inside Searcher has been created private string _assertDefaultNamingContext = null; private string _attributeScopeQuery = ""; private bool _attributeScopeQuerySpecified = false; private DereferenceAlias _derefAlias = DereferenceAlias.Never; private SecurityMasks _securityMask = SecurityMasks.None; private ExtendedDN _extendedDN = ExtendedDN.None; private DirectorySynchronization _sync = null; internal bool directorySynchronizationSpecified = false; private DirectoryVirtualListView _vlv = null; internal bool directoryVirtualListViewSpecified = false; internal SearchResultCollection searchResult = null; private const string defaultFilter = "(objectClass=*)"; /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, /// <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default values. /// </devdoc> public DirectorySearcher() : this(null, defaultFilter, null, System.DirectoryServices.SearchScope.Subtree) { _scopeSpecified = false; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with /// <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default /// values, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> set to the given value. /// </devdoc> public DirectorySearcher(DirectoryEntry searchRoot) : this(searchRoot, defaultFilter, null, System.DirectoryServices.SearchScope.Subtree) { _scopeSpecified = false; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with /// <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default /// values, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> set to the respective given values. /// </devdoc> public DirectorySearcher(DirectoryEntry searchRoot, string filter) : this(searchRoot, filter, null, System.DirectoryServices.SearchScope.Subtree) { _scopeSpecified = false; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with /// <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to its default /// value, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, and <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> set to the respective given values. /// </devdoc> public DirectorySearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad) : this(searchRoot, filter, propertiesToLoad, System.DirectoryServices.SearchScope.Subtree) { _scopeSpecified = false; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, /// <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default /// values, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> set to the given value. /// </devdoc> public DirectorySearcher(string filter) : this(null, filter, null, System.DirectoryServices.SearchScope.Subtree) { _scopeSpecified = false; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> /// and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default /// values, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> and <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> set to the respective given values. /// </devdoc> public DirectorySearcher(string filter, string[] propertiesToLoad) : this(null, filter, propertiesToLoad, System.DirectoryServices.SearchScope.Subtree) { _scopeSpecified = false; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> set to its default /// value, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to the respective given values.</para> /// </devdoc> public DirectorySearcher(string filter, string[] propertiesToLoad, SearchScope scope) : this(null, filter, propertiesToLoad, scope) { } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with the <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> properties set to the given /// values. /// </devdoc> public DirectorySearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad, SearchScope scope) { _searchRoot = searchRoot; _filter = filter; if (propertiesToLoad != null) PropertiesToLoad.AddRange(propertiesToLoad); this.SearchScope = scope; } protected override void Dispose(bool disposing) { // safe to call while finalizing or disposing // if (!_disposed && disposing) { if (_rootEntryAllocated) _searchRoot.Dispose(); _rootEntryAllocated = false; _disposed = true; } base.Dispose(disposing); } /// <devdoc> /// Gets or sets a value indicating whether the result should be cached on the /// client machine. /// </devdoc> [DefaultValue(true)] public bool CacheResults { get => _cacheResults; set { // user explicitly set CacheResults to true and also want VLV if (directoryVirtualListViewSpecified == true && value == true) throw new ArgumentException(SR.DSBadCacheResultsVLV); _cacheResults = value; _cacheResultsSpecified = true; } } /// <devdoc> /// Gets or sets the maximum amount of time that the client waits for /// the server to return results. If the server does not respond within this time, /// the search is aborted, and no results are returned.</para> /// </devdoc> public TimeSpan ClientTimeout { get => _clientTimeout; set { // prevent integer overflow if (value.TotalSeconds > Int32.MaxValue) { throw new ArgumentException(SR.TimespanExceedMax, "value"); } _clientTimeout = value; } } /// <devdoc> /// Gets or sets a value indicating whether the search should retrieve only the names of requested /// properties or the names and values of requested properties.</para> /// </devdoc> [DefaultValue(false)] public bool PropertyNamesOnly { get; set; } /// <devdoc> /// Gets or sets the Lightweight Directory Access Protocol (LDAP) filter string format. /// </devdoc> [ DefaultValue(defaultFilter), // CoreFXPort - Remove design support // TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign) ] public string Filter { get => _filter; set { if (value == null || value.Length == 0) value = defaultFilter; _filter = value; } } /// <devdoc> /// Gets or sets the page size in a paged search. /// </devdoc> [DefaultValue(0)] public int PageSize { get => _pageSize; set { if (value < 0) throw new ArgumentException(SR.DSBadPageSize); // specify non-zero pagesize explicitly and also want dirsync if (directorySynchronizationSpecified == true && value != 0) throw new ArgumentException(SR.DSBadPageSizeDirsync); _pageSize = value; } } /// <devdoc> /// Gets the set of properties retrieved during the search. By default, the <see cref='System.DirectoryServices.DirectoryEntry.Path'/> /// and <see cref='System.DirectoryServices.DirectoryEntry.Name'/> properties are retrieved. /// </devdoc> public StringCollection PropertiesToLoad { get { if (_propertiesToLoad == null) { _propertiesToLoad = new StringCollection(); } return _propertiesToLoad; } } /// <devdoc> /// Gets or sets how referrals are chased. /// </devdoc> [DefaultValue(ReferralChasingOption.External)] public ReferralChasingOption ReferralChasing { get => _referralChasing; set { if (value != ReferralChasingOption.None && value != ReferralChasingOption.Subordinate && value != ReferralChasingOption.External && value != ReferralChasingOption.All) throw new InvalidEnumArgumentException("value", (int)value, typeof(ReferralChasingOption)); _referralChasing = value; } } /// <devdoc> /// Gets or sets the scope of the search that should be observed by the server. /// </devdoc> [DefaultValue(SearchScope.Subtree)] public SearchScope SearchScope { get => _scope; set { if (value < SearchScope.Base || value > SearchScope.Subtree) throw new InvalidEnumArgumentException("value", (int)value, typeof(SearchScope)); // user explicitly set SearchScope to something other than Base and also want to do ASQ, it is not supported if (_attributeScopeQuerySpecified == true && value != SearchScope.Base) { throw new ArgumentException(SR.DSBadASQSearchScope); } _scope = value; _scopeSpecified = true; } } /// <devdoc> /// Gets or sets the time limit that the server should observe to search a page of results (as /// opposed to the time limit for the entire search). /// </devdoc> public TimeSpan ServerPageTimeLimit { get => _serverPageTimeLimit; set { // prevent integer overflow if (value.TotalSeconds > Int32.MaxValue) { throw new ArgumentException(SR.TimespanExceedMax, "value"); } _serverPageTimeLimit = value; } } /// <devdoc> /// Gets or sets the maximum amount of time the server spends searching. If the /// time limit is reached, only entries found up to that point will be returned. /// </devdoc> public TimeSpan ServerTimeLimit { get => _serverTimeLimit; set { // prevent integer overflow if (value.TotalSeconds > Int32.MaxValue) { throw new ArgumentException(SR.TimespanExceedMax, "value"); } _serverTimeLimit = value; } } /// <devdoc> /// Gets or sets the maximum number of objects that the /// server should return in a search. /// </devdoc> [DefaultValue(0)] public int SizeLimit { get => _sizeLimit; set { if (value < 0) throw new ArgumentException(SR.DSBadSizeLimit); _sizeLimit = value; } } /// <devdoc> /// Gets or sets the node in the Active Directory hierarchy /// at which the search will start. /// </devdoc> [DefaultValue(null)] public DirectoryEntry SearchRoot { get { if (_searchRoot == null && !DesignMode) { // get the default naming context. This should be the default root for the search. DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE", true, null, null, AuthenticationTypes.Secure); //SECREVIEW: Searching the root of the DS will demand browse permissions // on "*" or "LDAP://RootDSE". string defaultNamingContext = (string)rootDSE.Properties["defaultNamingContext"][0]; rootDSE.Dispose(); _searchRoot = new DirectoryEntry("LDAP://" + defaultNamingContext, true, null, null, AuthenticationTypes.Secure); _rootEntryAllocated = true; _assertDefaultNamingContext = "LDAP://" + defaultNamingContext; } return _searchRoot; } set { if (_rootEntryAllocated) _searchRoot.Dispose(); _rootEntryAllocated = false; _assertDefaultNamingContext = null; _searchRoot = value; } } /// <devdoc> /// Gets the property on which the results should be sorted. /// </devdoc> [TypeConverter(typeof(ExpandableObjectConverter))] public SortOption Sort { get => _sort; set => _sort = value ?? throw new ArgumentNullException(nameof(value)); } /// <devdoc> /// Gets or sets a value indicating whether searches should be carried out in an asynchronous /// way. /// </devdoc> [DefaultValue(false)] public bool Asynchronous { get; set; } /// <devdoc> /// Gets or sets a value indicateing whether the search should also return deleted objects that match the search /// filter. /// </devdoc> [DefaultValue(false)] public bool Tombstone { get; set; } /// <devdoc> /// Gets or sets an attribute name to indicate that an attribute-scoped query search should be /// performed. /// </devdoc> [ DefaultValue(""), // CoreFXPort - Remove design support // TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign) ] public string AttributeScopeQuery { get => _attributeScopeQuery; set { if (value == null) value = ""; // user explicitly set AttributeScopeQuery and value is not null or empty string if (value.Length != 0) { if (_scopeSpecified == true && SearchScope != SearchScope.Base) { throw new ArgumentException(SR.DSBadASQSearchScope); } // if user did not explicitly set search scope _scope = SearchScope.Base; _attributeScopeQuerySpecified = true; } else // user explicitly sets the value to default one and doesn't want to do asq { _attributeScopeQuerySpecified = false; } _attributeScopeQuery = value; } } /// <devdoc> /// Gets or sets a value to indicate how the aliases of found objects are to be /// resolved. /// </devdoc> [DefaultValue(DereferenceAlias.Never)] public DereferenceAlias DerefAlias { get => _derefAlias; set { if (value < DereferenceAlias.Never || value > DereferenceAlias.Always) throw new InvalidEnumArgumentException("value", (int)value, typeof(DereferenceAlias)); _derefAlias = value; } } /// <devdoc> /// Gets or sets a value to indicate the search should return security access information for the specified /// attributes. /// </devdoc> [DefaultValue(SecurityMasks.None)] public SecurityMasks SecurityMasks { get => _securityMask; set { // make sure the behavior is consistent with native ADSI if (value > (SecurityMasks.None | SecurityMasks.Owner | SecurityMasks.Group | SecurityMasks.Dacl | SecurityMasks.Sacl)) throw new InvalidEnumArgumentException("value", (int)value, typeof(SecurityMasks)); _securityMask = value; } } /// <devdoc> /// Gets or sets a value to return extended DNs according to the requested /// format. /// </devdoc> [DefaultValue(ExtendedDN.None)] public ExtendedDN ExtendedDN { get => _extendedDN; set { if (value < ExtendedDN.None || value > ExtendedDN.Standard) throw new InvalidEnumArgumentException("value", (int)value, typeof(ExtendedDN)); _extendedDN = value; } } /// <devdoc> /// Gets or sets a value to indicate a directory synchronization search, which returns all changes since a specified /// state. /// </devdoc> [DefaultValue(null)] public DirectorySynchronization DirectorySynchronization { get { // if user specifies dirsync search preference and search is executed if (directorySynchronizationSpecified && searchResult != null) { _sync.ResetDirectorySynchronizationCookie(searchResult.DirsyncCookie); } return _sync; } set { // specify non-zero pagesize explicitly and also want dirsync if (value != null) { if (PageSize != 0) throw new ArgumentException(SR.DSBadPageSizeDirsync); directorySynchronizationSpecified = true; } else // user explicitly sets the value to default one and doesn't want to do dirsync { directorySynchronizationSpecified = false; } _sync = value; } } /// <devdoc> /// Gets or sets a value to indicate the search should use the LDAP virtual list view (VLV) /// control. /// </devdoc> [DefaultValue(null)] public DirectoryVirtualListView VirtualListView { get { // if user specifies dirsync search preference and search is executed if (directoryVirtualListViewSpecified && searchResult != null) { DirectoryVirtualListView tempval = searchResult.VLVResponse; _vlv.Offset = tempval.Offset; _vlv.ApproximateTotal = tempval.ApproximateTotal; _vlv.DirectoryVirtualListViewContext = tempval.DirectoryVirtualListViewContext; if (_vlv.ApproximateTotal != 0) _vlv.TargetPercentage = (int)((double)_vlv.Offset / _vlv.ApproximateTotal * 100); else _vlv.TargetPercentage = 0; } return _vlv; } set { // if user explicitly set CacheResults to true and also want to set VLV if (value != null) { if (_cacheResultsSpecified == true && CacheResults == true) throw new ArgumentException(SR.DSBadCacheResultsVLV); directoryVirtualListViewSpecified = true; // if user does not explicit specify cache results to true and also do vlv, then cache results is default to false _cacheResults = false; } else // user explicitly sets the value to default one and doesn't want to do vlv { directoryVirtualListViewSpecified = false; } _vlv = value; } } /// <devdoc> /// Executes the search and returns only the first entry that is found. /// </devdoc> public SearchResult FindOne() { DirectorySynchronization tempsync = null; DirectoryVirtualListView tempvlv = null; SearchResult resultEntry = null; SearchResultCollection results = FindAll(false); try { foreach (SearchResult entry in results) { // need to get the dirsync cookie if (directorySynchronizationSpecified) tempsync = DirectorySynchronization; // need to get the vlv response if (directoryVirtualListViewSpecified) tempvlv = VirtualListView; resultEntry = entry; break; } } finally { searchResult = null; // still need to properly release the resource results.Dispose(); } return resultEntry; } /// <devdoc> /// Executes the search and returns a collection of the entries that are found. /// </devdoc> public SearchResultCollection FindAll() => FindAll(true); private SearchResultCollection FindAll(bool findMoreThanOne) { searchResult = null; DirectoryEntry clonedRoot = null; if (_assertDefaultNamingContext == null) { clonedRoot = SearchRoot.CloneBrowsable(); } else { clonedRoot = SearchRoot.CloneBrowsable(); } UnsafeNativeMethods.IAds adsObject = clonedRoot.AdsObject; if (!(adsObject is UnsafeNativeMethods.IDirectorySearch)) throw new NotSupportedException(SR.Format(SR.DSSearchUnsupported , SearchRoot.Path)); // this is a little bit hacky, but we need to perform a bind here, so we make sure the LDAP connection that we hold has more than // one reference count, one by SearchResultCollection object, one by DirectorySearcher object. In this way, when user calls // Dispose on SearchResultCollection, the connection is still there instead of reference count dropping to zero and being closed. // It is especially important for virtuallistview case, in order to reuse the vlv response, the search must be performed on the same ldap connection // only do it when vlv is used if (directoryVirtualListViewSpecified) { SearchRoot.Bind(true); } UnsafeNativeMethods.IDirectorySearch adsSearch = (UnsafeNativeMethods.IDirectorySearch)adsObject; SetSearchPreferences(adsSearch, findMoreThanOne); string[] properties = null; if (PropertiesToLoad.Count > 0) { if (!PropertiesToLoad.Contains("ADsPath")) { // if we don't get this property, we won't be able to return a list of DirectoryEntry objects! PropertiesToLoad.Add("ADsPath"); } properties = new string[PropertiesToLoad.Count]; PropertiesToLoad.CopyTo(properties, 0); } IntPtr resultsHandle; if (properties != null) adsSearch.ExecuteSearch(Filter, properties, properties.Length, out resultsHandle); else { adsSearch.ExecuteSearch(Filter, null, -1, out resultsHandle); properties = new string[0]; } SearchResultCollection result = new SearchResultCollection(clonedRoot, resultsHandle, properties, this); searchResult = result; return result; } private unsafe void SetSearchPreferences(UnsafeNativeMethods.IDirectorySearch adsSearch, bool findMoreThanOne) { ArrayList prefList = new ArrayList(); AdsSearchPreferenceInfo info; // search scope info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.SEARCH_SCOPE; info.vValue = new AdsValueHelper((int)SearchScope).GetStruct(); prefList.Add(info); // size limit if (_sizeLimit != 0 || !findMoreThanOne) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.SIZE_LIMIT; info.vValue = new AdsValueHelper(findMoreThanOne ? SizeLimit : 1).GetStruct(); prefList.Add(info); } // time limit if (ServerTimeLimit >= new TimeSpan(0)) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.TIME_LIMIT; info.vValue = new AdsValueHelper((int)ServerTimeLimit.TotalSeconds).GetStruct(); prefList.Add(info); } // propertyNamesOnly info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.ATTRIBTYPES_ONLY; info.vValue = new AdsValueHelper(PropertyNamesOnly).GetStruct(); prefList.Add(info); // Timeout if (ClientTimeout >= new TimeSpan(0)) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.TIMEOUT; info.vValue = new AdsValueHelper((int)ClientTimeout.TotalSeconds).GetStruct(); prefList.Add(info); } // page size if (PageSize != 0) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.PAGESIZE; info.vValue = new AdsValueHelper(PageSize).GetStruct(); prefList.Add(info); } // page time limit if (ServerPageTimeLimit >= new TimeSpan(0)) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.PAGED_TIME_LIMIT; info.vValue = new AdsValueHelper((int)ServerPageTimeLimit.TotalSeconds).GetStruct(); prefList.Add(info); } // chase referrals info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.CHASE_REFERRALS; info.vValue = new AdsValueHelper((int)ReferralChasing).GetStruct(); prefList.Add(info); // asynchronous if (Asynchronous == true) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.ASYNCHRONOUS; info.vValue = new AdsValueHelper(Asynchronous).GetStruct(); prefList.Add(info); } // tombstone if (Tombstone == true) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.TOMBSTONE; info.vValue = new AdsValueHelper(Tombstone).GetStruct(); prefList.Add(info); } // attributescopequery if (_attributeScopeQuerySpecified) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.ATTRIBUTE_QUERY; info.vValue = new AdsValueHelper(AttributeScopeQuery, AdsType.ADSTYPE_CASE_IGNORE_STRING).GetStruct(); prefList.Add(info); } // derefalias if (DerefAlias != DereferenceAlias.Never) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.DEREF_ALIASES; info.vValue = new AdsValueHelper((int)DerefAlias).GetStruct(); prefList.Add(info); } // securitymask if (SecurityMasks != SecurityMasks.None) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.SECURITY_MASK; info.vValue = new AdsValueHelper((int)SecurityMasks).GetStruct(); prefList.Add(info); } // extendeddn if (ExtendedDN != ExtendedDN.None) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.EXTENDED_DN; info.vValue = new AdsValueHelper((int)ExtendedDN).GetStruct(); prefList.Add(info); } // dirsync if (directorySynchronizationSpecified) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.DIRSYNC; info.vValue = new AdsValueHelper(DirectorySynchronization.GetDirectorySynchronizationCookie(), AdsType.ADSTYPE_PROV_SPECIFIC).GetStruct(); prefList.Add(info); if (DirectorySynchronization.Option != DirectorySynchronizationOptions.None) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.DIRSYNC_FLAG; info.vValue = new AdsValueHelper((int)DirectorySynchronization.Option).GetStruct(); prefList.Add(info); } } IntPtr ptrToFree = (IntPtr)0; IntPtr ptrVLVToFree = (IntPtr)0; IntPtr ptrVLVContexToFree = (IntPtr)0; try { // sort if (Sort.PropertyName != null && Sort.PropertyName.Length > 0) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.SORT_ON; AdsSortKey sortKey = new AdsSortKey(); sortKey.pszAttrType = Marshal.StringToCoTaskMemUni(Sort.PropertyName); ptrToFree = sortKey.pszAttrType; // so we can free it later. sortKey.pszReserved = (IntPtr)0; sortKey.fReverseOrder = (Sort.Direction == SortDirection.Descending) ? -1 : 0; byte[] sortKeyBytes = new byte[Marshal.SizeOf(sortKey)]; Marshal.Copy((INTPTR_INTPTRCAST)(&sortKey), sortKeyBytes, 0, sortKeyBytes.Length); info.vValue = new AdsValueHelper(sortKeyBytes, AdsType.ADSTYPE_PROV_SPECIFIC).GetStruct(); prefList.Add(info); } // vlv if (directoryVirtualListViewSpecified) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.VLV; AdsVLV vlvValue = new AdsVLV(); vlvValue.beforeCount = _vlv.BeforeCount; vlvValue.afterCount = _vlv.AfterCount; vlvValue.offset = _vlv.Offset; //we need to treat the empty string as null here if (_vlv.Target.Length != 0) vlvValue.target = Marshal.StringToCoTaskMemUni(_vlv.Target); else vlvValue.target = IntPtr.Zero; ptrVLVToFree = vlvValue.target; if (_vlv.DirectoryVirtualListViewContext == null) { vlvValue.contextIDlength = 0; vlvValue.contextID = (IntPtr)0; } else { vlvValue.contextIDlength = _vlv.DirectoryVirtualListViewContext._context.Length; vlvValue.contextID = Marshal.AllocCoTaskMem(vlvValue.contextIDlength); ptrVLVContexToFree = vlvValue.contextID; Marshal.Copy(_vlv.DirectoryVirtualListViewContext._context, 0, vlvValue.contextID, vlvValue.contextIDlength); } IntPtr vlvPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(AdsVLV))); byte[] vlvBytes = new byte[Marshal.SizeOf(vlvValue)]; try { Marshal.StructureToPtr(vlvValue, vlvPtr, false); Marshal.Copy(vlvPtr, vlvBytes, 0, vlvBytes.Length); } finally { Marshal.FreeHGlobal(vlvPtr); } info.vValue = new AdsValueHelper(vlvBytes, AdsType.ADSTYPE_PROV_SPECIFIC).GetStruct(); prefList.Add(info); } // cacheResults if (_cacheResultsSpecified) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.CACHE_RESULTS; info.vValue = new AdsValueHelper(CacheResults).GetStruct(); prefList.Add(info); } // // now make the call // AdsSearchPreferenceInfo[] prefs = new AdsSearchPreferenceInfo[prefList.Count]; for (int i = 0; i < prefList.Count; i++) { prefs[i] = (AdsSearchPreferenceInfo)prefList[i]; } DoSetSearchPrefs(adsSearch, prefs); } finally { if (ptrToFree != (IntPtr)0) Marshal.FreeCoTaskMem(ptrToFree); if (ptrVLVToFree != (IntPtr)0) Marshal.FreeCoTaskMem(ptrVLVToFree); if (ptrVLVContexToFree != (IntPtr)0) Marshal.FreeCoTaskMem(ptrVLVContexToFree); } } private static void DoSetSearchPrefs(UnsafeNativeMethods.IDirectorySearch adsSearch, AdsSearchPreferenceInfo[] prefs) { int structSize = Marshal.SizeOf(typeof(AdsSearchPreferenceInfo)); IntPtr ptr = Marshal.AllocHGlobal((IntPtr)(structSize * prefs.Length)); try { IntPtr tempPtr = ptr; for (int i = 0; i < prefs.Length; i++) { Marshal.StructureToPtr(prefs[i], tempPtr, false); tempPtr = IntPtr.Add(tempPtr, structSize); } adsSearch.SetSearchPreference(ptr, prefs.Length); // Check for the result status for all preferences tempPtr = ptr; for (int i = 0; i < prefs.Length; i++) { int status = Marshal.ReadInt32(tempPtr, 32); if (status != 0) { int prefIndex = prefs[i].dwSearchPref; string property = ""; switch (prefIndex) { case (int)AdsSearchPreferences.SEARCH_SCOPE: property = "SearchScope"; break; case (int)AdsSearchPreferences.SIZE_LIMIT: property = "SizeLimit"; break; case (int)AdsSearchPreferences.TIME_LIMIT: property = "ServerTimeLimit"; break; case (int)AdsSearchPreferences.ATTRIBTYPES_ONLY: property = "PropertyNamesOnly"; break; case (int)AdsSearchPreferences.TIMEOUT: property = "ClientTimeout"; break; case (int)AdsSearchPreferences.PAGESIZE: property = "PageSize"; break; case (int)AdsSearchPreferences.PAGED_TIME_LIMIT: property = "ServerPageTimeLimit"; break; case (int)AdsSearchPreferences.CHASE_REFERRALS: property = "ReferralChasing"; break; case (int)AdsSearchPreferences.SORT_ON: property = "Sort"; break; case (int)AdsSearchPreferences.CACHE_RESULTS: property = "CacheResults"; break; case (int)AdsSearchPreferences.ASYNCHRONOUS: property = "Asynchronous"; break; case (int)AdsSearchPreferences.TOMBSTONE: property = "Tombstone"; break; case (int)AdsSearchPreferences.ATTRIBUTE_QUERY: property = "AttributeScopeQuery"; break; case (int)AdsSearchPreferences.DEREF_ALIASES: property = "DerefAlias"; break; case (int)AdsSearchPreferences.SECURITY_MASK: property = "SecurityMasks"; break; case (int)AdsSearchPreferences.EXTENDED_DN: property = "ExtendedDn"; break; case (int)AdsSearchPreferences.DIRSYNC: property = "DirectorySynchronization"; break; case (int)AdsSearchPreferences.DIRSYNC_FLAG: property = "DirectorySynchronizationFlag"; break; case (int)AdsSearchPreferences.VLV: property = "VirtualListView"; break; } throw new InvalidOperationException(SR.Format(SR.DSSearchPreferencesNotAccepted , property)); } tempPtr = IntPtr.Add(tempPtr, structSize); } } finally { Marshal.FreeHGlobal(ptr); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace TeamTaskManager.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/*++ Copyright (c) 2000 Microsoft Corporation Module Name: _StreamFramer.cs Abstract: Author: Mauro Ottaviani original implementation Alexei Vopilov 20-Jul-2002 made it generic enough (still not perfect, consider IStreamFramer interface) Revision History: --*/ namespace System.Net { using System; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.ComponentModel; using System.Globalization; using System.Net; using System.Net.Sockets; internal class StreamFramer { private Stream m_Transport; private bool m_Eof; private FrameHeader m_WriteHeader = new FrameHeader(); private FrameHeader m_CurReadHeader = new FrameHeader(); private FrameHeader m_ReadVerifier = new FrameHeader(FrameHeader.IgnoreValue, FrameHeader.IgnoreValue, FrameHeader.IgnoreValue); //private const int c_DefaultBufferSize = 1024; //private int m_BufferSize = c_DefaultBufferSize; //private byte[] m_ReadBuffer = new byte[FrameHeader.SizeOf + m_BufferSize]; //private int m_CurReadOffset; private byte[] m_ReadHeaderBuffer; private byte[] m_WriteHeaderBuffer; private readonly AsyncCallback m_ReadFrameCallback; private readonly AsyncCallback m_BeginWriteCallback; private NetworkStream m_NetworkStream; //optimizing writes public StreamFramer(Stream Transport) { if (Transport == null || Transport == Stream.Null) { throw new ArgumentNullException("Transport"); } m_Transport = Transport; if(m_Transport.GetType() == typeof(NetworkStream)){ m_NetworkStream = Transport as NetworkStream; } m_ReadHeaderBuffer = new byte[m_CurReadHeader.Size]; m_WriteHeaderBuffer = new byte[m_WriteHeader.Size]; m_ReadFrameCallback = new AsyncCallback(ReadFrameCallback); m_BeginWriteCallback = new AsyncCallback(BeginWriteCallback); } /* // Consider removing. public FrameHeader m_ReadVerifierHeader { get { return m_ReadVerifier; } // May not be called while IO is in progress set { m_ReadVerifier = value; m_CurReadHeader = m_ReadVerifier.Clone(); m_ReadHeaderBuffer = new byte[m_CurReadHeader.Size]; } } */ public FrameHeader ReadHeader { get { return m_CurReadHeader; } } public FrameHeader WriteHeader { get { return m_WriteHeader; } /* // Consider removing. // May not be called while IO is in progress set { m_WriteHeader = value; m_WriteHeaderBuffer = new byte[m_WriteHeader.Size]; } */ } public Stream Transport { get { return m_Transport; } } /* // Consider removing. public bool EndOfFile { get { return m_Eof; } } */ /* // Consider removing. public bool CanRead { get { return Transport.CanRead; } } */ /* // Consider removing. public bool CanWrite { get { return Transport.CanWrite; } } */ public byte[] ReadMessage() { if (m_Eof) { return null; } int offset = 0; byte[] buffer = m_ReadHeaderBuffer; int bytesRead; while (offset < buffer.Length) { bytesRead = Transport.Read(buffer, offset, buffer.Length - offset); if (bytesRead == 0) { if (offset == 0) { // m_Eof, return null m_Eof = true; return null; } else { throw new IOException(SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed))); } } offset += bytesRead; } m_CurReadHeader.CopyFrom(buffer, 0, m_ReadVerifier); if (m_CurReadHeader.PayloadSize > m_CurReadHeader.MaxMessageSize) { throw new InvalidOperationException(SR.GetString(SR.net_frame_size, m_CurReadHeader.MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo), m_CurReadHeader.PayloadSize.ToString(NumberFormatInfo.InvariantInfo))); } buffer = new byte[m_CurReadHeader.PayloadSize]; offset = 0; while (offset < buffer.Length) { bytesRead = Transport.Read(buffer, offset, buffer.Length - offset); if (bytesRead == 0) { throw new IOException(SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed))); } offset += bytesRead; } return buffer; } public IAsyncResult BeginReadMessage(AsyncCallback asyncCallback, object stateObject) { WorkerAsyncResult workerResult; if (m_Eof){ workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback, null, 0, 0); workerResult.InvokeCallback(-1); return workerResult; } workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback, m_ReadHeaderBuffer, 0, m_ReadHeaderBuffer.Length); IAsyncResult result = Transport.BeginRead(m_ReadHeaderBuffer, 0, m_ReadHeaderBuffer.Length, m_ReadFrameCallback, workerResult); if (result.CompletedSynchronously) { ReadFrameComplete(result); } return workerResult; } private void ReadFrameCallback(IAsyncResult transportResult) { GlobalLog.Assert(transportResult.AsyncState is WorkerAsyncResult, "StreamFramer::ReadFrameCallback|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName); if (transportResult.CompletedSynchronously) { return; } WorkerAsyncResult workerResult = (WorkerAsyncResult) transportResult.AsyncState; try { ReadFrameComplete(transportResult); } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } if (!(e is IOException)) { e = new System.IO.IOException(SR.GetString(SR.net_io_readfailure, e.Message), e); } // Let's call user callback and he call us back and we will throw workerResult.InvokeCallback(e); } } // IO COMPLETION CALLBACK // // This callback is responsible for getting complete protocol frame // First, it reads the header // Second, it determines the frame size // Third, loops while not all frame received or an error. // private void ReadFrameComplete(IAsyncResult transportResult) { do { GlobalLog.Assert(transportResult.AsyncState is WorkerAsyncResult, "StreamFramer::ReadFrameComplete|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName); WorkerAsyncResult workerResult = (WorkerAsyncResult) transportResult.AsyncState; int bytesRead = Transport.EndRead(transportResult); workerResult.Offset += bytesRead; GlobalLog.Assert(workerResult.Offset <= workerResult.End, "StreamFramer::ReadFrameCallback|WRONG: offset - end = {0}", workerResult.Offset - workerResult.End); if (bytesRead <= 0) { // (by design) This indicates the stream has receives EOF // If we are in the middle of a Frame - fail, otherwise - produce EOF object result = null; if (!workerResult.HeaderDone && workerResult.Offset == 0) { result = (object)-1; } else { result = new System.IO.IOException(SR.GetString(SR.net_frame_read_io)); } workerResult.InvokeCallback(result); return; } if (workerResult.Offset >= workerResult.End) { if (!workerResult.HeaderDone) { workerResult.HeaderDone = true; // This indicates the header has been read succesfully m_CurReadHeader.CopyFrom(workerResult.Buffer, 0, m_ReadVerifier); int payloadSize = m_CurReadHeader.PayloadSize; if (payloadSize < 0) { // Let's call user callback and he call us back and we will throw workerResult.InvokeCallback(new System.IO.IOException(SR.GetString(SR.net_frame_read_size))); } if (payloadSize == 0) { // report emtpy frame (NOT eof!) to the caller, he might be interested in workerResult.InvokeCallback(0); return; } if (payloadSize > m_CurReadHeader.MaxMessageSize) { throw new InvalidOperationException(SR.GetString(SR.net_frame_size, m_CurReadHeader.MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo), payloadSize.ToString(NumberFormatInfo.InvariantInfo))); } // Start reading the remaining frame data (note header does not count) byte[] frame = new byte[payloadSize]; // Save the ref of the data block workerResult.Buffer = frame; workerResult.End = frame.Length; workerResult.Offset = 0; // Transport.BeginRead below will pickup those changes } else { workerResult.HeaderDone = false; //reset for optional object reuse workerResult.InvokeCallback(workerResult.End); return; } } // This means we need more data to complete the data block transportResult = Transport.BeginRead(workerResult.Buffer, workerResult.Offset, workerResult.End - workerResult.Offset, m_ReadFrameCallback, workerResult); } while(transportResult.CompletedSynchronously); } // // User will call this when workerResult gets signalled // // On Beginread User always gets back our WorkerAsyncResult // The Result property represents either a number of bytes read or an // exception put by our async state machine // public byte[] EndReadMessage(IAsyncResult asyncResult) { if (asyncResult==null) { throw new ArgumentNullException("asyncResult"); } WorkerAsyncResult workerResult = asyncResult as WorkerAsyncResult; if (workerResult == null) { throw new ArgumentException(SR.GetString(SR.net_io_async_result, typeof(WorkerAsyncResult).FullName), "asyncResult"); } if (!workerResult.InternalPeekCompleted) { workerResult.InternalWaitForCompletion(); } if (workerResult.Result is Exception) { throw (Exception)(workerResult.Result); } int size = (int)workerResult.Result; if (size == -1) { m_Eof = true; return null; } else if (size == 0) { //empty frame return new byte[0]; } return workerResult.Buffer; } // // // // public void WriteMessage(byte[] message) { if (message == null) { throw new ArgumentNullException("message"); } m_WriteHeader.PayloadSize = message.Length; m_WriteHeader.CopyTo(m_WriteHeaderBuffer, 0); if (m_NetworkStream != null && message.Length != 0) { BufferOffsetSize[] buffers = new BufferOffsetSize[2]; buffers[0] = new BufferOffsetSize(m_WriteHeaderBuffer, 0, m_WriteHeaderBuffer.Length, false); buffers[1] = new BufferOffsetSize(message, 0, message.Length, false); m_NetworkStream.MultipleWrite(buffers); } else { Transport.Write(m_WriteHeaderBuffer, 0, m_WriteHeaderBuffer.Length); if (message.Length==0) { return; } Transport.Write(message, 0, message.Length); } } // // // // public IAsyncResult BeginWriteMessage(byte[] message, AsyncCallback asyncCallback, object stateObject) { if (message == null) { throw new ArgumentNullException("message"); } m_WriteHeader.PayloadSize = message.Length; m_WriteHeader.CopyTo(m_WriteHeaderBuffer, 0); if (m_NetworkStream != null && message.Length != 0) { BufferOffsetSize[] buffers = new BufferOffsetSize[2]; buffers[0] = new BufferOffsetSize(m_WriteHeaderBuffer, 0, m_WriteHeaderBuffer.Length, false); buffers[1] = new BufferOffsetSize(message, 0, message.Length, false); return m_NetworkStream.BeginMultipleWrite(buffers, asyncCallback, stateObject); } if (message.Length == 0) { return Transport.BeginWrite(m_WriteHeaderBuffer, 0, m_WriteHeaderBuffer.Length, asyncCallback, stateObject); } //Will need two async writes // Prepare the second WorkerAsyncResult workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback, message, 0, message.Length); // Charge the first IAsyncResult result = Transport.BeginWrite(m_WriteHeaderBuffer, 0, m_WriteHeaderBuffer.Length, m_BeginWriteCallback, workerResult); if (result.CompletedSynchronously) { BeginWriteComplete(result); } return workerResult; } private void BeginWriteCallback(IAsyncResult transportResult) { GlobalLog.Assert(transportResult.AsyncState is WorkerAsyncResult, "StreamFramer::BeginWriteCallback|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.AsyncState.GetType().FullName); if (transportResult.CompletedSynchronously) { return; } WorkerAsyncResult workerResult = (WorkerAsyncResult) transportResult.AsyncState; try { BeginWriteComplete(transportResult); } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } workerResult.InvokeCallback(e); } } // IO COMPLETION CALLBACK // // Called when user IO request was wrapped to do several underlined IO // private void BeginWriteComplete(IAsyncResult transportResult) { do { WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState; //First, complete the previous portion write Transport.EndWrite(transportResult); //Check on exit criterion if (workerResult.Offset == workerResult.End) { workerResult.InvokeCallback(); return; } //setup exit criterion workerResult.Offset = workerResult.End; //Write next portion (frame body) using Async IO transportResult = Transport.BeginWrite(workerResult.Buffer, 0, workerResult.End, m_BeginWriteCallback, workerResult); } while (transportResult.CompletedSynchronously); } public void EndWriteMessage(IAsyncResult asyncResult) { if (asyncResult==null) { throw new ArgumentNullException("asyncResult"); } WorkerAsyncResult workerResult = asyncResult as WorkerAsyncResult; if (workerResult != null) { if (!workerResult.InternalPeekCompleted) { workerResult.InternalWaitForCompletion(); } if (workerResult.Result is Exception) { throw (Exception)(workerResult.Result); } } else { Transport.EndWrite(asyncResult); } } /* // Consider removing. public void Close() { Transport.Close(); } */ } // // This class wraps an Async IO request // It is based on our internal LazyAsyncResult helper // - If ParentResult is not null then the base class (LazyAsyncResult) methods must not be used // // - If ParentResult == null, then real user IO request is wrapped // /* // Consider removing. internal delegate void WorkerCallback(WorkerAsyncResult result); */ internal class WorkerAsyncResult : LazyAsyncResult { public byte[] Buffer; public int Offset; public int End; public bool IsWrite; public WorkerAsyncResult ParentResult; /* // Consider removing. public WorkerCallback StepDoneCallback; */ public bool HeaderDone; // This migth be reworked so we read both header and frame in one chunk public bool HandshakeDone; public WorkerAsyncResult(object asyncObject, object asyncState, AsyncCallback savedAsyncCallback, byte[] buffer, int offset, int end) : base( asyncObject, asyncState, savedAsyncCallback) { Buffer = buffer; Offset = offset; End = end; } /* // Consider removing. public WorkerAsyncResult(WorkerAsyncResult parentResult, byte[] buffer, int offset, int end) : base(null, null, null) { ParentResult = parentResult; Buffer = buffer; Offset = offset; End = end; } */ } // This guy describes the header used in framing of the stream data. internal class FrameHeader { public const int IgnoreValue = -1; public const int HandshakeDoneId= 20; public const int HandshakeErrId = 21; public const int HandshakeId = 22; public const int DefaultMajorV = 1; public const int DefaultMinorV = 0; private int _MessageId; private int _MajorV; private int _MinorV; private int _PayloadSize; public FrameHeader () { _MessageId = HandshakeId; _MajorV = DefaultMajorV; _MinorV = DefaultMinorV; _PayloadSize = -1; } public FrameHeader (int messageId, int majorV, int minorV) { _MessageId = messageId; _MajorV = majorV; _MinorV = minorV; _PayloadSize = -1; } /* // Consider removing. public FrameHeader Clone() { return new FrameHeader(_MessageId, _MajorV, _MinorV); } */ public int Size { get { return 5; } } public int MaxMessageSize { get { return 0xFFFF; } } public int MessageId { get { return _MessageId; } set { _MessageId = value; } } public int MajorV { get { return _MajorV; } } public int MinorV { get { return _MinorV; } } public int PayloadSize { get { return _PayloadSize; } set { if (value > MaxMessageSize) { throw new ArgumentException(SR.GetString(SR.net_frame_max_size, MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo), value.ToString(NumberFormatInfo.InvariantInfo)), "PayloadSize"); } _PayloadSize = value; } } public void CopyTo(byte[] dest, int start) { dest[start++] = (byte)_MessageId; dest[start++] = (byte)_MajorV; dest[start++] = (byte)_MinorV; dest[start++] = (byte)((_PayloadSize >> 8) & 0xFF); dest[start] = (byte)(_PayloadSize & 0xFF); } public void CopyFrom(byte[] bytes, int start, FrameHeader verifier) { _MessageId = bytes[start++]; _MajorV = bytes[start++]; _MinorV = bytes[start++]; _PayloadSize = (int) ((bytes[start++]<<8) | bytes[start]); if (verifier.MessageId != FrameHeader.IgnoreValue && MessageId != verifier.MessageId) { throw new InvalidOperationException(SR.GetString(SR.net_io_header_id, "MessageId", MessageId, verifier.MessageId)); } if (verifier.MajorV != FrameHeader.IgnoreValue && MajorV != verifier.MajorV) { throw new InvalidOperationException(SR.GetString(SR.net_io_header_id, "MajorV", MajorV, verifier.MajorV)); } if (verifier.MinorV != FrameHeader.IgnoreValue && MinorV != verifier.MinorV) { throw new InvalidOperationException(SR.GetString(SR.net_io_header_id, "MinorV", MinorV, verifier.MinorV)); } } } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System.Linq; using EventStore.Core.Data; using EventStore.Core.Services.Storage.ReaderIndex; using NUnit.Framework; using ReadStreamResult = EventStore.Core.Services.Storage.ReaderIndex.ReadStreamResult; namespace EventStore.Core.Tests.Services.Storage.HashCollisions { [TestFixture] public class with_three_collisioned_streams_with_different_number_of_events_third_one_deleted_each_read_index_should : ReadIndexTestScenario { private EventRecord[] _prepares1; private EventRecord[] _prepares2; private EventRecord[] _prepares3; private EventRecord _delete3; protected override void WriteTestScenario() { _prepares1 = new EventRecord[3]; for (int i = 0; i < _prepares1.Length; i++) { _prepares1[i] = WriteSingleEvent("AB", i, "test" + i); } _prepares2 = new EventRecord[5]; for (int i = 0; i < _prepares2.Length; i++) { _prepares2[i] = WriteSingleEvent("CD", i, "test" + i); } _prepares3 = new EventRecord[7]; for (int i = 0; i < _prepares3.Length; i++) { _prepares3[i] = WriteSingleEvent("EF", i, "test" + i); } _delete3 = WriteDelete("EF"); } #region first [Test] public void return_correct_last_event_version_for_first_stream() { Assert.AreEqual(2, ReadIndex.GetStreamLastEventNumber("AB")); } [Test] public void return_minus_one_when_asked_for_last_version_for_stream_with_same_hash_as_first() { Assert.AreEqual(-1, ReadIndex.GetStreamLastEventNumber("FY")); } [Test] public void return_correct_first_record_for_first_stream() { var result = ReadIndex.ReadEvent("AB", 0); Assert.AreEqual(ReadEventResult.Success, result.Result); Assert.AreEqual(_prepares1[0], result.Record); } [Test] public void return_correct_last_log_record_for_first_stream() { var result = ReadIndex.ReadEvent("AB", 2); Assert.AreEqual(ReadEventResult.Success, result.Result); Assert.AreEqual(_prepares1[2], result.Record); } [Test] public void not_find_record_with_version_3_in_first_stream() { var result = ReadIndex.ReadEvent("AB", 3); Assert.AreEqual(ReadEventResult.NotFound, result.Result); Assert.IsNull(result.Record); } [Test] public void return_not_found_for_record_version_3_for_stream_with_same_hash_as_first_stream() { var result = ReadIndex.ReadEvent("FY", 3); Assert.AreEqual(ReadEventResult.NoStream, result.Result); Assert.IsNull(result.Record); } [Test] public void return_not_found_for_record_version_2_for_stream_with_same_hash_as_first_stream() { var result = ReadIndex.ReadEvent("FY", 2); Assert.AreEqual(ReadEventResult.NoStream, result.Result); Assert.IsNull(result.Record); } [Test] public void return_not_found_for_record_version_0_for_stream_with_same_hash_as_first_stream() { var result = ReadIndex.ReadEvent("FY", 0); Assert.AreEqual(ReadEventResult.NoStream, result.Result); Assert.IsNull(result.Record); } [Test] public void return_correct_range_on_from_start_range_query_for_first_stream() { var result = ReadIndex.ReadStreamEventsForward("AB", 0, 3); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(3, result.Records.Length); for (int i = 0; i < _prepares1.Length; i++) { Assert.AreEqual(_prepares1[i], result.Records[i]); } } [Test] public void return_correct_0_1_range_on_from_start_range_query_for_first_stream() { var result = ReadIndex.ReadStreamEventsForward("AB", 0, 1); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(1, result.Records.Length); Assert.AreEqual(_prepares1[0], result.Records[0]); } [Test] public void return_correct_1_1_range_on_from_start_range_query_for_first_stream() { var result = ReadIndex.ReadStreamEventsForward("AB", 1, 1); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(1, result.Records.Length); Assert.AreEqual(_prepares1[1], result.Records[0]); } [Test] public void return_empty_range_for_3_1_range_on_from_start_range_query_request_for_first_stream() { var result = ReadIndex.ReadStreamEventsForward("AB", 3, 1); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_range_on_from_start_range_query_for_non_existing_stream_with_same_hash_as_first_one() { var result = ReadIndex.ReadStreamEventsForward("FY", 0, 3); Assert.AreEqual(ReadStreamResult.NoStream, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_1_1_range_on_from_start_range_query_for_non_existing_stream_with_same_hash_as_first_one() { var result = ReadIndex.ReadStreamEventsForward("FY", 1, 1); Assert.AreEqual(ReadStreamResult.NoStream, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_3_1_range_on_from_start_range_query_for_non_existing_stream_with_same_hash_as_first_one() { var result = ReadIndex.ReadStreamEventsForward("FY", 3, 1); Assert.AreEqual(ReadStreamResult.NoStream, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_correct_range_on_from_end_range_query_for_first_stream_with_specific_version() { var result = ReadIndex.ReadStreamEventsBackward("AB", 2, 3); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(3, result.Records.Length); var records = result.Records.Reverse().ToArray(); for (int i = 0; i < _prepares1.Length; i++) { Assert.AreEqual(_prepares1[i], records[i]); } } [Test] public void return_correct_range_on_from_end_range_query_for_first_stream_with_from_end_version() { var result = ReadIndex.ReadStreamEventsBackward("AB", -1, 3); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(3, result.Records.Length); var records = result.Records.Reverse().ToArray(); for (int i = 0; i < _prepares1.Length; i++) { Assert.AreEqual(_prepares1[i], records[i]); } } [Test] public void return_correct_0_1_range_on_from_end_range_query_for_first_stream() { var result = ReadIndex.ReadStreamEventsBackward("AB", 0, 1); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(1, result.Records.Length); Assert.AreEqual(_prepares1[0], result.Records[0]); } [Test] public void return_correct_from_end_1_range_on_from_end_range_query_for_first_stream() { var result = ReadIndex.ReadStreamEventsBackward("AB", -1, 1); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(1, result.Records.Length); Assert.AreEqual(_prepares1[2], result.Records[0]); } [Test] public void return_correct_1_1_range_on_from_end_range_query_for_first_stream() { var result = ReadIndex.ReadStreamEventsBackward("AB", 1, 1); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(1, result.Records.Length); Assert.AreEqual(_prepares1[1], result.Records[0]); } [Test] public void return_empty_range_for_3_1_range_on_from_end_range_query_request_for_first_stream() { var result = ReadIndex.ReadStreamEventsBackward("AB", 3, 1); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_range_on_from_end_range_query_for_non_existing_stream_with_same_hash_as_first_one() { var result = ReadIndex.ReadStreamEventsBackward("FY", 0, 3); Assert.AreEqual(ReadStreamResult.NoStream, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_1_1_range_on_from_end_range_query_for_non_existing_stream_with_same_hash_as_first_one() { var result = ReadIndex.ReadStreamEventsBackward("FY", 1, 1); Assert.AreEqual(ReadStreamResult.NoStream, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_3_1_range_on_from_end_range_query_for_non_existing_stream_with_same_hash_as_first_one() { var result = ReadIndex.ReadStreamEventsBackward("FY", 3, 1); Assert.AreEqual(ReadStreamResult.NoStream, result.Result); Assert.AreEqual(0, result.Records.Length); } #endregion #region second [Test] public void return_correct_last_event_version_for_second_stream() { Assert.AreEqual(4, ReadIndex.GetStreamLastEventNumber("CD")); } [Test] public void return_minus_one_when_aked_for_last_version_for_stream_with_same_hash_as_second() { Assert.AreEqual(-1, ReadIndex.GetStreamLastEventNumber("FY")); } [Test] public void return_correct_first_record_for_second_stream() { var result = ReadIndex.ReadEvent("CD", 0); Assert.AreEqual(ReadEventResult.Success, result.Result); Assert.AreEqual(_prepares2[0], result.Record); } [Test] public void return_correct_last_log_record_for_second_stream() { var result = ReadIndex.ReadEvent("CD", 4); Assert.AreEqual(ReadEventResult.Success, result.Result); Assert.AreEqual(_prepares2[4], result.Record); } [Test] public void not_find_record_with_version_5_in_second_stream() { var result = ReadIndex.ReadEvent("CD", 5); Assert.AreEqual(ReadEventResult.NotFound, result.Result); Assert.IsNull(result.Record); } [Test] public void return_not_found_for_record_version_5_for_stream_with_same_hash_as_second_stream() { var result = ReadIndex.ReadEvent("FY", 5); Assert.AreEqual(ReadEventResult.NoStream, result.Result); Assert.IsNull(result.Record); } [Test] public void return_not_found_for_record_version_4_for_stream_with_same_hash_as_second_stream() { var result = ReadIndex.ReadEvent("FY", 4); Assert.AreEqual(ReadEventResult.NoStream, result.Result); Assert.IsNull(result.Record); } [Test] public void return_not_found_for_record_version_0_for_stream_with_same_hash_as_second_stream() { var result = ReadIndex.ReadEvent("FY", 0); Assert.AreEqual(ReadEventResult.NoStream, result.Result); Assert.IsNull(result.Record); } [Test] public void return_correct_range_on_from_start_range_query_for_second_stream() { var result = ReadIndex.ReadStreamEventsForward("CD", 0, 5); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(5, result.Records.Length); for (int i = 0; i < _prepares2.Length; i++) { Assert.AreEqual(_prepares2[i], result.Records[i]); } } [Test] public void return_correct_0_2_range_on_from_start_range_query_for_second_stream() { var result = ReadIndex.ReadStreamEventsForward("CD", 0, 2); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(2, result.Records.Length); Assert.AreEqual(_prepares2[0], result.Records[0]); Assert.AreEqual(_prepares2[1], result.Records[1]); } [Test] public void return_correct_2_2_range_on_from_start_range_query_for_second_stream() { var result = ReadIndex.ReadStreamEventsForward("CD", 2, 2); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(2, result.Records.Length); Assert.AreEqual(_prepares2[2], result.Records[0]); Assert.AreEqual(_prepares2[3], result.Records[1]); } [Test] public void return_empty_range_for_5_1_range_on_from_start_range_query_request_for_second_stream() { var result = ReadIndex.ReadStreamEventsForward("CD", 5, 1); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_range_on_from_start_range_query_for_non_existing_stream_with_same_hash_as_second_one() { var result = ReadIndex.ReadStreamEventsForward("FY", 0, 5); Assert.AreEqual(ReadStreamResult.NoStream, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_5_1_range_on_from_start_range_query_for_non_existing_stream_with_same_hash_as_second_one() { var result = ReadIndex.ReadStreamEventsForward("FY", 5, 1); Assert.AreEqual(ReadStreamResult.NoStream, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_correct_range_on_from_end_range_query_for_second_stream_with_specific_version() { var result = ReadIndex.ReadStreamEventsBackward("CD", 4, 5); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(5, result.Records.Length); var records = result.Records.Reverse().ToArray(); for (int i = 0; i < _prepares2.Length; i++) { Assert.AreEqual(_prepares2[i], records[i]); } } [Test] public void return_correct_range_on_from_end_range_query_for_second_stream_with_from_end_version() { var result = ReadIndex.ReadStreamEventsBackward("CD", -1, 5); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(5, result.Records.Length); var records = result.Records.Reverse().ToArray(); for (int i = 0; i < _prepares2.Length; i++) { Assert.AreEqual(_prepares2[i], records[i]); } } [Test] public void return_correct_0_1_range_on_from_end_range_query_for_second_stream() { var result = ReadIndex.ReadStreamEventsBackward("CD", 0, 1); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(1, result.Records.Length); Assert.AreEqual(_prepares2[0], result.Records[0]); } [Test] public void return_correct_from_end_1_range_on_from_end_range_query_for_second_stream() { var result = ReadIndex.ReadStreamEventsBackward("CD", -1, 1); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(1, result.Records.Length); Assert.AreEqual(_prepares2[4], result.Records[0]); } [Test] public void return_correct_1_1_range_on_from_end_range_query_for_second_stream() { var result = ReadIndex.ReadStreamEventsBackward("CD", 1, 1); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(1, result.Records.Length); Assert.AreEqual(_prepares2[1], result.Records[0]); } [Test] public void return_correct_from_end_2_range_on_from_end_range_query_for_second_stream() { var result = ReadIndex.ReadStreamEventsBackward("CD", -1, 2); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(2, result.Records.Length); Assert.AreEqual(_prepares2[4], result.Records[0]); Assert.AreEqual(_prepares2[3], result.Records[1]); } [Test] public void return_empty_range_for_5_1_range_on_from_end_range_query_request_for_second_stream() { var result = ReadIndex.ReadStreamEventsBackward("CD", 5, 1); Assert.AreEqual(ReadStreamResult.Success, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_range_on_from_end_range_query_for_non_existing_stream_with_same_hash_as_second_one() { var result = ReadIndex.ReadStreamEventsBackward("FY", 0, 5); Assert.AreEqual(ReadStreamResult.NoStream, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_5_1_range_on_from_end_range_query_for_non_existing_stream_with_same_hash_as_second_one() { var result = ReadIndex.ReadStreamEventsBackward("FY", 5, 1); Assert.AreEqual(ReadStreamResult.NoStream, result.Result); Assert.AreEqual(0, result.Records.Length); } #endregion #region third [Test] public void return_correct_last_event_version_for_third_stream() { Assert.AreEqual(EventNumber.DeletedStream, ReadIndex.GetStreamLastEventNumber("EF")); } [Test] public void return_minus_one_when_aked_for_last_version_for_stream_with_same_hash_as_third() { Assert.AreEqual(-1, ReadIndex.GetStreamLastEventNumber("FY")); } [Test] public void not_find_first_record_for_third_stream() { var result = ReadIndex.ReadEvent("EF", 0); Assert.AreEqual(ReadEventResult.StreamDeleted, result.Result); Assert.IsNull(result.Record); } [Test] public void not_find_last_log_record_for_third_stream() { var result = ReadIndex.ReadEvent("EF", 6); Assert.AreEqual(ReadEventResult.StreamDeleted, result.Result); } [Test] public void not_find_record_with_version_7_in_third_stream() { var result = ReadIndex.ReadEvent("EF", 7); Assert.AreEqual(ReadEventResult.StreamDeleted, result.Result); } [Test] public void return_not_found_for_record_version_7_for_stream_with_same_hash_as_third_stream() { var result = ReadIndex.ReadEvent("FY", 7); Assert.AreEqual(ReadEventResult.NoStream, result.Result); } [Test] public void return_empty_range_on_from_start_range_query_for_third_stream() { var result = ReadIndex.ReadStreamEventsForward("EF", 0, 7); Assert.AreEqual(ReadStreamResult.StreamDeleted, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_0_7_range_on_from_start_range_query_for_third_stream() { var result = ReadIndex.ReadStreamEventsForward("EF", 0, 7); Assert.AreEqual(ReadStreamResult.StreamDeleted, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_2_3_range_on_from_start_range_query_for_third_stream() { var result = ReadIndex.ReadStreamEventsForward("EF", 2, 3); Assert.AreEqual(ReadStreamResult.StreamDeleted, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_range_for_7_1_range_on_from_start_range_query_request_for_third_stream() { var result = ReadIndex.ReadStreamEventsForward("EF", 7, 1); Assert.AreEqual(ReadStreamResult.StreamDeleted, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_range_on_from_start_range_query_for_non_existing_stream_with_same_hash_as_third_one() { var result = ReadIndex.ReadStreamEventsForward("FY", 0, 7); Assert.AreEqual(ReadStreamResult.NoStream, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_7_1_range_on_from_start_range_query_for_non_existing_stream_with_same_hash_as_third_one() { var result = ReadIndex.ReadStreamEventsForward("EF", 7, 1); Assert.AreEqual(ReadStreamResult.StreamDeleted, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_range_on_from_end_range_query_for_third_stream() { var result = ReadIndex.ReadStreamEventsBackward("EF", 0, 7); Assert.AreEqual(ReadStreamResult.StreamDeleted, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_0_1_range_on_from_end_range_query_for_third_stream() { var result = ReadIndex.ReadStreamEventsBackward("EF", 0, 1); Assert.AreEqual(ReadStreamResult.StreamDeleted, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_1_1_range_on_from_end_range_query_for_third_stream() { var result = ReadIndex.ReadStreamEventsBackward("EF", 1, 1); Assert.AreEqual(ReadStreamResult.StreamDeleted, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_range_for_7_1_range_on_from_end_range_query_request_for_third_stream() { var result = ReadIndex.ReadStreamEventsBackward("EF", 7, 1); Assert.AreEqual(ReadStreamResult.StreamDeleted, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_range_on_from_end_range_query_for_non_existing_stream_with_same_hash_as_third_one() { var result = ReadIndex.ReadStreamEventsBackward("FY", 0, 7); Assert.AreEqual(ReadStreamResult.NoStream, result.Result); Assert.AreEqual(0, result.Records.Length); } [Test] public void return_empty_7_1_range_on_from_end_range_query_for_non_existing_stream_with_same_hash_as_third_one() { var result = ReadIndex.ReadStreamEventsBackward("EF", 7, 1); Assert.AreEqual(ReadStreamResult.StreamDeleted, result.Result); Assert.AreEqual(0, result.Records.Length); } #endregion #region all [Test] public void return_all_prepares_on_read_all_forward() { var events = ReadIndex.ReadAllEventsForward(new TFPos(0, 0), 100).Records.Select(r => r.Event).ToArray(); Assert.AreEqual(3 + 5 + 7 + 1, events.Length); Assert.AreEqual(_prepares1[0], events[0]); Assert.AreEqual(_prepares1[1], events[1]); Assert.AreEqual(_prepares1[2], events[2]); Assert.AreEqual(_prepares2[0], events[3]); Assert.AreEqual(_prepares2[1], events[4]); Assert.AreEqual(_prepares2[2], events[5]); Assert.AreEqual(_prepares2[3], events[6]); Assert.AreEqual(_prepares2[4], events[7]); Assert.AreEqual(_prepares3[0], events[8]); Assert.AreEqual(_prepares3[1], events[9]); Assert.AreEqual(_prepares3[2], events[10]); Assert.AreEqual(_prepares3[3], events[11]); Assert.AreEqual(_prepares3[4], events[12]); Assert.AreEqual(_prepares3[5], events[13]); Assert.AreEqual(_prepares3[6], events[14]); Assert.AreEqual(_delete3, events[15]); } [Test] public void return_all_prepares_on_read_all_backward() { var events = ReadIndex.ReadAllEventsBackward(GetBackwardReadPos(), 100).Records.Select(r => r.Event).ToArray(); Assert.AreEqual(3 + 5 + 7 + 1, events.Length); Assert.AreEqual(_prepares1[0], events[15]); Assert.AreEqual(_prepares1[1], events[14]); Assert.AreEqual(_prepares1[2], events[13]); Assert.AreEqual(_prepares2[0], events[12]); Assert.AreEqual(_prepares2[1], events[11]); Assert.AreEqual(_prepares2[2], events[10]); Assert.AreEqual(_prepares2[3], events[9]); Assert.AreEqual(_prepares2[4], events[8]); Assert.AreEqual(_prepares3[0], events[7]); Assert.AreEqual(_prepares3[1], events[6]); Assert.AreEqual(_prepares3[2], events[5]); Assert.AreEqual(_prepares3[3], events[4]); Assert.AreEqual(_prepares3[4], events[3]); Assert.AreEqual(_prepares3[5], events[2]); Assert.AreEqual(_prepares3[6], events[1]); Assert.AreEqual(_delete3, events[0]); } #endregion } }
// 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; using System.Reflection; using System.Reflection.Emit; using System.Threading; using Xunit; namespace System.Reflection.Emit.Tests { public class TypeBuilderDefineDefaultConstructor { private const string DynamicAssemblyName = "TestDynamicAssembly"; private const string DynamicModuleName = "TestDynamicModule"; private const string DynamicBaseTypeName = "BaseTestDynamicType"; private const string DynamicTypeName = "TestDynamicType"; private const string DynamicBaseFieldName = "m_baseTestDynamicFieldA"; private const string DynamicMethodName = "TestDynamicMethodA"; public TypeBuilder RetriveTestTypeBuilder(string typeName, TypeAttributes typeAtt) { AssemblyName asmName = new AssemblyName(); asmName.Name = DynamicAssemblyName; AssemblyBuilder asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); ModuleBuilder modBuilder = TestLibrary.Utilities.GetModuleBuilder(asmBuilder, DynamicModuleName); TypeBuilder typeBuilder = modBuilder.DefineType(typeName, typeAtt); return typeBuilder; } public TypeBuilder RetriveTestTypeBuilder(TypeAttributes typeAtt) { AssemblyName asmName = new AssemblyName(); asmName.Name = DynamicAssemblyName; AssemblyBuilder asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); ModuleBuilder modBuilder = TestLibrary.Utilities.GetModuleBuilder(asmBuilder, DynamicModuleName); TypeBuilder typeBuilder = modBuilder.DefineType(DynamicTypeName, typeAtt); return typeBuilder; } [Fact] public void TestDefaultConstructor1() { ExePosTest(TypeAttributes.Public | TypeAttributes.Class, MethodAttributes.Public, BindingFlags.Public | BindingFlags.Instance); } [Fact] public void TestDefaultConstructor2() { ExePosTest(TypeAttributes.Class | TypeAttributes.Public, MethodAttributes.Static, BindingFlags.Static | BindingFlags.NonPublic); } [Fact] public void TestDefaultConstructor3() { ExePosTest(TypeAttributes.Class | TypeAttributes.Public, MethodAttributes.Family, BindingFlags.Instance | BindingFlags.NonPublic); } [Fact] public void TestDefaultConstructor4() { ExePosTest(TypeAttributes.Class | TypeAttributes.Public, MethodAttributes.Assembly, BindingFlags.Instance | BindingFlags.NonPublic); } [Fact] public void TestDefaultConstructor5() { ExePosTest(TypeAttributes.Class | TypeAttributes.Public, MethodAttributes.Private, BindingFlags.Instance | BindingFlags.NonPublic); } [Fact] public void TestDefaultConstructor6() { ExePosTest(TypeAttributes.Class | TypeAttributes.Public, MethodAttributes.PrivateScope, BindingFlags.Instance | BindingFlags.NonPublic); } [Fact] public void TestDefaultConstructor7() { ExePosTest(TypeAttributes.Class | TypeAttributes.Public, MethodAttributes.FamORAssem, BindingFlags.Instance | BindingFlags.NonPublic); } [Fact] public void TestDefaultConstructor8() { ExePosTest(TypeAttributes.Class | TypeAttributes.Public, MethodAttributes.FamANDAssem, BindingFlags.Instance | BindingFlags.NonPublic); } [Fact] public void TestDefaultConstructor9() { ExePosTest(TypeAttributes.Class | TypeAttributes.Public, MethodAttributes.Final | MethodAttributes.Public, BindingFlags.Instance | BindingFlags.Public); } [Fact] public void TestDefaultConstructor10() { ExePosTest(TypeAttributes.Class | TypeAttributes.Public, MethodAttributes.Final | MethodAttributes.Family, BindingFlags.Instance | BindingFlags.NonPublic); } [Fact] public void TestDefaultConstructor11() { ExePosTest(TypeAttributes.Class | TypeAttributes.Public, MethodAttributes.SpecialName | MethodAttributes.Family, BindingFlags.Instance | BindingFlags.NonPublic); } [Fact] public void TestDefaultConstructor12() { ExePosTest(TypeAttributes.Class | TypeAttributes.Public, MethodAttributes.UnmanagedExport | MethodAttributes.Family, BindingFlags.Instance | BindingFlags.NonPublic); } [Fact] public void TestDefaultConstructor13() { ExePosTest(TypeAttributes.Class | TypeAttributes.Public, MethodAttributes.RTSpecialName | MethodAttributes.Family, BindingFlags.Instance | BindingFlags.NonPublic); } [Fact] public void TestDefaultConstructor14() { ExePosTest(TypeAttributes.Class | TypeAttributes.Public, MethodAttributes.HideBySig | MethodAttributes.Family, BindingFlags.Instance | BindingFlags.NonPublic); } private void ExePosTest(TypeAttributes typeAttr, MethodAttributes ctorAttr, BindingFlags ctorBindingAttr) { TypeBuilder testTypeBuilder; ConstructorBuilder ctorBuilder; ConstructorInfo actualCtor; testTypeBuilder = RetriveTestTypeBuilder(typeAttr); ctorBuilder = testTypeBuilder.DefineDefaultConstructor(ctorAttr); Type testType = testTypeBuilder.CreateTypeInfo().AsType(); actualCtor = testType.GetConstructors(ctorBindingAttr).FirstOrDefault(); Assert.NotNull(actualCtor); } [Fact] public void TestThrowsExceptionForCreatetypeCalled() { TypeBuilder testTypeBuilder; testTypeBuilder = RetriveTestTypeBuilder(TypeAttributes.Public); testTypeBuilder.CreateTypeInfo().AsType(); Assert.Throws<InvalidOperationException>(() => { testTypeBuilder.DefineDefaultConstructor(MethodAttributes.Public); }); } [Fact] public void TestThrowsExceptionForInterface() { TypeBuilder testTypeBuilder; testTypeBuilder = RetriveTestTypeBuilder("negtest2", TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract); Assert.Throws<InvalidOperationException>(() => { testTypeBuilder.DefineDefaultConstructor(MethodAttributes.Public); }); } [Fact] public void TestThrowsExceptionForNoDefaultConstructor() { TypeBuilder baseTestTypeBuilder, testTypeBuilder; ConstructorBuilder baseCtorBuilder; FieldBuilder baseFieldBuilderA; baseTestTypeBuilder = RetriveTestTypeBuilder(DynamicBaseTypeName, TypeAttributes.Public | TypeAttributes.Class); baseFieldBuilderA = baseTestTypeBuilder.DefineField(DynamicBaseFieldName, typeof(int), FieldAttributes.Family); baseCtorBuilder = baseTestTypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new Type[] { typeof(int) }); ILGenerator baseCtorIL = baseCtorBuilder.GetILGenerator(); baseCtorIL.Emit(OpCodes.Ldarg_0); baseCtorIL.Emit(OpCodes.Call, typeof(object).GetConstructor(new Type[0])); baseCtorIL.Emit(OpCodes.Ldarg_0); baseCtorIL.Emit(OpCodes.Ldarg_1); baseCtorIL.Emit(OpCodes.Stfld, baseFieldBuilderA); baseCtorIL.Emit(OpCodes.Ret); Type baseTestType = baseTestTypeBuilder.CreateTypeInfo().AsType(); testTypeBuilder = RetriveTestTypeBuilder(TypeAttributes.Public | TypeAttributes.Class); testTypeBuilder.SetParent(baseTestType); Assert.Throws<NotSupportedException>(() => { testTypeBuilder.DefineDefaultConstructor(MethodAttributes.Public); }); } [Fact] public void TestThrowsExceptionForPrivateDefaultConstructor() { TypeBuilder baseTestTypeBuilder, testTypeBuilder; ConstructorBuilder baseCtorBuilder; baseTestTypeBuilder = RetriveTestTypeBuilder(DynamicBaseTypeName, TypeAttributes.Public | TypeAttributes.Class); baseCtorBuilder = baseTestTypeBuilder.DefineConstructor(MethodAttributes.Private, CallingConventions.HasThis, new Type[] { typeof(int) }); ILGenerator baseCtorIL = baseCtorBuilder.GetILGenerator(); baseCtorIL.Emit(OpCodes.Ret); Type baseTestType = baseTestTypeBuilder.CreateTypeInfo().AsType(); testTypeBuilder = RetriveTestTypeBuilder(TypeAttributes.Public | TypeAttributes.Class); testTypeBuilder.SetParent(baseTestType); Assert.Throws<NotSupportedException>(() => { testTypeBuilder.DefineDefaultConstructor(MethodAttributes.Public); }); } [Fact] public void TestThrowsExceptionForPrivateScopeDefaultConstructor() { TypeBuilder baseTestTypeBuilder, testTypeBuilder; ConstructorBuilder baseCtorBuilder; baseTestTypeBuilder = RetriveTestTypeBuilder(DynamicBaseTypeName, TypeAttributes.Public | TypeAttributes.Class); baseCtorBuilder = baseTestTypeBuilder.DefineConstructor(MethodAttributes.PrivateScope, CallingConventions.HasThis, new Type[] { typeof(int) }); ILGenerator baseCtorIL = baseCtorBuilder.GetILGenerator(); baseCtorIL.Emit(OpCodes.Ret); Type baseTestType = baseTestTypeBuilder.CreateTypeInfo().AsType(); testTypeBuilder = RetriveTestTypeBuilder(TypeAttributes.Public | TypeAttributes.Class); testTypeBuilder.SetParent(baseTestType); Assert.Throws<NotSupportedException>(() => { testTypeBuilder.DefineDefaultConstructor(MethodAttributes.Public); }); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: FindNode.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Territorium.Kademlia.Protocol { /// <summary>Holder for reflection information generated from FindNode.proto</summary> public static partial class FindNodeReflection { #region Descriptor /// <summary>File descriptor for FindNode.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static FindNodeReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cg5GaW5kTm9kZS5wcm90byKDAQoIRmluZE5vZGUSFgoOb3JpZ2luX2FkZHJl", "c3MYASABKAwSGwoTZGVzdGluYXRpb25fYWRkcmVzcxgCIAEoDBIUCgxub2Rl", "X3RvX2ZpbmQYAyABKAwSGgoSbm9kZXNfZm91bmRfc29fZmFyGAQgASgMEhAK", "CGN1c3RvbWVyGAUgASgMQiCqAh1UZXJyaXRvcml1bS5LYWRlbWxpYS5Qcm90", "b2NvbGIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Territorium.Kademlia.Protocol.FindNode), global::Territorium.Kademlia.Protocol.FindNode.Parser, new[]{ "OriginAddress", "DestinationAddress", "NodeToFind", "NodesFoundSoFar", "Customer" }, null, null, null) })); } #endregion } #region Messages public sealed partial class FindNode : pb::IMessage<FindNode> { private static readonly pb::MessageParser<FindNode> _parser = new pb::MessageParser<FindNode>(() => new FindNode()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<FindNode> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Territorium.Kademlia.Protocol.FindNodeReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FindNode() => OnConstruction(); partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FindNode(FindNode other) : this() { originAddress_ = other.originAddress_; destinationAddress_ = other.destinationAddress_; nodeToFind_ = other.nodeToFind_; nodesFoundSoFar_ = other.nodesFoundSoFar_; customer_ = other.customer_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FindNode Clone() { return new FindNode(this); } /// <summary>Field number for the "origin_address" field.</summary> public const int OriginAddressFieldNumber = 1; private pb::ByteString originAddress_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString OriginAddress { get => originAddress_; set => originAddress_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } /// <summary>Field number for the "destination_address" field.</summary> public const int DestinationAddressFieldNumber = 2; private pb::ByteString destinationAddress_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString DestinationAddress { get => destinationAddress_; set => destinationAddress_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } /// <summary>Field number for the "node_to_find" field.</summary> public const int NodeToFindFieldNumber = 3; private pb::ByteString nodeToFind_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString NodeToFind { get => nodeToFind_; set => nodeToFind_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } /// <summary>Field number for the "nodes_found_so_far" field.</summary> public const int NodesFoundSoFarFieldNumber = 4; private pb::ByteString nodesFoundSoFar_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString NodesFoundSoFar { get => nodesFoundSoFar_; set => nodesFoundSoFar_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } /// <summary>Field number for the "customer" field.</summary> public const int CustomerFieldNumber = 5; private pb::ByteString customer_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString Customer { get => customer_; set => customer_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as FindNode); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(FindNode other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (OriginAddress != other.OriginAddress) return false; if (DestinationAddress != other.DestinationAddress) return false; if (NodeToFind != other.NodeToFind) return false; if (NodesFoundSoFar != other.NodesFoundSoFar) return false; if (Customer != other.Customer) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (OriginAddress.Length != 0) hash ^= OriginAddress.GetHashCode(); if (DestinationAddress.Length != 0) hash ^= DestinationAddress.GetHashCode(); if (NodeToFind.Length != 0) hash ^= NodeToFind.GetHashCode(); if (NodesFoundSoFar.Length != 0) hash ^= NodesFoundSoFar.GetHashCode(); if (Customer.Length != 0) hash ^= Customer.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (OriginAddress.Length != 0) { output.WriteRawTag(10); output.WriteBytes(OriginAddress); } if (DestinationAddress.Length != 0) { output.WriteRawTag(18); output.WriteBytes(DestinationAddress); } if (NodeToFind.Length != 0) { output.WriteRawTag(26); output.WriteBytes(NodeToFind); } if (NodesFoundSoFar.Length != 0) { output.WriteRawTag(34); output.WriteBytes(NodesFoundSoFar); } if (Customer.Length != 0) { output.WriteRawTag(42); output.WriteBytes(Customer); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (OriginAddress.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(OriginAddress); } if (DestinationAddress.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(DestinationAddress); } if (NodeToFind.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(NodeToFind); } if (NodesFoundSoFar.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(NodesFoundSoFar); } if (Customer.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(Customer); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(FindNode other) { if (other == null) { return; } if (other.OriginAddress.Length != 0) { OriginAddress = other.OriginAddress; } if (other.DestinationAddress.Length != 0) { DestinationAddress = other.DestinationAddress; } if (other.NodeToFind.Length != 0) { NodeToFind = other.NodeToFind; } if (other.NodesFoundSoFar.Length != 0) { NodesFoundSoFar = other.NodesFoundSoFar; } if (other.Customer.Length != 0) { Customer = other.Customer; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { OriginAddress = input.ReadBytes(); break; } case 18: { DestinationAddress = input.ReadBytes(); break; } case 26: { NodeToFind = input.ReadBytes(); break; } case 34: { NodesFoundSoFar = input.ReadBytes(); break; } case 42: { Customer = input.ReadBytes(); break; } } } } } #endregion } #endregion Designer generated code
/* * 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 Apache.Ignite.Core.Tests { using System.Collections.Generic; using System.Linq; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Events; using NUnit.Framework; /// <summary> /// Tests <see cref="IgniteConfiguration.LocalEventListeners" />. /// </summary> public class EventsTestLocalListeners { /** Cache name. */ private const string CacheName = "cache"; /// <summary> /// Tests the rebalance events which occur during node startup. /// </summary> [Test] public void TestRebalanceEvents() { ICollection<int> cacheRebalanceStopStartEvts = new[] { EventType.CacheRebalanceStarted, EventType.CacheRebalanceStopped }; var listener = new Listener<CacheRebalancingEvent>(); using (IIgnite ignite0 = Ignition.Start(GetConfig(listener, cacheRebalanceStopStartEvts, "TestRebalanceEvents"))) { var cache = ignite0.GetOrCreateCache<int, int>(CacheName); for (int i = 0; i < 2000; i++) cache[i] = i; using (IIgnite ignite1 = Ignition.Start(GetConfig(listener, cacheRebalanceStopStartEvts))) { AffinityTopologyVersion afterRebalanceTop = new AffinityTopologyVersion(2, 1); Assert.True(ignite1.WaitTopology(afterRebalanceTop, CacheName), "Failed to wait topology " + afterRebalanceTop); var events = listener.GetEvents(); Assert.AreEqual(2, events.Count); var rebalanceStart = events.First(); Assert.AreEqual(CacheName, rebalanceStart.CacheName); Assert.AreEqual(EventType.CacheRebalanceStarted, rebalanceStart.Type); var rebalanceStop = events.Last(); Assert.AreEqual(CacheName, rebalanceStop.CacheName); Assert.AreEqual(EventType.CacheRebalanceStopped, rebalanceStop.Type); } } } /// <summary> /// Tests the unsubscription. /// </summary> [Test] public void TestUnsubscribe() { var listener = new Listener<CacheEvent>(); using (var ignite = Ignition.Start(GetConfig(listener, EventType.CacheAll))) { Assert.AreEqual(0, listener.GetEvents().Count); var cache = ignite.GetCache<int, int>(CacheName); // Put causes 3 events: EntryCreated, ObjectPut, EntryDestroyed. cache.Put(1, 1); Assert.AreEqual(3, listener.GetEvents().Count); // Remove listener from one of the event types. var res = ignite.GetEvents().StopLocalListen(listener, EventType.CacheEntryCreated); Assert.IsTrue(res); cache.Put(2, 2); Assert.AreEqual(2, listener.GetEvents().Count); // Remove from all event types. res = ignite.GetEvents().StopLocalListen(listener); Assert.IsTrue(res); cache.Put(3, 3); Assert.AreEqual(0, listener.GetEvents().Count); // Remove when not subscribed. res = ignite.GetEvents().StopLocalListen(listener); Assert.IsFalse(res); } } /// <summary> /// Tests the configuration validation. /// </summary> [Test] public void TestConfigValidation() { var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { LocalEventListeners = new LocalEventListener<IEvent>[1] }; // Null collection element. var ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.AreEqual("LocalEventListeners can't contain nulls.", ex.Message); // Null listener property. cfg.LocalEventListeners = new[] {new LocalEventListener<IEvent>()}; ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.AreEqual("LocalEventListener.Listener can't be null.", ex.Message); // Null event types. cfg.LocalEventListeners = new[] {new LocalEventListener<IEvent> {Listener = new Listener<IEvent>()}}; ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.AreEqual("LocalEventListener.EventTypes can't be null or empty.", ex.Message); // Empty event types. cfg.LocalEventListeners = new[] {new LocalEventListener<IEvent> {Listener = new Listener<IEvent>(), EventTypes = new int[0]}}; ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg)); Assert.AreEqual("LocalEventListener.EventTypes can't be null or empty.", ex.Message); } /// <summary> /// Gets the configuration. /// </summary> private static IgniteConfiguration GetConfig<T>(IEventListener<T> listener, ICollection<int> eventTypes, string instanceName = null) where T : IEvent { return new IgniteConfiguration(TestUtils.GetTestConfiguration()) { IgniteInstanceName = instanceName, LocalEventListeners = new[] { new LocalEventListener<T> { Listener = listener, EventTypes = eventTypes } }, IncludedEventTypes = eventTypes, CacheConfiguration = new[] { new CacheConfiguration(CacheName) } }; } /// <summary> /// Listener. /// </summary> private class Listener<T> : IEventListener<T> where T : IEvent { /** Listen action. */ private readonly List<T> _events = new List<T>(); /// <summary> /// Gets the events. /// </summary> public ICollection<T> GetEvents() { lock (_events) { var res = _events.ToArray(); _events.Clear(); return res; } } /** <inheritdoc /> */ public bool Invoke(T evt) { lock (_events) { _events.Add(evt); } return true; } } } }
/* * Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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 vector = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Vector3; using rotation = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Quaternion; namespace Aurora.ScriptEngine.AuroraDotNetEngine.Runtime { public partial class ScriptBaseClass { // LSL CONSTANTS public static readonly LSL_Types.LSLInteger TRUE = new LSL_Types.LSLInteger(1); public static readonly LSL_Types.LSLInteger FALSE = new LSL_Types.LSLInteger(0); public static readonly LSL_Types.LSLInteger STATUS_PHYSICS = 1; public static readonly LSL_Types.LSLInteger STATUS_ROTATE_X = 2; public static readonly LSL_Types.LSLInteger STATUS_ROTATE_Y = 4; public static readonly LSL_Types.LSLInteger STATUS_ROTATE_Z = 8; public static readonly LSL_Types.LSLInteger STATUS_PHANTOM = 16; public static readonly LSL_Types.LSLInteger STATUS_SANDBOX = 32; public static readonly LSL_Types.LSLInteger STATUS_BLOCK_GRAB = 64; public static readonly LSL_Types.LSLInteger STATUS_DIE_AT_EDGE = 128; public static readonly LSL_Types.LSLInteger STATUS_RETURN_AT_EDGE = 256; public static readonly LSL_Types.LSLInteger STATUS_CAST_SHADOWS = 512; public static readonly LSL_Types.LSLInteger STATUS_BLOCK_GRAB_OBJECT = 1024; public static readonly LSL_Types.LSLInteger AGENT = 1; public static readonly LSL_Types.LSLInteger AGENT_BY_LEGACY_NAME = 1; public static readonly LSL_Types.LSLInteger AGENT_BY_USERNAME = 0x10; public static readonly LSL_Types.LSLInteger ACTIVE = 2; public static readonly LSL_Types.LSLInteger PASSIVE = 4; public static readonly LSL_Types.LSLInteger SCRIPTED = 8; public static readonly LSL_Types.LSLInteger CONTROL_FWD = 1; public static readonly LSL_Types.LSLInteger CONTROL_BACK = 2; public static readonly LSL_Types.LSLInteger CONTROL_LEFT = 4; public static readonly LSL_Types.LSLInteger CONTROL_RIGHT = 8; public static readonly LSL_Types.LSLInteger CONTROL_UP = 16; public static readonly LSL_Types.LSLInteger CONTROL_DOWN = 32; public static readonly LSL_Types.LSLInteger CONTROL_ROT_LEFT = 256; public static readonly LSL_Types.LSLInteger CONTROL_ROT_RIGHT = 512; public static readonly LSL_Types.LSLInteger CONTROL_LBUTTON = 268435456; public static readonly LSL_Types.LSLInteger CONTROL_ML_LBUTTON = 1073741824; //Permissions public static readonly LSL_Types.LSLInteger PERMISSION_DEBIT = 2; public static readonly LSL_Types.LSLInteger PERMISSION_TAKE_CONTROLS = 4; public static readonly LSL_Types.LSLInteger PERMISSION_REMAP_CONTROLS = 8; public static readonly LSL_Types.LSLInteger PERMISSION_TRIGGER_ANIMATION = 16; public static readonly LSL_Types.LSLInteger PERMISSION_ATTACH = 32; public static readonly LSL_Types.LSLInteger PERMISSION_RELEASE_OWNERSHIP = 64; public static readonly LSL_Types.LSLInteger PERMISSION_CHANGE_LINKS = 128; public static readonly LSL_Types.LSLInteger PERMISSION_CHANGE_JOINTS = 256; public static readonly LSL_Types.LSLInteger PERMISSION_CHANGE_PERMISSIONS = 512; public static readonly LSL_Types.LSLInteger PERMISSION_TRACK_CAMERA = 1024; public static readonly LSL_Types.LSLInteger PERMISSION_CONTROL_CAMERA = 2048; public static readonly LSL_Types.LSLInteger PERMISSION_COMBAT = 8196; public static readonly LSL_Types.LSLInteger AGENT_FLYING = 1; public static readonly LSL_Types.LSLInteger AGENT_ATTACHMENTS = 2; public static readonly LSL_Types.LSLInteger AGENT_SCRIPTED = 4; public static readonly LSL_Types.LSLInteger AGENT_MOUSELOOK = 8; public static readonly LSL_Types.LSLInteger AGENT_SITTING = 16; public static readonly LSL_Types.LSLInteger AGENT_ON_OBJECT = 32; public static readonly LSL_Types.LSLInteger AGENT_AWAY = 64; public static readonly LSL_Types.LSLInteger AGENT_WALKING = 128; public static readonly LSL_Types.LSLInteger AGENT_IN_AIR = 256; public static readonly LSL_Types.LSLInteger AGENT_TYPING = 512; public static readonly LSL_Types.LSLInteger AGENT_CROUCHING = 1024; public static readonly LSL_Types.LSLInteger AGENT_BUSY = 2048; public static readonly LSL_Types.LSLInteger AGENT_ALWAYS_RUN = 4096; //Particle Systems public static readonly LSL_Types.LSLInteger PSYS_PART_INTERP_COLOR_MASK = 1; public static readonly LSL_Types.LSLInteger PSYS_PART_INTERP_SCALE_MASK = 2; public static readonly LSL_Types.LSLInteger PSYS_PART_BOUNCE_MASK = 4; public static readonly LSL_Types.LSLInteger PSYS_PART_WIND_MASK = 8; public static readonly LSL_Types.LSLInteger PSYS_PART_FOLLOW_SRC_MASK = 16; public static readonly LSL_Types.LSLInteger PSYS_PART_FOLLOW_VELOCITY_MASK = 32; public static readonly LSL_Types.LSLInteger PSYS_PART_TARGET_POS_MASK = 64; public static readonly LSL_Types.LSLInteger PSYS_PART_TARGET_LINEAR_MASK = 128; public static readonly LSL_Types.LSLInteger PSYS_PART_EMISSIVE_MASK = 256; public static readonly LSL_Types.LSLInteger PSYS_PART_FLAGS = 0; public static readonly LSL_Types.LSLInteger PSYS_PART_START_COLOR = 1; public static readonly LSL_Types.LSLInteger PSYS_PART_START_ALPHA = 2; public static readonly LSL_Types.LSLInteger PSYS_PART_END_COLOR = 3; public static readonly LSL_Types.LSLInteger PSYS_PART_END_ALPHA = 4; public static readonly LSL_Types.LSLInteger PSYS_PART_START_SCALE = 5; public static readonly LSL_Types.LSLInteger PSYS_PART_END_SCALE = 6; public static readonly LSL_Types.LSLInteger PSYS_PART_MAX_AGE = 7; public static readonly LSL_Types.LSLInteger PSYS_SRC_ACCEL = 8; public static readonly LSL_Types.LSLInteger PSYS_SRC_PATTERN = 9; public static readonly LSL_Types.LSLInteger PSYS_SRC_INNERANGLE = 10; public static readonly LSL_Types.LSLInteger PSYS_SRC_OUTERANGLE = 11; public static readonly LSL_Types.LSLInteger PSYS_SRC_TEXTURE = 12; public static readonly LSL_Types.LSLInteger PSYS_SRC_BURST_RATE = 13; public static readonly LSL_Types.LSLInteger PSYS_SRC_BURST_PART_COUNT = 15; public static readonly LSL_Types.LSLInteger PSYS_SRC_BURST_RADIUS = 16; public static readonly LSL_Types.LSLInteger PSYS_SRC_BURST_SPEED_MIN = 17; public static readonly LSL_Types.LSLInteger PSYS_SRC_BURST_SPEED_MAX = 18; public static readonly LSL_Types.LSLInteger PSYS_SRC_MAX_AGE = 19; public static readonly LSL_Types.LSLInteger PSYS_SRC_TARGET_KEY = 20; public static readonly LSL_Types.LSLInteger PSYS_SRC_OMEGA = 21; public static readonly LSL_Types.LSLInteger PSYS_SRC_ANGLE_BEGIN = 22; public static readonly LSL_Types.LSLInteger PSYS_SRC_ANGLE_END = 23; public static readonly LSL_Types.LSLInteger PSYS_SRC_PATTERN_DROP = 1; public static readonly LSL_Types.LSLInteger PSYS_SRC_PATTERN_EXPLODE = 2; public static readonly LSL_Types.LSLInteger PSYS_SRC_PATTERN_ANGLE = 4; public static readonly LSL_Types.LSLInteger PSYS_SRC_PATTERN_ANGLE_CONE = 8; public static readonly LSL_Types.LSLInteger PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY = 16; public static readonly LSL_Types.LSLInteger VEHICLE_TYPE_NONE = 0; public static readonly LSL_Types.LSLInteger VEHICLE_TYPE_SLED = 1; public static readonly LSL_Types.LSLInteger VEHICLE_TYPE_CAR = 2; public static readonly LSL_Types.LSLInteger VEHICLE_TYPE_BOAT = 3; public static readonly LSL_Types.LSLInteger VEHICLE_TYPE_AIRPLANE = 4; public static readonly LSL_Types.LSLInteger VEHICLE_TYPE_BALLOON = 5; public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_FRICTION_TIMESCALE = 16; public static readonly LSL_Types.LSLInteger VEHICLE_ANGULAR_FRICTION_TIMESCALE = 17; public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_MOTOR_DIRECTION = 18; public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_MOTOR_OFFSET = 20; public static readonly LSL_Types.LSLInteger VEHICLE_ANGULAR_MOTOR_DIRECTION = 19; public static readonly LSL_Types.LSLInteger VEHICLE_HOVER_HEIGHT = 24; public static readonly LSL_Types.LSLInteger VEHICLE_HOVER_EFFICIENCY = 25; public static readonly LSL_Types.LSLInteger VEHICLE_HOVER_TIMESCALE = 26; public static readonly LSL_Types.LSLInteger VEHICLE_BUOYANCY = 27; public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_DEFLECTION_EFFICIENCY = 28; public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_DEFLECTION_TIMESCALE = 29; public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_MOTOR_TIMESCALE = 30; public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE = 31; public static readonly LSL_Types.LSLInteger VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY = 32; public static readonly LSL_Types.LSLInteger VEHICLE_ANGULAR_DEFLECTION_TIMESCALE = 33; public static readonly LSL_Types.LSLInteger VEHICLE_ANGULAR_MOTOR_TIMESCALE = 34; public static readonly LSL_Types.LSLInteger VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE = 35; public static readonly LSL_Types.LSLInteger VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY = 36; public static readonly LSL_Types.LSLInteger VEHICLE_VERTICAL_ATTRACTION_TIMESCALE = 37; public static readonly LSL_Types.LSLInteger VEHICLE_BANKING_EFFICIENCY = 38; public static readonly LSL_Types.LSLInteger VEHICLE_BANKING_MIX = 39; public static readonly LSL_Types.LSLInteger VEHICLE_BANKING_TIMESCALE = 40; public static readonly LSL_Types.LSLInteger VEHICLE_REFERENCE_FRAME = 44; public static readonly LSL_Types.LSLInteger VEHICLE_RANGE_BLOCK = 45; public static readonly LSL_Types.LSLInteger VEHICLE_ROLL_FRAME = 46; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_NO_DEFLECTION_UP = 1; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_NO_FLY_UP = 1; //Old name for NO_DEFLECTION_UP public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_LIMIT_ROLL_ONLY = 2; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_HOVER_WATER_ONLY = 4; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_HOVER_TERRAIN_ONLY = 8; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT = 16; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_HOVER_UP_ONLY = 32; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_LIMIT_MOTOR_UP = 64; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_MOUSELOOK_STEER = 128; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_MOUSELOOK_BANK = 256; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_CAMERA_DECOUPLED = 512; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_NO_X = 1024; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_NO_Y = 2048; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_NO_Z = 4096; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_LOCK_HOVER_HEIGHT = 8192; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_NO_DEFLECTION = 16392; public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_LOCK_ROTATION = 32784; public static readonly LSL_Types.LSLInteger INVENTORY_ALL = -1; public static readonly LSL_Types.LSLInteger INVENTORY_NONE = -1; public static readonly LSL_Types.LSLInteger INVENTORY_TEXTURE = 0; public static readonly LSL_Types.LSLInteger INVENTORY_SOUND = 1; public static readonly LSL_Types.LSLInteger INVENTORY_LANDMARK = 3; public static readonly LSL_Types.LSLInteger INVENTORY_CLOTHING = 5; public static readonly LSL_Types.LSLInteger INVENTORY_OBJECT = 6; public static readonly LSL_Types.LSLInteger INVENTORY_NOTECARD = 7; public static readonly LSL_Types.LSLInteger INVENTORY_SCRIPT = 10; public static readonly LSL_Types.LSLInteger INVENTORY_BODYPART = 13; public static readonly LSL_Types.LSLInteger INVENTORY_ANIMATION = 20; public static readonly LSL_Types.LSLInteger INVENTORY_GESTURE = 21; public static readonly LSL_Types.LSLInteger ATTACH_CHEST = 1; public static readonly LSL_Types.LSLInteger ATTACH_HEAD = 2; public static readonly LSL_Types.LSLInteger ATTACH_LSHOULDER = 3; public static readonly LSL_Types.LSLInteger ATTACH_RSHOULDER = 4; public static readonly LSL_Types.LSLInteger ATTACH_LHAND = 5; public static readonly LSL_Types.LSLInteger ATTACH_RHAND = 6; public static readonly LSL_Types.LSLInteger ATTACH_LFOOT = 7; public static readonly LSL_Types.LSLInteger ATTACH_RFOOT = 8; public static readonly LSL_Types.LSLInteger ATTACH_BACK = 9; public static readonly LSL_Types.LSLInteger ATTACH_PELVIS = 10; public static readonly LSL_Types.LSLInteger ATTACH_MOUTH = 11; public static readonly LSL_Types.LSLInteger ATTACH_CHIN = 12; public static readonly LSL_Types.LSLInteger ATTACH_LEAR = 13; public static readonly LSL_Types.LSLInteger ATTACH_REAR = 14; public static readonly LSL_Types.LSLInteger ATTACH_LEYE = 15; public static readonly LSL_Types.LSLInteger ATTACH_REYE = 16; public static readonly LSL_Types.LSLInteger ATTACH_NOSE = 17; public static readonly LSL_Types.LSLInteger ATTACH_RUARM = 18; public static readonly LSL_Types.LSLInteger ATTACH_RLARM = 19; public static readonly LSL_Types.LSLInteger ATTACH_LUARM = 20; public static readonly LSL_Types.LSLInteger ATTACH_LLARM = 21; public static readonly LSL_Types.LSLInteger ATTACH_RHIP = 22; public static readonly LSL_Types.LSLInteger ATTACH_RULEG = 23; public static readonly LSL_Types.LSLInteger ATTACH_RLLEG = 24; public static readonly LSL_Types.LSLInteger ATTACH_LHIP = 25; public static readonly LSL_Types.LSLInteger ATTACH_LULEG = 26; public static readonly LSL_Types.LSLInteger ATTACH_LLLEG = 27; public static readonly LSL_Types.LSLInteger ATTACH_BELLY = 28; public static readonly LSL_Types.LSLInteger ATTACH_RPEC = 29; public static readonly LSL_Types.LSLInteger ATTACH_LPEC = 30; public static readonly LSL_Types.LSLInteger ATTACH_HUD_CENTER_2 = 31; public static readonly LSL_Types.LSLInteger ATTACH_HUD_TOP_RIGHT = 32; public static readonly LSL_Types.LSLInteger ATTACH_HUD_TOP_CENTER = 33; public static readonly LSL_Types.LSLInteger ATTACH_HUD_TOP_LEFT = 34; public static readonly LSL_Types.LSLInteger ATTACH_HUD_CENTER_1 = 35; public static readonly LSL_Types.LSLInteger ATTACH_HUD_BOTTOM_LEFT = 36; public static readonly LSL_Types.LSLInteger ATTACH_HUD_BOTTOM = 37; public static readonly LSL_Types.LSLInteger ATTACH_HUD_BOTTOM_RIGHT = 38; public static readonly LSL_Types.LSLInteger LAND_LEVEL = 0; public static readonly LSL_Types.LSLInteger LAND_RAISE = 1; public static readonly LSL_Types.LSLInteger LAND_LOWER = 2; public static readonly LSL_Types.LSLInteger LAND_SMOOTH = 3; public static readonly LSL_Types.LSLInteger LAND_NOISE = 4; public static readonly LSL_Types.LSLInteger LAND_REVERT = 5; public static readonly LSL_Types.LSLInteger LAND_SMALL_BRUSH = 1; public static readonly LSL_Types.LSLInteger LAND_MEDIUM_BRUSH = 2; public static readonly LSL_Types.LSLInteger LAND_LARGE_BRUSH = 3; // llGetAgentList public static readonly LSL_Types.LSLInteger AGENT_LIST_PARCEL = 1; public static readonly LSL_Types.LSLInteger AGENT_LIST_PARCEL_OWNER = 2; public static readonly LSL_Types.LSLInteger AGENT_LIST_REGION = 4; //Agent Dataserver public static readonly LSL_Types.LSLInteger DATA_ONLINE = 1; public static readonly LSL_Types.LSLInteger DATA_NAME = 2; public static readonly LSL_Types.LSLInteger DATA_BORN = 3; public static readonly LSL_Types.LSLInteger DATA_RATING = 4; public static readonly LSL_Types.LSLInteger DATA_SIM_POS = 5; public static readonly LSL_Types.LSLInteger DATA_SIM_STATUS = 6; public static readonly LSL_Types.LSLInteger DATA_SIM_RATING = 7; public static readonly LSL_Types.LSLInteger DATA_PAYINFO = 8; public static readonly LSL_Types.LSLInteger DATA_SIM_RELEASE = 128; public static readonly LSL_Types.LSLInteger ANIM_ON = 1; public static readonly LSL_Types.LSLInteger LOOP = 2; public static readonly LSL_Types.LSLInteger REVERSE = 4; public static readonly LSL_Types.LSLInteger PING_PONG = 8; public static readonly LSL_Types.LSLInteger SMOOTH = 16; public static readonly LSL_Types.LSLInteger ROTATE = 32; public static readonly LSL_Types.LSLInteger SCALE = 64; public static readonly LSL_Types.LSLInteger ALL_SIDES = -1; public static readonly LSL_Types.LSLInteger LINK_SET = -1; public static readonly LSL_Types.LSLInteger LINK_ROOT = 1; public static readonly LSL_Types.LSLInteger LINK_ALL_OTHERS = -2; public static readonly LSL_Types.LSLInteger LINK_ALL_CHILDREN = -3; public static readonly LSL_Types.LSLInteger LINK_THIS = -4; public static readonly LSL_Types.LSLInteger CHANGED_INVENTORY = 1; public static readonly LSL_Types.LSLInteger CHANGED_COLOR = 2; public static readonly LSL_Types.LSLInteger CHANGED_SHAPE = 4; public static readonly LSL_Types.LSLInteger CHANGED_SCALE = 8; public static readonly LSL_Types.LSLInteger CHANGED_TEXTURE = 16; public static readonly LSL_Types.LSLInteger CHANGED_LINK = 32; public static readonly LSL_Types.LSLInteger CHANGED_ALLOWED_DROP = 64; public static readonly LSL_Types.LSLInteger CHANGED_OWNER = 128; public static readonly LSL_Types.LSLInteger CHANGED_REGION = 256; public static readonly LSL_Types.LSLInteger CHANGED_TELEPORT = 512; public static readonly LSL_Types.LSLInteger CHANGED_REGION_RESTART = 1024; public static readonly LSL_Types.LSLInteger CHANGED_REGION_START = 1024; //LL Changed the constant from CHANGED_REGION_RESTART public static readonly LSL_Types.LSLInteger CHANGED_MEDIA = 2048; public static readonly LSL_Types.LSLInteger CHANGED_ANIMATION = 16384; public static readonly LSL_Types.LSLInteger CHANGED_STATE = 32768; public static readonly LSL_Types.LSLInteger TYPE_INVALID = 0; public static readonly LSL_Types.LSLInteger TYPE_INTEGER = 1; public static readonly LSL_Types.LSLInteger TYPE_FLOAT = 2; public static readonly LSL_Types.LSLInteger TYPE_STRING = 3; public static readonly LSL_Types.LSLInteger TYPE_KEY = 4; public static readonly LSL_Types.LSLInteger TYPE_VECTOR = 5; public static readonly LSL_Types.LSLInteger TYPE_ROTATION = 6; //XML RPC Remote Data Channel public static readonly LSL_Types.LSLInteger REMOTE_DATA_CHANNEL = 1; public static readonly LSL_Types.LSLInteger REMOTE_DATA_REQUEST = 2; public static readonly LSL_Types.LSLInteger REMOTE_DATA_REPLY = 3; //llHTTPRequest public static readonly LSL_Types.LSLInteger HTTP_METHOD = 0; public static readonly LSL_Types.LSLInteger HTTP_MIMETYPE = 1; public static readonly LSL_Types.LSLInteger HTTP_BODY_MAXLENGTH = 2; public static readonly LSL_Types.LSLInteger HTTP_VERIFY_CERT = 3; public static readonly LSL_Types.LSLInteger CONTENT_TYPE_TEXT = 0; public static readonly LSL_Types.LSLInteger CONTENT_TYPE_HTML = 1; public static readonly LSL_Types.LSLInteger PRIM_MATERIAL = 2; public static readonly LSL_Types.LSLInteger PRIM_PHYSICS = 3; public static readonly LSL_Types.LSLInteger PRIM_TEMP_ON_REZ = 4; public static readonly LSL_Types.LSLInteger PRIM_PHANTOM = 5; public static readonly LSL_Types.LSLInteger PRIM_POSITION = 6; public static readonly LSL_Types.LSLInteger PRIM_SIZE = 7; public static readonly LSL_Types.LSLInteger PRIM_ROTATION = 8; public static readonly LSL_Types.LSLInteger PRIM_TYPE = 9; public static readonly LSL_Types.LSLInteger PRIM_TEXTURE = 17; public static readonly LSL_Types.LSLInteger PRIM_COLOR = 18; public static readonly LSL_Types.LSLInteger PRIM_BUMP_SHINY = 19; public static readonly LSL_Types.LSLInteger PRIM_FULLBRIGHT = 20; public static readonly LSL_Types.LSLInteger PRIM_FLEXIBLE = 21; public static readonly LSL_Types.LSLInteger PRIM_TEXGEN = 22; public static readonly LSL_Types.LSLInteger PRIM_POINT_LIGHT = 23; public static readonly LSL_Types.LSLInteger PRIM_CAST_SHADOWS = 24; // Not implemented, here for completeness sake public static readonly LSL_Types.LSLInteger PRIM_GLOW = 25; public static readonly LSL_Types.LSLInteger PRIM_TEXT = 26; public static readonly LSL_Types.LSLInteger PRIM_NAME = 27; public static readonly LSL_Types.LSLInteger PRIM_DESC = 28; public static readonly LSL_Types.LSLInteger PRIM_ROT_LOCAL = 29; public static readonly LSL_Types.LSLInteger PRIM_OMEGA = 32; public static readonly LSL_Types.LSLInteger PRIM_POS_LOCAL = 33; public static readonly LSL_Types.LSLInteger PRIM_LINK_TARGET = 34; public static readonly LSL_Types.LSLInteger PRIM_PHYSICS_SHAPE_TYPE = 35; public static readonly LSL_Types.LSLInteger PRIM_TEXGEN_DEFAULT = 0; public static readonly LSL_Types.LSLInteger PRIM_TEXGEN_PLANAR = 1; public static readonly LSL_Types.LSLInteger PRIM_PHYSICS_SHAPE_PRIM = 0; public static readonly LSL_Types.LSLInteger PRIM_PHYSICS_SHAPE_CONVEX = 2; public static readonly LSL_Types.LSLInteger PRIM_PHYSICS_SHAPE_NONE = 1; public static readonly LSL_Types.LSLInteger DENSITY = 0; public static readonly LSL_Types.LSLInteger FRICTION = 1; public static readonly LSL_Types.LSLInteger RESTITUTION = 2; public static readonly LSL_Types.LSLInteger GRAVITY_MULTIPLIER = 3; public static readonly LSL_Types.LSLInteger PRIM_TYPE_BOX = 0; public static readonly LSL_Types.LSLInteger PRIM_TYPE_CYLINDER = 1; public static readonly LSL_Types.LSLInteger PRIM_TYPE_PRISM = 2; public static readonly LSL_Types.LSLInteger PRIM_TYPE_SPHERE = 3; public static readonly LSL_Types.LSLInteger PRIM_TYPE_TORUS = 4; public static readonly LSL_Types.LSLInteger PRIM_TYPE_TUBE = 5; public static readonly LSL_Types.LSLInteger PRIM_TYPE_RING = 6; public static readonly LSL_Types.LSLInteger PRIM_TYPE_SCULPT = 7; public static readonly LSL_Types.LSLInteger PRIM_HOLE_DEFAULT = 0; public static readonly LSL_Types.LSLInteger PRIM_HOLE_CIRCLE = 16; public static readonly LSL_Types.LSLInteger PRIM_HOLE_SQUARE = 32; public static readonly LSL_Types.LSLInteger PRIM_HOLE_TRIANGLE = 48; public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_STONE = 0; public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_METAL = 1; public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_GLASS = 2; public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_WOOD = 3; public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_FLESH = 4; public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_PLASTIC = 5; public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_RUBBER = 6; public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_LIGHT = 7; public static readonly LSL_Types.LSLInteger PRIM_SHINY_NONE = 0; public static readonly LSL_Types.LSLInteger PRIM_SHINY_LOW = 1; public static readonly LSL_Types.LSLInteger PRIM_SHINY_MEDIUM = 2; public static readonly LSL_Types.LSLInteger PRIM_SHINY_HIGH = 3; public static readonly LSL_Types.LSLInteger PRIM_BUMP_NONE = 0; public static readonly LSL_Types.LSLInteger PRIM_BUMP_BRIGHT = 1; public static readonly LSL_Types.LSLInteger PRIM_BUMP_DARK = 2; public static readonly LSL_Types.LSLInteger PRIM_BUMP_WOOD = 3; public static readonly LSL_Types.LSLInteger PRIM_BUMP_BARK = 4; public static readonly LSL_Types.LSLInteger PRIM_BUMP_BRICKS = 5; public static readonly LSL_Types.LSLInteger PRIM_BUMP_CHECKER = 6; public static readonly LSL_Types.LSLInteger PRIM_BUMP_CONCRETE = 7; public static readonly LSL_Types.LSLInteger PRIM_BUMP_TILE = 8; public static readonly LSL_Types.LSLInteger PRIM_BUMP_STONE = 9; public static readonly LSL_Types.LSLInteger PRIM_BUMP_DISKS = 10; public static readonly LSL_Types.LSLInteger PRIM_BUMP_GRAVEL = 11; public static readonly LSL_Types.LSLInteger PRIM_BUMP_BLOBS = 12; public static readonly LSL_Types.LSLInteger PRIM_BUMP_SIDING = 13; public static readonly LSL_Types.LSLInteger PRIM_BUMP_LARGETILE = 14; public static readonly LSL_Types.LSLInteger PRIM_BUMP_STUCCO = 15; public static readonly LSL_Types.LSLInteger PRIM_BUMP_SUCTION = 16; public static readonly LSL_Types.LSLInteger PRIM_BUMP_WEAVE = 17; public static readonly LSL_Types.LSLInteger PRIM_SCULPT_TYPE_SPHERE = 1; public static readonly LSL_Types.LSLInteger PRIM_SCULPT_TYPE_TORUS = 2; public static readonly LSL_Types.LSLInteger PRIM_SCULPT_TYPE_PLANE = 3; public static readonly LSL_Types.LSLInteger PRIM_SCULPT_TYPE_CYLINDER = 4; //Aurora-Sim const only public static readonly LSL_Types.LSLInteger PRIM_SCULPT_TYPE_MESH = 5; //??? public static readonly LSL_Types.LSLInteger PRIM_SCULPT_FLAG_INVERT = 64; public static readonly LSL_Types.LSLInteger PRIM_SCULPT_FLAG_MIRROR = 128; public static readonly LSL_Types.LSLInteger MASK_BASE = 0; public static readonly LSL_Types.LSLInteger MASK_OWNER = 1; public static readonly LSL_Types.LSLInteger MASK_GROUP = 2; public static readonly LSL_Types.LSLInteger MASK_EVERYONE = 3; public static readonly LSL_Types.LSLInteger MASK_NEXT = 4; public static readonly LSL_Types.LSLInteger PERM_TRANSFER = 8192; public static readonly LSL_Types.LSLInteger PERM_MODIFY = 16384; public static readonly LSL_Types.LSLInteger PERM_COPY = 32768; public static readonly LSL_Types.LSLInteger PERM_MOVE = 524288; public static readonly LSL_Types.LSLInteger PERM_ALL = 2147483647; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_STOP = 0; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_PAUSE = 1; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_PLAY = 2; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_LOOP = 3; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_TEXTURE = 4; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_URL = 5; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_TIME = 6; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_AGENT = 7; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_UNLOAD = 8; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_AUTO_ALIGN = 9; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_TYPE = 10; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_SIZE = 11; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_DESC = 12; public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_LOOP_SET = 13; // constants for llGetPrimMediaParams/llSetPrimMediaParams public static readonly LSL_Types.LSLInteger PRIM_MEDIA_ALT_IMAGE_ENABLE = 0; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_CONTROLS = 1; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_CURRENT_URL = 2; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_HOME_URL = 3; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_AUTO_LOOP = 4; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_AUTO_PLAY = 5; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_AUTO_SCALE = 6; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_AUTO_ZOOM = 7; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_FIRST_CLICK_INTERACT = 8; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_WIDTH_PIXELS = 9; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_HEIGHT_PIXELS = 10; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_WHITELIST_ENABLE = 11; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_WHITELIST = 12; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_PERMS_INTERACT = 13; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_PERMS_CONTROL = 14; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_CONTROLS_STANDARD = 0; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_CONTROLS_MINI = 1; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_PERM_NONE = 0; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_PERM_OWNER = 1; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_PERM_GROUP = 2; public static readonly LSL_Types.LSLInteger PRIM_MEDIA_PERM_ANYONE = 4; // extra constants for llSetPrimMediaParams public static readonly LSL_Types.LSLInteger LSL_STATUS_OK = new LSL_Types.LSLInteger(0); public static readonly LSL_Types.LSLInteger LSL_STATUS_MALFORMED_PARAMS = new LSL_Types.LSLInteger(1000); public static readonly LSL_Types.LSLInteger LSL_STATUS_TYPE_MISMATCH = new LSL_Types.LSLInteger(1001); public static readonly LSL_Types.LSLInteger LSL_STATUS_BOUNDS_ERROR = new LSL_Types.LSLInteger(1002); public static readonly LSL_Types.LSLInteger LSL_STATUS_NOT_FOUND = new LSL_Types.LSLInteger(1003); public static readonly LSL_Types.LSLInteger LSL_STATUS_NOT_SUPPORTED = new LSL_Types.LSLInteger(1004); public static readonly LSL_Types.LSLInteger LSL_STATUS_INTERNAL_ERROR = new LSL_Types.LSLInteger(1999); public static readonly LSL_Types.LSLInteger LSL_STATUS_WHITELIST_FAILED = new LSL_Types.LSLInteger(2001); public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_FLY = 0x1; // parcel allows flying public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_SCRIPTS = 0x2; // parcel allows outside scripts public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_LANDMARK = 0x8; // parcel allows landmarks to be created public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_TERRAFORM = 0x10; // parcel allows anyone to terraform the land public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_DAMAGE = 0x20; // parcel allows damage public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_CREATE_OBJECTS = 0x40; // parcel allows anyone to create objects public static readonly LSL_Types.LSLInteger PARCEL_FLAG_USE_ACCESS_GROUP = 0x100; // parcel limits access to a group public static readonly LSL_Types.LSLInteger PARCEL_FLAG_USE_ACCESS_LIST = 0x200; // parcel limits access to a list of residents public static readonly LSL_Types.LSLInteger PARCEL_FLAG_USE_BAN_LIST = 0x400; // parcel uses a ban list, including restricting access based on payment info public static readonly LSL_Types.LSLInteger PARCEL_FLAG_USE_LAND_PASS_LIST = 0x800; // parcel allows passes to be purchased public static readonly LSL_Types.LSLInteger PARCEL_FLAG_LOCAL_SOUND_ONLY = 0x8000; // parcel restricts spatialized sound to the parcel public static readonly LSL_Types.LSLInteger PARCEL_FLAG_RESTRICT_PUSHOBJECT = 0x200000; // parcel restricts llPushObject public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_GROUP_SCRIPTS = 0x2000000; // parcel allows scripts owned by group public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS = 0x4000000; // parcel allows group object creation public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY = 0x8000000; // parcel allows objects owned by any user to enter public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY = 0x10000000; // parcel allows with the same group to enter public static readonly LSL_Types.LSLInteger REGION_FLAG_ALLOW_DAMAGE = 0x1; // region is entirely damage enabled public static readonly LSL_Types.LSLInteger REGION_FLAG_FIXED_SUN = 0x10; // region has a fixed sun position public static readonly LSL_Types.LSLInteger REGION_FLAG_BLOCK_TERRAFORM = 0x40; // region terraforming disabled public static readonly LSL_Types.LSLInteger REGION_FLAG_SANDBOX = 0x100; // region is a sandbox public static readonly LSL_Types.LSLInteger REGION_FLAG_DISABLE_COLLISIONS = 0x1000; // region has disabled collisions public static readonly LSL_Types.LSLInteger REGION_FLAG_DISABLE_PHYSICS = 0x4000; // region has disabled physics public static readonly LSL_Types.LSLInteger REGION_FLAG_BLOCK_FLY = 0x80000; // region blocks flying public static readonly LSL_Types.LSLInteger REGION_FLAG_ALLOW_DIRECT_TELEPORT = 0x100000; // region allows direct teleports public static readonly LSL_Types.LSLInteger REGION_FLAG_RESTRICT_PUSHOBJECT = 0x400000; // region restricts llPushObject public static readonly LSL_Types.LSLInteger PAY_HIDE = new LSL_Types.LSLInteger(-1); public static readonly LSL_Types.LSLInteger PAY_DEFAULT = new LSL_Types.LSLInteger(-2); public static readonly LSL_Types.LSLInteger PAYMENT_INFO_ON_FILE = 0x1; public static readonly LSL_Types.LSLInteger PAYMENT_INFO_USED = 0x2; public static readonly LSL_Types.LSLString NULL_KEY = "00000000-0000-0000-0000-000000000000"; public static readonly LSL_Types.LSLString EOF = "\n\n\n"; public static readonly LSL_Types.LSLFloat PI = 3.1415926535897932384626433832795; public static readonly LSL_Types.LSLFloat TWO_PI = 6.283185307179586476925286766559; public static readonly LSL_Types.LSLFloat PI_BY_TWO = 1.5707963267948966192313216916398; public static readonly LSL_Types.LSLFloat DEG_TO_RAD = 0.01745329238f; public static readonly LSL_Types.LSLFloat RAD_TO_DEG = 57.29578f; public static readonly LSL_Types.LSLFloat SQRT2 = 1.4142135623730950488016887242097; public static readonly LSL_Types.LSLInteger STRING_TRIM_HEAD = 1; public static readonly LSL_Types.LSLInteger STRING_TRIM_TAIL = 2; public static readonly LSL_Types.LSLInteger STRING_TRIM = 3; public static readonly LSL_Types.LSLInteger LIST_STAT_RANGE = 0; public static readonly LSL_Types.LSLInteger LIST_STAT_MIN = 1; public static readonly LSL_Types.LSLInteger LIST_STAT_MAX = 2; public static readonly LSL_Types.LSLInteger LIST_STAT_MEAN = 3; public static readonly LSL_Types.LSLInteger LIST_STAT_MEDIAN = 4; public static readonly LSL_Types.LSLInteger LIST_STAT_STD_DEV = 5; public static readonly LSL_Types.LSLInteger LIST_STAT_SUM = 6; public static readonly LSL_Types.LSLInteger LIST_STAT_SUM_SQUARES = 7; public static readonly LSL_Types.LSLInteger LIST_STAT_NUM_COUNT = 8; public static readonly LSL_Types.LSLInteger LIST_STAT_GEOMETRIC_MEAN = 9; public static readonly LSL_Types.LSLInteger LIST_STAT_HARMONIC_MEAN = 100; //ParcelPrim Categories public static readonly LSL_Types.LSLInteger PARCEL_COUNT_TOTAL = 0; public static readonly LSL_Types.LSLInteger PARCEL_COUNT_OWNER = 1; public static readonly LSL_Types.LSLInteger PARCEL_COUNT_GROUP = 2; public static readonly LSL_Types.LSLInteger PARCEL_COUNT_OTHER = 3; public static readonly LSL_Types.LSLInteger PARCEL_COUNT_SELECTED = 4; public static readonly LSL_Types.LSLInteger PARCEL_COUNT_TEMP = 5; public static readonly LSL_Types.LSLInteger DEBUG_CHANNEL = 0x7FFFFFFF; public static readonly LSL_Types.LSLInteger PUBLIC_CHANNEL = 0x00000000; public static readonly LSL_Types.LSLInteger OBJECT_UNKNOWN_DETAIL = -1; public static readonly LSL_Types.LSLInteger OBJECT_NAME = 1; public static readonly LSL_Types.LSLInteger OBJECT_DESC = 2; public static readonly LSL_Types.LSLInteger OBJECT_POS = 3; public static readonly LSL_Types.LSLInteger OBJECT_ROT = 4; public static readonly LSL_Types.LSLInteger OBJECT_VELOCITY = 5; public static readonly LSL_Types.LSLInteger OBJECT_OWNER = 6; public static readonly LSL_Types.LSLInteger OBJECT_GROUP = 7; public static readonly LSL_Types.LSLInteger OBJECT_CREATOR = 8; public static readonly LSL_Types.LSLInteger OBJECT_RUNNING_SCRIPT_COUNT = 9; public static readonly LSL_Types.LSLInteger OBJECT_TOTAL_SCRIPT_COUNT = 10; public static readonly LSL_Types.LSLInteger OBJECT_SCRIPT_MEMORY = 11; public static readonly LSL_Types.LSLInteger OBJECT_SCRIPT_TIME = 12; public static readonly LSL_Types.LSLInteger OBJECT_PRIM_EQUIVALENCE = 13; public static readonly LSL_Types.LSLInteger OBJECT_SERVER_COST = 14; public static readonly LSL_Types.LSLInteger OBJECT_STREAMING_COST = 15; public static readonly LSL_Types.LSLInteger OBJECT_PHYSICS_COST = 16; public static readonly vector ZERO_VECTOR = new vector(0.0, 0.0, 0.0); public static readonly rotation ZERO_ROTATION = new rotation(0.0, 0.0, 0.0, 1.0); // constants for llSetCameraParams public static readonly LSL_Types.LSLInteger CAMERA_PITCH = 0; public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_OFFSET = 1; public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_OFFSET_X = 2; public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_OFFSET_Y = 3; public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_OFFSET_Z = 4; public static readonly LSL_Types.LSLInteger CAMERA_POSITION_LAG = 5; public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_LAG = 6; public static readonly LSL_Types.LSLInteger CAMERA_DISTANCE = 7; public static readonly LSL_Types.LSLInteger CAMERA_BEHINDNESS_ANGLE = 8; public static readonly LSL_Types.LSLInteger CAMERA_BEHINDNESS_LAG = 9; public static readonly LSL_Types.LSLInteger CAMERA_POSITION_THRESHOLD = 10; public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_THRESHOLD = 11; public static readonly LSL_Types.LSLInteger CAMERA_ACTIVE = 12; public static readonly LSL_Types.LSLInteger CAMERA_POSITION = 13; public static readonly LSL_Types.LSLInteger CAMERA_POSITION_X = 14; public static readonly LSL_Types.LSLInteger CAMERA_POSITION_Y = 15; public static readonly LSL_Types.LSLInteger CAMERA_POSITION_Z = 16; public static readonly LSL_Types.LSLInteger CAMERA_FOCUS = 17; public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_X = 18; public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_Y = 19; public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_Z = 20; public static readonly LSL_Types.LSLInteger CAMERA_POSITION_LOCKED = 21; public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_LOCKED = 22; // constants for llGetParcelDetails public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_NAME = 0; public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_DESC = 1; public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_OWNER = 2; public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_GROUP = 3; public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_AREA = 4; public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_ID = 5; public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_PRIVACY = 6; //Old name public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_SEE_AVATARS = 6; // constants for llSetClickAction public static readonly LSL_Types.LSLInteger CLICK_ACTION_NONE = 0; public static readonly LSL_Types.LSLInteger CLICK_ACTION_TOUCH = 0; public static readonly LSL_Types.LSLInteger CLICK_ACTION_SIT = 1; public static readonly LSL_Types.LSLInteger CLICK_ACTION_BUY = 2; public static readonly LSL_Types.LSLInteger CLICK_ACTION_PAY = 3; public static readonly LSL_Types.LSLInteger CLICK_ACTION_OPEN = 4; public static readonly LSL_Types.LSLInteger CLICK_ACTION_PLAY = 5; public static readonly LSL_Types.LSLInteger CLICK_ACTION_OPEN_MEDIA = 6; // constants for the llDetectedTouch* functions public static readonly LSL_Types.LSLInteger TOUCH_INVALID_FACE = -1; public static readonly vector TOUCH_INVALID_TEXCOORD = new vector(-1.0, -1.0, 0.0); public static readonly vector TOUCH_INVALID_VECTOR = ZERO_VECTOR; // Constants for default textures public static readonly LSL_Types.LSLString TEXTURE_BLANK = "5748decc-f629-461c-9a36-a35a221fe21f"; public static readonly LSL_Types.LSLString TEXTURE_DEFAULT = "89556747-24cb-43ed-920b-47caed15465f"; public static readonly LSL_Types.LSLString TEXTURE_PLYWOOD = "89556747-24cb-43ed-920b-47caed15465f"; public static readonly LSL_Types.LSLString TEXTURE_TRANSPARENT = "8dcd4a48-2d37-4909-9f78-f7a9eb4ef903"; public static readonly LSL_Types.LSLString TEXTURE_MEDIA = "8b5fec65-8d8d-9dc5-cda8-8fdf2716e361"; // Constants for osGetRegionStats public static readonly LSL_Types.LSLInteger STATS_TIME_DILATION = 0; public static readonly LSL_Types.LSLInteger STATS_SIM_FPS = 1; public static readonly LSL_Types.LSLInteger STATS_PHYSICS_FPS = 2; public static readonly LSL_Types.LSLInteger STATS_AGENT_UPDATES = 3; public static readonly LSL_Types.LSLInteger STATS_FRAME_MS = 4; public static readonly LSL_Types.LSLInteger STATS_NET_MS = 5; public static readonly LSL_Types.LSLInteger STATS_OTHER_MS = 6; public static readonly LSL_Types.LSLInteger STATS_PHYSICS_MS = 7; public static readonly LSL_Types.LSLInteger STATS_AGENT_MS = 8; public static readonly LSL_Types.LSLInteger STATS_IMAGE_MS = 9; public static readonly LSL_Types.LSLInteger STATS_SCRIPT_MS = 10; public static readonly LSL_Types.LSLInteger STATS_TOTAL_PRIMS = 11; public static readonly LSL_Types.LSLInteger STATS_ACTIVE_PRIMS = 12; public static readonly LSL_Types.LSLInteger STATS_ROOT_AGENTS = 13; public static readonly LSL_Types.LSLInteger STATS_CHILD_AGENTS = 14; public static readonly LSL_Types.LSLInteger STATS_ACTIVE_SCRIPTS = 15; public static readonly LSL_Types.LSLInteger STATS_SCRIPT_LPS = 16; //Doesn't work public static readonly LSL_Types.LSLInteger STATS_SCRIPT_EPS = 31; public static readonly LSL_Types.LSLInteger STATS_IN_PACKETS_PER_SECOND = 17; public static readonly LSL_Types.LSLInteger STATS_OUT_PACKETS_PER_SECOND = 18; public static readonly LSL_Types.LSLInteger STATS_PENDING_DOWNLOADS = 19; public static readonly LSL_Types.LSLInteger STATS_PENDING_UPLOADS = 20; public static readonly LSL_Types.LSLInteger STATS_UNACKED_BYTES = 24; public static readonly LSL_Types.LSLString URL_REQUEST_GRANTED = "URL_REQUEST_GRANTED"; public static readonly LSL_Types.LSLString URL_REQUEST_DENIED = "URL_REQUEST_DENIED"; public static readonly LSL_Types.LSLInteger PASS_IF_NOT_HANDLED = 0; public static readonly LSL_Types.LSLInteger PASS_ALWAYS = 1; public static readonly LSL_Types.LSLInteger PASS_NEVER = 2; public static readonly LSL_Types.LSLInteger RC_REJECT_TYPES = 2; public static readonly LSL_Types.LSLInteger RC_DATA_FLAGS = 4; public static readonly LSL_Types.LSLInteger RC_MAX_HITS = 8; public static readonly LSL_Types.LSLInteger RC_DETECT_PHANTOM = 16; public static readonly LSL_Types.LSLInteger RC_REJECT_AGENTS = 2; public static readonly LSL_Types.LSLInteger RC_REJECT_PHYSICAL = 4; public static readonly LSL_Types.LSLInteger RC_REJECT_NONPHYSICAL = 8; public static readonly LSL_Types.LSLInteger RC_REJECT_LAND = 16; public static readonly LSL_Types.LSLInteger RC_GET_NORMAL = 2; public static readonly LSL_Types.LSLInteger RC_GET_ROOT_KEY = 4; public static readonly LSL_Types.LSLInteger RC_GET_LINK_NUM = 8; public static readonly LSL_Types.LSLInteger RCERR_CAST_TIME_EXCEEDED = 1; public static readonly LSL_Types.LSLInteger PROFILE_NONE = 0; public static readonly LSL_Types.LSLInteger PROFILE_SCRIPT_MEMORY = 1; public static readonly LSL_Types.LSLInteger ESTATE_ACCESS_ALLOWED_AGENT_ADD = 0; public static readonly LSL_Types.LSLInteger ESTATE_ACCESS_ALLOWED_AGENT_REMOVE = 1; public static readonly LSL_Types.LSLInteger ESTATE_ACCESS_ALLOWED_GROUP_ADD = 2; public static readonly LSL_Types.LSLInteger ESTATE_ACCESS_ALLOWED_GROUP_REMOVE = 3; public static readonly LSL_Types.LSLInteger ESTATE_ACCESS_BANNED_AGENT_ADD = 4; public static readonly LSL_Types.LSLInteger ESTATE_ACCESS_BANNED_AGENT_REMOVE = 5; public static readonly LSL_Types.LSLInteger KFM_MODE = 2; public static readonly LSL_Types.LSLInteger KFM_LOOP = 4; public static readonly LSL_Types.LSLInteger KFM_REVERSE = 8; public static readonly LSL_Types.LSLInteger KFM_FORWARD = 16; public static readonly LSL_Types.LSLInteger KFM_PING_PONG = 32; public static readonly LSL_Types.LSLInteger KFM_TRANSLATION = 64; public static readonly LSL_Types.LSLInteger KFM_ROTATION = 128; public static readonly LSL_Types.LSLInteger KFM_COMMAND = 256; public static readonly LSL_Types.LSLInteger KFM_CMD_STOP = 512; public static readonly LSL_Types.LSLInteger KFM_CMD_PLAY = 1024; public static readonly LSL_Types.LSLInteger KFM_CMD_PAUSE = 2048; public static readonly LSL_Types.LSLInteger KFM_DATA = 4096; public static readonly LSL_Types.LSLInteger CHARACTER_DESIRED_SPEED = 1; public static readonly LSL_Types.LSLInteger CHARACTER_RADIUS = 2; public static readonly LSL_Types.LSLInteger CHARACTER_LENGTH = 3; public static readonly LSL_Types.LSLInteger CHARACTER_ORIENTATION = 4; public static readonly LSL_Types.LSLInteger TRAVERSAL_TYPE = 7; public static readonly LSL_Types.LSLInteger CHARACTER_TYPE = 8; public static readonly LSL_Types.LSLInteger CHARACTER_AVOIDANCE_MODE = 9; public static readonly LSL_Types.LSLInteger CHARACTER_MAX_ACCEL = 10; public static readonly LSL_Types.LSLInteger CHARACTER_MAX_DECEL = 11; public static readonly LSL_Types.LSLInteger CHARACTER_MAX_ANGULAR_SPEED = 12; public static readonly LSL_Types.LSLInteger CHARACTER_MAX_ANGULAR_ACCEL = 13; public static readonly LSL_Types.LSLInteger CHARACTER_TURN_SPEED_MULTIPLIER = 14; public static readonly LSL_Types.LSLInteger PURSUIT_OFFSET = 1; public static readonly LSL_Types.LSLInteger REQUIRE_LINE_OF_SIGHT = 2; public static readonly LSL_Types.LSLInteger PURSUIT_INTERCEPT = 4; public static readonly LSL_Types.LSLInteger PURSUIT_FUZZ_FACTOR = 8; public static readonly LSL_Types.LSLInteger CHARACTER_TYPE_NONE = 0; public static readonly LSL_Types.LSLInteger CHARACTER_TYPE_A = 1; public static readonly LSL_Types.LSLInteger CHARACTER_TYPE_B = 2; public static readonly LSL_Types.LSLInteger CHARACTER_TYPE_C = 3; public static readonly LSL_Types.LSLInteger CHARACTER_TYPE_D = 4; public static readonly LSL_Types.LSLInteger AVOID_CHARACTERS = 1; public static readonly LSL_Types.LSLInteger AVOID_DYNAMIC_OBSTACLES = 2; public static readonly LSL_Types.LSLInteger HORIZONTAL = 0; public static readonly LSL_Types.LSLInteger VERTICAL = 1; public static readonly LSL_Types.LSLInteger TRAVERSAL_TYPE_NONE = 1; public static readonly LSL_Types.LSLInteger TRAVERSAL_TYPE_FAST = 2; public static readonly LSL_Types.LSLInteger TRAVERSAL_TYPE_SLOW = 4; public static readonly LSL_Types.LSLInteger PU_SLOWDOWN_DISTANCE_REACHED = 0x00; public static readonly LSL_Types.LSLInteger PU_GOAL_REACHED = 0x01; public static readonly LSL_Types.LSLInteger PU_FAILURE_INVALID_START = 0x02; public static readonly LSL_Types.LSLInteger PU_FAILURE_INVALID_GOAL = 0x03; public static readonly LSL_Types.LSLInteger PU_FAILURE_UNREACHABLE = 0x04; public static readonly LSL_Types.LSLInteger PU_FAILURE_TARGET_GONE = 0x05; public static readonly LSL_Types.LSLInteger PU_FAILURE_NO_VALID_DESTINATION = 0x06; public static readonly LSL_Types.LSLInteger PU_EVADE_HIDDEN = 0x07; public static readonly LSL_Types.LSLInteger PU_EVADE_SPOTTED = 0x08; public static readonly LSL_Types.LSLInteger PU_FAILURE_NO_NAVMESH = 0x09; public static readonly LSL_Types.LSLInteger PU_FAILURE_OTHER = 0xF4240; public static readonly LSL_Types.LSLInteger FORCE_DIRECT_PATH = 1; public static readonly LSL_Types.LSLInteger CHARACTER_CMD_STOP = 0x0; public static readonly LSL_Types.LSLInteger CHARACTER_CMD_JUMP = 0x1; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: The boolean class serves as a wrapper for the primitive ** type boolean. ** ** ===========================================================*/ using System; using System.Globalization; using System.Diagnostics.Contracts; namespace System { // The Boolean class provides the // object representation of the boolean primitive type. public struct Boolean : IComparable, IComparable<Boolean>, IEquatable<Boolean>, IConvertible { // // Member Variables // private bool _value; // The true value. // internal const int True = 1; // The false value. // internal const int False = 0; // // Internal Constants are real consts for performance. // // The internal string representation of true. // internal const String TrueLiteral = "True"; // The internal string representation of false. // internal const String FalseLiteral = "False"; // // Public Constants // // The public string representation of true. // public static readonly String TrueString = TrueLiteral; // The public string representation of false. // public static readonly String FalseString = FalseLiteral; // // Overriden Instance Methods // /*=================================GetHashCode================================== **Args: None **Returns: 1 or 0 depending on whether this instance represents true or false. **Exceptions: None **Overriden From: Value ==============================================================================*/ // Provides a hash code for this instance. public override int GetHashCode() { return (_value) ? True : False; } /*===================================ToString=================================== **Args: None **Returns: "True" or "False" depending on the state of the boolean. **Exceptions: None. ==============================================================================*/ // Converts the boolean value of this instance to a String. public override String ToString() { if (false == _value) { return FalseLiteral; } return TrueLiteral; } String IConvertible.ToString(IFormatProvider provider) { return ToString(); } // Determines whether two Boolean objects are equal. public override bool Equals(Object obj) { //If it's not a boolean, we're definitely not equal if (!(obj is Boolean)) { return false; } return (_value == ((Boolean)obj)._value); } public bool Equals(Boolean obj) { return _value == obj; } // Compares this object to another object, returning an integer that // indicates the relationship. For booleans, false sorts before true. // null is considered to be less than any instance. // If object is not of type boolean, this method throws an ArgumentException. // // Returns a value less than zero if this object // int IComparable.CompareTo(Object obj) { if (obj == null) { return 1; } if (!(obj is Boolean)) { throw new ArgumentException(SR.Arg_MustBeBoolean); } if (_value == ((Boolean)obj)._value) { return 0; } else if (_value == false) { return -1; } return 1; } public int CompareTo(Boolean value) { if (_value == value) { return 0; } else if (_value == false) { return -1; } return 1; } // // Static Methods // // Determines whether a String represents true or false. // public static Boolean Parse(String value) { if (value == null) throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); Boolean result = false; if (!TryParse(value, out result)) { throw new FormatException(SR.Format_BadBoolean); } else { return result; } } // Determines whether a String represents true or false. // public static Boolean TryParse(String value, out Boolean result) { result = false; if (value == null) { return false; } // For perf reasons, let's first see if they're equal, then do the // trim to get rid of white space, and check again. if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if (FalseLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { result = false; return true; } // Special case: Trim whitespace as well as null characters. value = TrimWhiteSpaceAndNull(value); if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if (FalseLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { result = false; return true; } return false; } private static String TrimWhiteSpaceAndNull(String value) { int start = 0; int end = value.Length - 1; char nullChar = (char)0x0000; while (start < value.Length) { if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar) { break; } start++; } while (end >= start) { if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar) { break; } end--; } return value.Substring(start, end - start + 1); } // // IConvertible implementation // TypeCode IConvertible.GetTypeCode() { return TypeCode.Boolean; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return _value; } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Boolean", "Char")); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(_value); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Boolean", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System.IO; namespace CoralEngine { public enum Direction : int { Left, Right, Up, Down } public class Target { public Engine Engine; public string Entity = ""; public Target(Engine engine) { this.Engine = engine; } public void Trigger(Entity Sender) { Entity ent = Engine.World.FindEntitiy(Entity); if (ent != null) ent.Triggered(Sender); } public virtual void Serialize(BinaryWriter writer) { writer.Write(Entity); } public virtual void Deserialize(BinaryReader reader) { Entity = reader.ReadString(); } } public class Entity : ICloneable { public Engine Engine; public String Name = ""; public Vector2 Position; public Vector2 Velocity; public Vector2 Size; public int Z; public Direction Direction; private string _parent = ""; public string Parent { get { return _parent; } set { _parent = value; if (Engine != null) { Entity ent = Engine.World.FindEntitiy(value); if (ent == null) { _parent = ""; ParentOffset = new Vector2(0); } else ParentOffset = ent.Position - Position; } } } public Vector2 ParentOffset = new Vector2(0); public bool Solid; public bool Dynamic; public bool Template; public bool Visible = true; public float Friction = 0.15f; public bool MustSerialize = true; public object Clone() { return this.MemberwiseClone(); } public virtual void Triggered(Entity sender) { } public virtual void Initialize(World world) { this.Engine = world.Engine; world.Entities.Add(this); Entity ent = Engine.World.FindEntitiy(Parent); if (ent == null) { Parent = ""; ParentOffset = new Vector2(0); } else ParentOffset = ent.Position - Position; } public virtual Rectangle GetCollision() { return new Rectangle((int)Position.X - (int)Size.X / 2, (int)Position.Y - (int)Size.Y / 2, (int)Size.X, (int)Size.Y); } public virtual Rectangle GetRenderRectangle() { return GetCollision(); } public virtual void Update(GameTime gameTime) { if (Dynamic) { Velocity += Engine.World.Gravity / 100; Velocity.X *= 0.99f; Rectangle Future; Entity CollideWith; Future = GetCollision(); Future.X += (int)Velocity.X; CollideWith = Engine.World.CollidesWithSolid(this, Future); if (CollideWith == null) Position.X += (int)Velocity.X; else { if (Position.X < CollideWith.Position.X - CollideWith.Size.X / 2) Position.X = CollideWith.Position.X - CollideWith.Size.X; else Position.X = CollideWith.Position.X - CollideWith.Size.X; Velocity.X = 0; } Future = GetCollision(); Future.Y += (int)Velocity.Y; CollideWith = Engine.World.CollidesWithSolid(this, Future); if (CollideWith == null) Position.Y += (int)Velocity.Y; else { if (Position.Y < CollideWith.Position.Y - CollideWith.Size.Y / 2) { Position.Y = CollideWith.Position.Y - CollideWith.Size.Y; Velocity.X *= 1f - CollideWith.Friction; } else Position.Y = CollideWith.Position.Y + CollideWith.Size.Y; Velocity.Y = 0; } } if (Parent != "") { Entity parent = Engine.World.FindEntitiy(Parent); Position = parent.Position - ParentOffset; } } public virtual void Render(SpriteBatch spriteBatch) { if (Engine.RenderDebug) { Rectangle rect = GetCollision(); Color renderColor = Visible ? Color.Red : Color.Blue; // Cross spriteBatch.Draw(EngineContent.Textures.Pixel, new Rectangle(rect.X + rect.Width / 2, rect.Y, 1, rect.Height), renderColor); spriteBatch.Draw(EngineContent.Textures.Pixel, new Rectangle(rect.X, rect.Y + rect.Height / 2, rect.Width, 1), renderColor); // Top left spriteBatch.Draw(EngineContent.Textures.Pixel, new Rectangle(rect.X, rect.Y, 16, 1), renderColor); spriteBatch.Draw(EngineContent.Textures.Pixel, new Rectangle(rect.X, rect.Y, 1, 16), renderColor); // Top right spriteBatch.Draw(EngineContent.Textures.Pixel, new Rectangle(rect.X + rect.Width - 16, rect.Y, 16, 1), renderColor); spriteBatch.Draw(EngineContent.Textures.Pixel, new Rectangle(rect.X + rect.Width - 1, rect.Y, 1, 16), renderColor); // Bottom left spriteBatch.Draw(EngineContent.Textures.Pixel, new Rectangle(rect.X, rect.Y + rect.Height - 1, 16, 1), renderColor); spriteBatch.Draw(EngineContent.Textures.Pixel, new Rectangle(rect.X, rect.Y + rect.Height - 16, 1, 16), renderColor); // Bottom right spriteBatch.Draw(EngineContent.Textures.Pixel, new Rectangle(rect.X + rect.Width - 16, rect.Y + rect.Height - 1, 16, 1), renderColor); spriteBatch.Draw(EngineContent.Textures.Pixel, new Rectangle(rect.X + rect.Width - 1, rect.Y + rect.Height - 16, 1, 16), renderColor); // Name spriteBatch.DrawString(EngineContent.Fonts.Calibri12, Name, Position + new Vector2(6), renderColor); } } public virtual void Serialize(BinaryWriter writer) { if (MustSerialize) { writer.Write(Name); writer.Write(Position.X); writer.Write(Position.Y); writer.Write(Velocity.X); writer.Write(Velocity.Y); writer.Write(Size.X); writer.Write(Size.Y); writer.Write(Z); writer.Write((int)Direction); writer.Write(Parent); writer.Write(Solid); writer.Write(Dynamic); writer.Write(Template); writer.Write(Visible); writer.Write(Friction); } } public virtual void Deserialize(BinaryReader reader) { if (MustSerialize) { Name = reader.ReadString(); Position = new Vector2(reader.ReadSingle(), reader.ReadSingle()); Velocity = new Vector2(reader.ReadSingle(), reader.ReadSingle()); Size = new Vector2(reader.ReadSingle(), reader.ReadSingle()); Z = reader.ReadInt32(); Direction = (Direction)reader.ReadInt32(); Parent = reader.ReadString(); Solid = reader.ReadBoolean(); Dynamic = reader.ReadBoolean(); Template = reader.ReadBoolean(); Visible = reader.ReadBoolean(); Friction = reader.ReadSingle(); } } public virtual void Preload() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.EntityFrameworkCore; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.Deleting { public sealed class AtomicDeleteResourceTests : IClassFixture<IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext>> { private readonly IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> _testContext; private readonly OperationsFakers _fakers = new(); public AtomicDeleteResourceTests(IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> testContext) { _testContext = testContext; testContext.UseController<OperationsController>(); } [Fact] public async Task Can_delete_existing_resource() { // Arrange Performer existingPerformer = _fakers.Performer.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Performers.Add(existingPerformer); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new[] { new { op = "remove", @ref = new { type = "performers", id = existingPerformer.StringId } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Performer performerInDatabase = await dbContext.Performers.FirstWithIdOrDefaultAsync(existingPerformer.Id); performerInDatabase.Should().BeNull(); }); } [Fact] public async Task Can_delete_existing_resources() { // Arrange const int elementCount = 5; List<MusicTrack> existingTracks = _fakers.MusicTrack.Generate(elementCount); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<MusicTrack>(); dbContext.MusicTracks.AddRange(existingTracks); await dbContext.SaveChangesAsync(); }); var operationElements = new List<object>(elementCount); for (int index = 0; index < elementCount; index++) { operationElements.Add(new { op = "remove", @ref = new { type = "musicTracks", id = existingTracks[index].StringId } }); } var requestBody = new { atomic__operations = operationElements }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { List<MusicTrack> tracksInDatabase = await dbContext.MusicTracks.ToListAsync(); tracksInDatabase.Should().BeEmpty(); }); } [Fact] public async Task Can_delete_resource_with_OneToOne_relationship_from_principal_side() { // Arrange Lyric existingLyric = _fakers.Lyric.Generate(); existingLyric.Track = _fakers.MusicTrack.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Lyrics.Add(existingLyric); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new[] { new { op = "remove", @ref = new { type = "lyrics", id = existingLyric.StringId } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Lyric lyricsInDatabase = await dbContext.Lyrics.FirstWithIdOrDefaultAsync(existingLyric.Id); lyricsInDatabase.Should().BeNull(); MusicTrack trackInDatabase = await dbContext.MusicTracks.FirstWithIdAsync(existingLyric.Track.Id); trackInDatabase.Lyric.Should().BeNull(); }); } [Fact] public async Task Can_delete_resource_with_OneToOne_relationship_from_dependent_side() { // Arrange MusicTrack existingTrack = _fakers.MusicTrack.Generate(); existingTrack.Lyric = _fakers.Lyric.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.MusicTracks.Add(existingTrack); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new[] { new { op = "remove", @ref = new { type = "musicTracks", id = existingTrack.StringId } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { MusicTrack tracksInDatabase = await dbContext.MusicTracks.FirstWithIdOrDefaultAsync(existingTrack.Id); tracksInDatabase.Should().BeNull(); Lyric lyricInDatabase = await dbContext.Lyrics.FirstWithIdAsync(existingTrack.Lyric.Id); lyricInDatabase.Track.Should().BeNull(); }); } [Fact] public async Task Can_delete_existing_resource_with_OneToMany_relationship() { // Arrange MusicTrack existingTrack = _fakers.MusicTrack.Generate(); existingTrack.Performers = _fakers.Performer.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.MusicTracks.Add(existingTrack); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new[] { new { op = "remove", @ref = new { type = "musicTracks", id = existingTrack.StringId } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { MusicTrack trackInDatabase = await dbContext.MusicTracks.FirstWithIdOrDefaultAsync(existingTrack.Id); trackInDatabase.Should().BeNull(); List<Performer> performersInDatabase = await dbContext.Performers.ToListAsync(); performersInDatabase.Should().ContainSingle(userAccount => userAccount.Id == existingTrack.Performers.ElementAt(0).Id); performersInDatabase.Should().ContainSingle(userAccount => userAccount.Id == existingTrack.Performers.ElementAt(1).Id); }); } [Fact] public async Task Can_delete_existing_resource_with_ManyToMany_relationship() { // Arrange Playlist existingPlaylist = _fakers.Playlist.Generate(); existingPlaylist.Tracks = _fakers.MusicTrack.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Playlists.Add(existingPlaylist); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new[] { new { op = "remove", @ref = new { type = "playlists", id = existingPlaylist.StringId } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Playlist playlistInDatabase = await dbContext.Playlists.FirstWithIdOrDefaultAsync(existingPlaylist.Id); playlistInDatabase.Should().BeNull(); MusicTrack trackInDatabase = await dbContext.MusicTracks.FirstWithIdOrDefaultAsync(existingPlaylist.Tracks[0].Id); trackInDatabase.Should().NotBeNull(); }); } [Fact] public async Task Cannot_delete_resource_for_href_element() { // Arrange var requestBody = new { atomic__operations = new[] { new { op = "remove", href = "/api/v1/musicTracks/1" } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Usage of the 'href' element is not supported."); error.Detail.Should().BeNull(); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } [Fact] public async Task Cannot_delete_resource_for_missing_ref_element() { // Arrange var requestBody = new { atomic__operations = new[] { new { op = "remove" } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: The 'ref' element is required."); error.Detail.Should().BeNull(); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } [Fact] public async Task Cannot_delete_resource_for_missing_type() { // Arrange var requestBody = new { atomic__operations = new[] { new { op = "remove", @ref = new { id = Unknown.StringId.Int32 } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: The 'ref.type' element is required."); error.Detail.Should().BeNull(); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } [Fact] public async Task Cannot_delete_resource_for_unknown_type() { // Arrange var requestBody = new { atomic__operations = new[] { new { op = "remove", @ref = new { type = Unknown.ResourceType, id = Unknown.StringId.Int32 } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Request body includes unknown resource type."); error.Detail.Should().Be($"Resource type '{Unknown.ResourceType}' does not exist."); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } [Fact] public async Task Cannot_delete_resource_for_missing_ID() { // Arrange var requestBody = new { atomic__operations = new[] { new { op = "remove", @ref = new { type = "musicTracks" } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: The 'ref.id' or 'ref.lid' element is required."); error.Detail.Should().BeNull(); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } [Fact] public async Task Cannot_delete_resource_for_unknown_ID() { // Arrange string performerId = Unknown.StringId.For<Performer, int>(); var requestBody = new { atomic__operations = new[] { new { op = "remove", @ref = new { type = "performers", id = performerId } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'performers' with ID '{performerId}' does not exist."); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } [Fact] public async Task Cannot_delete_resource_for_incompatible_ID() { // Arrange string guid = Unknown.StringId.Guid; var requestBody = new { atomic__operations = new[] { new { op = "remove", @ref = new { type = "playlists", id = guid } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body."); error.Detail.Should().Be($"Failed to convert '{guid}' of type 'String' to type 'Int64'."); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } [Fact] public async Task Cannot_delete_resource_for_ID_and_local_ID() { // Arrange var requestBody = new { atomic__operations = new[] { new { op = "remove", @ref = new { type = "musicTracks", id = Unknown.StringId.For<MusicTrack, Guid>(), lid = "local-1" } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: The 'ref.id' or 'ref.lid' element is required."); error.Detail.Should().BeNull(); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } } }
using Newtonsoft.Json; using SteamKit2; using System; using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Net; namespace SteamTrade.TradeOffer { public class OfferSession { private static readonly CookieContainer Cookies = new CookieContainer(); public string SessionId { get; private set; } public string SteamLogin { get; private set; } public string SteamLoginSecure { get; private set; } private TradeOfferWebAPI WebApi { get; set; } internal JsonSerializerSettings JsonSerializerSettings { get; set; } internal const string SendUrl = "https://steamcommunity.com/tradeoffer/new/send"; public OfferSession(string sessionId, string token, string tokensecure, TradeOfferWebAPI webApi) { Cookies.Add(new Cookie("sessionid", sessionId, String.Empty, "steamcommunity.com")); Cookies.Add(new Cookie("steamLogin", token, String.Empty, "steamcommunity.com")); Cookies.Add(new Cookie("steamLoginSecure", tokensecure, String.Empty, "steamcommunity.com")); SessionId = sessionId; SteamLogin = token; SteamLoginSecure = tokensecure; this.WebApi = webApi; JsonSerializerSettings = new JsonSerializerSettings(); JsonSerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None; JsonSerializerSettings.Formatting = Formatting.None; } public string Fetch(string url, string method, NameValueCollection data = null, bool ajax = false, string referer = "") { try { HttpWebResponse response = SteamWeb.Request(url, method, data, Cookies, ajax, referer); return ReadWebStream(response); } catch (WebException we) { Debug.WriteLine(we); return ReadWebStream(we.Response); } } private static string ReadWebStream(WebResponse webResponse) { using (var stream = webResponse.GetResponseStream()) { if (stream != null) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } return null; } public bool Accept(string tradeOfferId, out string tradeId) { tradeId = ""; var data = new NameValueCollection(); data.Add("sessionid", SessionId); data.Add("serverid", "1"); data.Add("tradeofferid", tradeOfferId); string url = string.Format("https://steamcommunity.com/tradeoffer/{0}/accept", tradeOfferId); string referer = string.Format("https://steamcommunity.com/tradeoffer/{0}/", tradeOfferId); string resp = Fetch(url, "POST", data, false, referer); if (!String.IsNullOrEmpty(resp)) { try { var result = JsonConvert.DeserializeObject<TradeOfferAcceptResponse>(resp); if (!String.IsNullOrEmpty(result.TradeId)) { tradeId = result.TradeId; return true; } //todo: log the error Debug.WriteLine(result.TradeError); } catch (JsonException jsex) { Debug.WriteLine(jsex); } } else { var state = WebApi.GetOfferState(tradeOfferId); if (state == TradeOfferState.TradeOfferStateAccepted) { return true; } } return false; } public bool Decline(string tradeOfferId) { var data = new NameValueCollection(); data.Add("sessionid", SessionId); data.Add("serverid", "1"); data.Add("tradeofferid", tradeOfferId); string url = string.Format("https://steamcommunity.com/tradeoffer/{0}/decline", tradeOfferId); //should be http://steamcommunity.com/{0}/{1}/tradeoffers - id/profile persona/id64 ideally string referer = string.Format("https://steamcommunity.com/tradeoffer/{0}/", tradeOfferId); var resp = Fetch(url, "POST", data, false, referer); if (!String.IsNullOrEmpty(resp)) { try { var json = JsonConvert.DeserializeObject<NewTradeOfferResponse>(resp); if (json.TradeOfferId != null && json.TradeOfferId == tradeOfferId) { return true; } } catch (JsonException jsex) { Debug.WriteLine(jsex); } } else { var state = WebApi.GetOfferState(tradeOfferId); if (state == TradeOfferState.TradeOfferStateDeclined) { return true; } } return false; } public bool Cancel(string tradeOfferId) { var data = new NameValueCollection(); data.Add("sessionid", SessionId); data.Add("serverid", "1"); string url = string.Format("https://steamcommunity.com/tradeoffer/{0}/cancel", tradeOfferId); //should be http://steamcommunity.com/{0}/{1}/tradeoffers/sent/ - id/profile persona/id64 ideally string referer = string.Format("https://steamcommunity.com/tradeoffer/{0}/", tradeOfferId); var resp = Fetch(url, "POST", data, false, referer); if (!String.IsNullOrEmpty(resp)) { try { var json = JsonConvert.DeserializeObject<NewTradeOfferResponse>(resp); if (json.TradeOfferId != null && json.TradeOfferId == tradeOfferId) { return true; } } catch (JsonException jsex) { Debug.WriteLine(jsex); } } else { var state = WebApi.GetOfferState(tradeOfferId); if (state == TradeOfferState.TradeOfferStateCanceled) { return true; } } return false; } /// <summary> /// Creates a new counter offer /// </summary> /// <param name="message">A message to include with the trade offer</param> /// <param name="otherSteamId">The SteamID of the partner we are trading with</param> /// <param name="status">The list of items we and they are going to trade</param> /// <param name="newTradeOfferId">The trade offer Id that will be created if successful</param> /// <param name="tradeOfferId">The trade offer Id of the offer being countered</param> /// <returns></returns> public bool CounterOffer(string message, SteamID otherSteamId, TradeOffer.TradeStatus status, out string newTradeOfferId, string tradeOfferId) { if (String.IsNullOrEmpty(tradeOfferId)) { throw new ArgumentNullException("tradeOfferId", "Trade Offer Id must be set for counter offers."); } var data = new NameValueCollection(); data.Add("sessionid", SessionId); data.Add("serverid", "1"); data.Add("partner", otherSteamId.ConvertToUInt64().ToString()); data.Add("tradeoffermessage", message); data.Add("json_tradeoffer", JsonConvert.SerializeObject(status, JsonSerializerSettings)); data.Add("tradeofferid_countered", tradeOfferId); data.Add("trade_offer_create_params", "{}"); string referer = string.Format("https://steamcommunity.com/tradeoffer/{0}/", tradeOfferId); if (!Request(SendUrl, data, referer, tradeOfferId, out newTradeOfferId)) { var state = WebApi.GetOfferState(tradeOfferId); if (state == TradeOfferState.TradeOfferStateCountered) { return true; } return false; } return true; } /// <summary> /// Creates a new trade offer /// </summary> /// <param name="message">A message to include with the trade offer</param> /// <param name="otherSteamId">The SteamID of the partner we are trading with</param> /// <param name="status">The list of items we and they are going to trade</param> /// <param name="newTradeOfferId">The trade offer Id that will be created if successful</param> /// <returns>True if successfully returns a newTradeOfferId, else false</returns> public bool SendTradeOffer(string message, SteamID otherSteamId, TradeOffer.TradeStatus status, out string newTradeOfferId) { var data = new NameValueCollection(); data.Add("sessionid", SessionId); data.Add("serverid", "1"); data.Add("partner", otherSteamId.ConvertToUInt64().ToString()); data.Add("tradeoffermessage", message); data.Add("json_tradeoffer", JsonConvert.SerializeObject(status, JsonSerializerSettings)); data.Add("trade_offer_create_params", "{}"); string referer = string.Format("https://steamcommunity.com/tradeoffer/new/?partner={0}", otherSteamId.AccountID); return Request(SendUrl, data, referer, null, out newTradeOfferId); } /// <summary> /// Creates a new trade offer with a token /// </summary> /// <param name="message">A message to include with the trade offer</param> /// <param name="otherSteamId">The SteamID of the partner we are trading with</param> /// <param name="status">The list of items we and they are going to trade</param> /// <param name="token">The token of the partner we are trading with</param> /// <param name="newTradeOfferId">The trade offer Id that will be created if successful</param> /// <returns>True if successfully returns a newTradeOfferId, else false</returns> public bool SendTradeOfferWithToken(string message, SteamID otherSteamId, TradeOffer.TradeStatus status, string token, out string newTradeOfferId) { if (String.IsNullOrEmpty(token)) { throw new ArgumentNullException("token", "Partner trade offer token is missing"); } var offerToken = new OfferAccessToken() { TradeOfferAccessToken = token }; var data = new NameValueCollection(); data.Add("sessionid", SessionId); data.Add("serverid", "1"); data.Add("partner", otherSteamId.ConvertToUInt64().ToString()); data.Add("tradeoffermessage", message); data.Add("json_tradeoffer", JsonConvert.SerializeObject(status, JsonSerializerSettings)); data.Add("trade_offer_create_params", JsonConvert.SerializeObject(offerToken, JsonSerializerSettings)); string referer = string.Format("https://steamcommunity.com/tradeoffer/new/?partner={0}&token={1}", otherSteamId.AccountID, token); return Request(SendUrl, data, referer, null, out newTradeOfferId); } internal bool Request(string url, NameValueCollection data, string referer, string tradeOfferId, out string newTradeOfferId) { newTradeOfferId = ""; string resp = Fetch(url, "POST", data, false, referer); if (!String.IsNullOrEmpty(resp)) { try { var offerResponse = JsonConvert.DeserializeObject<NewTradeOfferResponse>(resp); if (!String.IsNullOrEmpty(offerResponse.TradeOfferId)) { newTradeOfferId = offerResponse.TradeOfferId; return true; } else { //todo: log possible error Debug.WriteLine(offerResponse.TradeError); } } catch (JsonException jsex) { Debug.WriteLine(jsex); } } return false; } } public class NewTradeOfferResponse { [JsonProperty("tradeofferid")] public string TradeOfferId { get; set; } [JsonProperty("strError")] public string TradeError { get; set; } } public class OfferAccessToken { [JsonProperty("trade_offer_access_token")] public string TradeOfferAccessToken { get; set; } } public class TradeOfferAcceptResponse { [JsonProperty("tradeid")] public string TradeId { get; set; } [JsonProperty("strError")] public string TradeError { get; set; } public TradeOfferAcceptResponse() { TradeId = String.Empty; TradeError = String.Empty; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Relational.Migrations.Infrastructure; using WebApplication.v5.WebApplication.Models; namespace WebApplication.v5.WebApplication.Migrations { [ContextType(typeof(ApplicationDbContext))] partial class CreateIdentitySchema { public override string Id { get { return "00000000000000_CreateIdentitySchema"; } } public override string ProductVersion { get { return "7.0.0-beta5"; } } public override void BuildTargetModel(ModelBuilder builder) { builder .Annotation("SqlServer:ValueGeneration", "Identity"); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 1); b.Property<string>("Name") .Annotation("OriginalValueIndex", 2); b.Property<string>("NormalizedName") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoles"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity) .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 1); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 2); b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoleClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity) .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 1); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 2); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUserClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<string>("ProviderKey") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 1); b.Property<string>("ProviderDisplayName") .Annotation("OriginalValueIndex", 2); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("LoginProvider", "ProviderKey"); b.Annotation("Relational:TableName", "AspNetUserLogins"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId") .Annotation("OriginalValueIndex", 0); b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 1); b.Key("UserId", "RoleId"); b.Annotation("Relational:TableName", "AspNetUserRoles"); }); builder.Entity("WebApplication.v5.WebApplication.Models.ApplicationUser", b => { b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<int>("AccessFailedCount") .Annotation("OriginalValueIndex", 1); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 2); b.Property<string>("Email") .Annotation("OriginalValueIndex", 3); b.Property<bool>("EmailConfirmed") .Annotation("OriginalValueIndex", 4); b.Property<bool>("LockoutEnabled") .Annotation("OriginalValueIndex", 5); b.Property<DateTimeOffset?>("LockoutEnd") .Annotation("OriginalValueIndex", 6); b.Property<string>("NormalizedEmail") .Annotation("OriginalValueIndex", 7); b.Property<string>("NormalizedUserName") .Annotation("OriginalValueIndex", 8); b.Property<string>("PasswordHash") .Annotation("OriginalValueIndex", 9); b.Property<string>("PhoneNumber") .Annotation("OriginalValueIndex", 10); b.Property<bool>("PhoneNumberConfirmed") .Annotation("OriginalValueIndex", 11); b.Property<string>("SecurityStamp") .Annotation("OriginalValueIndex", 12); b.Property<bool>("TwoFactorEnabled") .Annotation("OriginalValueIndex", 13); b.Property<string>("UserName") .Annotation("OriginalValueIndex", 14); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUsers"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Reference("WebApplication.v5.WebApplication.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Reference("WebApplication.v5.WebApplication.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); b.Reference("WebApplication.v5.WebApplication.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); } } }
/* * 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 Apache.Ignite.Core.Impl.Compute { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Memory; /// <summary> /// Holder for user-provided compute job. /// </summary> internal class ComputeJobHolder : IBinaryWriteAware { /** Actual job. */ private readonly IComputeJob _job; /** Owning grid. */ private readonly IIgniteInternal _ignite; /** Result (set for local jobs only). */ private volatile ComputeJobResultImpl _jobRes; /// <summary> /// Default ctor for marshalling. /// </summary> /// <param name="reader"></param> public ComputeJobHolder(BinaryReader reader) { Debug.Assert(reader != null); _ignite = reader.Marshaller.Ignite; _job = reader.ReadObject<IComputeJob>(); } /// <summary> /// Constructor. /// </summary> /// <param name="grid">Grid.</param> /// <param name="job">Job.</param> public ComputeJobHolder(IIgniteInternal grid, IComputeJob job) { Debug.Assert(grid != null); Debug.Assert(job != null); _ignite = grid; _job = job; } /// <summary> /// Executes local job. /// </summary> /// <param name="cancel">Cancel flag.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User code can throw any exception type.")] public void ExecuteLocal(bool cancel) { ComputeRunner.InjectResources(_ignite, _job); var nodeId = _ignite.GetIgnite().GetCluster().GetLocalNode().Id; try { var res = Execute0(cancel); _jobRes = new ComputeJobResultImpl(res, null, _job, nodeId, cancel); } catch (Exception e) { var ex = new IgniteException( "Compute job has failed on local node, examine InnerException for details.", e); _jobRes = new ComputeJobResultImpl(null, ex, _job, nodeId, cancel); } } /// <summary> /// Execute job serializing result to the stream. /// </summary> /// <param name="cancel">Whether the job must be cancelled.</param> /// <param name="stream">Stream.</param> public void ExecuteRemote(PlatformMemoryStream stream, bool cancel) { ComputeRunner.ExecuteJobAndWriteResults(_ignite, stream, _job, _ => Execute0(cancel)); } /// <summary> /// Cancel the job. /// </summary> public void Cancel() { _job.Cancel(); } /// <summary> /// Serialize the job to the stream. /// </summary> /// <param name="stream">Stream.</param> /// <returns>True if successfull.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User job can throw any exception")] internal bool Serialize(IBinaryStream stream) { BinaryWriter writer = _ignite.Marshaller.StartMarshal(stream); try { writer.Write(this); return true; } catch (Exception e) { writer.WriteString("Failed to marshal job [job=" + _job + ", errType=" + e.GetType().Name + ", errMsg=" + e.Message + ']'); return false; } finally { // 4. Process metadata. _ignite.Marshaller.FinishMarshal(writer); } } /// <summary> /// Job. /// </summary> internal IComputeJob Job { get { return _job; } } /// <summary> /// Job result. /// </summary> internal ComputeJobResultImpl JobResult { get { return _jobRes; } } /// <summary> /// Internal job execution routine. /// </summary> /// <param name="cancel">Cancel flag.</param> private object Execute0(bool cancel) { if (cancel) { _job.Cancel(); } return _job.Execute(); } /** <inheritDoc /> */ public void WriteBinary(IBinaryWriter writer) { BinaryWriter writer0 = (BinaryWriter) writer.GetRawWriter(); writer0.WriteObjectDetached(_job); } /// <summary> /// Create job instance. /// </summary> /// <param name="grid">Grid.</param> /// <param name="stream">Stream.</param> /// <returns></returns> internal static ComputeJobHolder CreateJob(Ignite grid, IBinaryStream stream) { try { return grid.Marshaller.StartUnmarshal(stream).ReadObject<ComputeJobHolder>(); } catch (Exception e) { throw new IgniteException("Failed to deserialize the job [errType=" + e.GetType().Name + ", errMsg=" + e.Message + ']'); } } } }
// // Queue.cs // // Author: // Chris Toshok <toshok@ximian.com> // Alexander Hixon <hixon.alexander@mediati.org> // // Copyright (C) 2005-2008 Novell, 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 System.IO; using System.Text; using System.Security.Cryptography; using System.Collections.Generic; using System.Web; using System.Xml; using Hyena; using Banshee.Base; using Banshee.Collection; using Banshee.ServiceStack; using Banshee.Sources; using Lastfm; using Lastfm.Data; namespace Banshee.Lastfm.Audioscrobbler { class Queue : IQueue { internal class QueuedTrack { private static DateTime epoch = DateTimeUtil.LocalUnixEpoch.ToUniversalTime (); public QueuedTrack (TrackInfo track, DateTime start_time) { this.artist = track.ArtistName; this.album = track.AlbumTitle; this.title = track.TrackTitle; this.track_number = (int) track.TrackNumber; this.duration = (int) track.Duration.TotalSeconds; // Idealy would use Hyena's DateTimeUtil, but it is broken since the "unix epoch" it uses is // not UTC, so depending on whether jan 1 1970 was in day-light savings and whether the user's // current timezone is in DLS, we'll be an hour off. this.start_time = (long) (start_time.ToUniversalTime () - epoch).TotalSeconds; // TODO //this.musicbrainzid = track.MusicBrainzId; this.musicbrainzid = ""; // set trackauth value, otherwise empty string is default if (track is ILastfmInfo) { this.track_auth = (track as ILastfmInfo).TrackAuth; } } public QueuedTrack (string artist, string album, string title, int track_number, int duration, long start_time, string musicbrainzid, string track_auth) { this.artist = artist; this.album = album; this.title = title; this.track_number = track_number; this.duration = duration; this.start_time = start_time; this.musicbrainzid = musicbrainzid; this.track_auth = track_auth; } public long StartTime { get { return start_time; } } public string Artist { get { return artist; } } public string Album { get { return album; } } public string Title { get { return title; } } public int TrackNumber { get { return track_number; } } public int Duration { get { return duration; } } public string MusicBrainzId { get { return musicbrainzid; } } public string TrackAuth { get { return track_auth; } } string artist; string album; string title; int track_number; int duration; string musicbrainzid; long start_time; string track_auth = String.Empty; } List<QueuedTrack> queue; string xml_path; bool dirty; public event EventHandler TrackAdded; public Queue () { string xmlfilepath = Path.Combine (Hyena.Paths.ExtensionCacheRoot, "last.fm"); xml_path = Path.Combine (xmlfilepath, "audioscrobbler-queue.xml"); queue = new List<QueuedTrack> (); if (!Directory.Exists(xmlfilepath)) { Directory.CreateDirectory (xmlfilepath); } Load (); } public void Save () { if (!dirty) return; XmlTextWriter writer = new XmlTextWriter (xml_path, Encoding.Default); writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.IndentChar = ' '; writer.WriteStartDocument (true); writer.WriteStartElement ("AudioscrobblerQueue"); foreach (QueuedTrack track in queue) { writer.WriteStartElement ("QueuedTrack"); writer.WriteElementString ("Artist", track.Artist); writer.WriteElementString ("Album", track.Album); writer.WriteElementString ("Title", track.Title); writer.WriteElementString ("TrackNumber", track.TrackNumber.ToString()); writer.WriteElementString ("Duration", track.Duration.ToString()); writer.WriteElementString ("StartTime", track.StartTime.ToString()); writer.WriteElementString ("MusicBrainzId", track.MusicBrainzId); writer.WriteElementString ("TrackAuth", track.TrackAuth); writer.WriteEndElement (); // Track } writer.WriteEndElement (); // AudioscrobblerQueue writer.WriteEndDocument (); writer.Close (); } public void Load () { queue.Clear (); try { string query = "//AudioscrobblerQueue/QueuedTrack"; XmlDocument doc = new XmlDocument (); doc.Load (xml_path); XmlNodeList nodes = doc.SelectNodes (query); foreach (XmlNode node in nodes) { string artist = ""; string album = ""; string title = ""; int track_number = 0; int duration = 0; long start_time = 0; string musicbrainzid = ""; string track_auth = ""; foreach (XmlNode child in node.ChildNodes) { if (child.Name == "Artist" && child.ChildNodes.Count != 0) { artist = child.ChildNodes [0].Value; } else if (child.Name == "Album" && child.ChildNodes.Count != 0) { album = child.ChildNodes [0].Value; } else if (child.Name == "Title" && child.ChildNodes.Count != 0) { title = child.ChildNodes [0].Value; } else if (child.Name == "TrackNumber" && child.ChildNodes.Count != 0) { track_number = Convert.ToInt32 (child.ChildNodes [0].Value); } else if (child.Name == "Duration" && child.ChildNodes.Count != 0) { duration = Convert.ToInt32 (child.ChildNodes [0].Value); } else if (child.Name == "StartTime" && child.ChildNodes.Count != 0) { start_time = Convert.ToInt64 (child.ChildNodes [0].Value); } else if (child.Name == "MusicBrainzId" && child.ChildNodes.Count != 0) { musicbrainzid = child.ChildNodes [0].Value; } else if (child.Name == "TrackAuth" && child.ChildNodes.Count != 0) { track_auth = child.ChildNodes [0].Value; } } queue.Add (new QueuedTrack (artist, album, title, track_number, duration, start_time, musicbrainzid, track_auth)); } } catch { } } public string GetTransmitInfo (out int numtracks) { StringBuilder sb = new StringBuilder (); int i; for (i = 0; i < queue.Count; i ++) { /* Last.fm 1.2 can handle up to 50 songs in one request */ if (i == 49) break; QueuedTrack track = (QueuedTrack) queue[i]; string str_track_number = String.Empty; if (track.TrackNumber != 0) str_track_number = track.TrackNumber.ToString(); string source = "P"; /* chosen by user */ if (track.TrackAuth.Length != 0) { // from last.fm source = "L" + track.TrackAuth; } sb.AppendFormat ( "&a[{9}]={0}&t[{9}]={1}&i[{9}]={2}&o[{9}]={3}&r[{9}]={4}&l[{9}]={5}&b[{9}]={6}&n[{9}]={7}&m[{9}]={8}", HttpUtility.UrlEncode (track.Artist), HttpUtility.UrlEncode (track.Title), track.StartTime.ToString (), source, "" /* rating: L/B/S */, track.Duration.ToString (), HttpUtility.UrlEncode (track.Album), str_track_number, track.MusicBrainzId, i); } numtracks = i; return sb.ToString (); } public void Add (object track, DateTime started_at) { TrackInfo t = (track as TrackInfo); if (t != null) { queue.Add (new QueuedTrack (t, started_at)); dirty = true; RaiseTrackAdded (this, new EventArgs ()); } } public void RemoveRange (int first, int count) { queue.RemoveRange (first, count); dirty = true; } public int Count { get { return queue.Count; } } private void RaiseTrackAdded (object o, EventArgs args) { EventHandler handler = TrackAdded; if (handler != null) handler (o, args); } } }
using System; using Microsoft.Xna.Framework; using Nez.BitmapFonts; namespace Nez.UI { /// <summary> /// A table that can be dragged and resized. The top padding is used as the window's title height. /// /// The preferred size of a window is the preferred size of the title text and the children as laid out by the table. After adding /// children to the window, it can be convenient to call {@link #pack()} to size the window to the size of the children. /// </summary> public class Window : Table, IInputListener { static private int MOVE = 1 << 5; private WindowStyle style; bool _isMovable = true, _isResizable; int resizeBorderSize = 8; bool _dragging; bool _keepWithinStage = true; Label titleLabel; Table titleTable; public Window( string title, WindowStyle style ) { Assert.isNotNull( title, "title cannot be null" ); touchable = Touchable.Enabled; clip = true; titleLabel = new Label( title, new LabelStyle( style.titleFont, style.titleFontColor ) ); titleLabel.setEllipsis( true ); titleTable = new Table(); titleTable.add( titleLabel ).setExpandX().setFillX().setMinWidth( 0 ); addElement( titleTable ); setStyle( style ); width = 150; height = 150; } public Window( string title, Skin skin, string styleName = null ) : this( title, skin.get<WindowStyle>( styleName ) ) {} #region IInputListener int edge; float startX, startY, lastX, lastY; void IInputListener.onMouseEnter() { } void IInputListener.onMouseExit() { } bool IInputListener.onMousePressed( Vector2 mousePos ) { float width = getWidth(), height = getHeight(); edge = 0; if( _isResizable && mousePos.X >= 0 && mousePos.X < width && mousePos.Y >= 0 && mousePos.Y < height ) { if( mousePos.X < resizeBorderSize ) edge |= (int)AlignInternal.left; if( mousePos.X > width - resizeBorderSize ) edge |= (int)AlignInternal.right; if( mousePos.Y < resizeBorderSize ) edge |= (int)AlignInternal.top; if( mousePos.Y > height - resizeBorderSize ) edge |= (int)AlignInternal.bottom; int tempResizeBorderSize = resizeBorderSize; if( edge != 0 ) tempResizeBorderSize += 25; if( mousePos.X < tempResizeBorderSize ) edge |= (int)AlignInternal.left; if( mousePos.X > width - tempResizeBorderSize ) edge |= (int)AlignInternal.right; if( mousePos.Y < tempResizeBorderSize ) edge |= (int)AlignInternal.top; if( mousePos.Y > height - tempResizeBorderSize ) edge |= (int)AlignInternal.bottom; } if( _isMovable && edge == 0 && mousePos.Y >= 0 && mousePos.Y <= getPadTop() && mousePos.X >= 0 && mousePos.X <= width ) edge = MOVE; _dragging = edge != 0; startX = mousePos.X; startY = mousePos.Y; lastX = mousePos.X; lastY = mousePos.Y; return true; } void IInputListener.onMouseMoved( Vector2 mousePos ) { if( !_dragging ) return; float width = getWidth(), height = getHeight(); float windowX = getX(), windowY = getY(); var stage = getStage(); var parentWidth = stage.getWidth(); var parentHeight = stage.getHeight(); var clampPosition = _keepWithinStage && getParent() == stage.getRoot(); if( ( edge & MOVE ) != 0 ) { float amountX = mousePos.X - startX, amountY = mousePos.Y - startY; if( clampPosition ) { if( windowX + amountX < 0 ) amountX = -windowX; if( windowY + amountY < 0 ) amountY = -windowY; if( windowX + width + amountX > parentWidth ) amountX = parentWidth - windowX - width; if( windowY + height + amountY > parentHeight ) amountY = parentHeight - windowY - height; } windowX += amountX; windowY += amountY; } if( ( edge & (int)AlignInternal.left ) != 0 ) { float amountX = mousePos.X - startX; if( width - amountX < minWidth ) amountX = -( minWidth - width ); if( clampPosition && windowX + amountX < 0 ) amountX = -windowX; width -= amountX; windowX += amountX; } if( ( edge & (int)AlignInternal.top ) != 0 ) { float amountY = mousePos.Y - startY; if( height - amountY < minHeight ) amountY = -( minHeight - height ); if( clampPosition && windowY + amountY < 0 ) amountY = -windowY; height -= amountY; windowY += amountY; } if( ( edge & (int)AlignInternal.right ) != 0 ) { float amountX = mousePos.X - lastX; if( width + amountX < minWidth ) amountX = minWidth - width; if( clampPosition && windowX + width + amountX > parentWidth ) amountX = parentWidth - windowX - width; width += amountX; } if( ( edge & (int)AlignInternal.bottom ) != 0 ) { float amountY = mousePos.Y - lastY; if( height + amountY < minHeight ) amountY = minHeight - height; if( clampPosition && windowY + height + amountY > parentHeight ) amountY = parentHeight - windowY - height; height += amountY; } lastX = mousePos.X; lastY = mousePos.Y; setBounds( Mathf.round( windowX ), Mathf.round( windowY ), Mathf.round( width ), Mathf.round( height ) ); } void IInputListener.onMouseUp( Vector2 mousePos ) { _dragging = false; } bool IInputListener.onMouseScrolled( int mouseWheelDelta ) { return false; } #endregion public Window setStyle( WindowStyle style ) { this.style = style; setBackground( style.background ); var labelStyle = titleLabel.getStyle(); labelStyle.font = style.titleFont ?? labelStyle.font; labelStyle.fontColor = style.titleFontColor; titleLabel.setStyle( labelStyle ); invalidateHierarchy(); return this; } /// <summary> /// Returns the window's style. Modifying the returned style may not have an effect until {@link #setStyle(WindowStyle)} is called /// </summary> /// <returns>The style.</returns> public WindowStyle getStyle() { return style; } public void keepWithinStage() { if( !_keepWithinStage ) return; var stage = getStage(); var parentWidth = stage.getWidth(); var parentHeight = stage.getHeight(); if( x < 0 ) x = 0; if( y < 0 ) y = 0; if( getY( AlignInternal.bottom ) > parentHeight ) y = parentHeight - height; if( getX( AlignInternal.right ) > parentWidth ) x = parentWidth - width; } public override void draw( Graphics graphics, float parentAlpha ) { keepWithinStage(); if( style.stageBackground != null ) { var stagePos = stageToLocalCoordinates( Vector2.Zero ); var stageSize = stageToLocalCoordinates( new Vector2( stage.getWidth(), stage.getHeight() ) ); drawStageBackground( graphics, parentAlpha, getX() + stagePos.X, getY() + stagePos.Y, getX() + stageSize.X, getY() + stageSize.Y ); } base.draw( graphics, parentAlpha ); } protected void drawStageBackground( Graphics graphics, float parentAlpha, float x, float y, float width, float height ) { style.stageBackground.draw( graphics, x, y, width, height, new Color( color, (int)(color.A * parentAlpha) ) ); } protected override void drawBackground( Graphics graphics, float parentAlpha, float x, float y ) { base.drawBackground( graphics, parentAlpha, x, y ); // Manually draw the title table before clipping is done. titleTable.color.A = color.A; float padTop = getPadTop(), padLeft = getPadLeft(); titleTable.setSize( getWidth() - padLeft - getPadRight(), padTop ); titleTable.setPosition( padLeft, 0 ); } public override Element hit( Vector2 point ) { var hit = base.hit( point ); if( hit == null || hit == this ) return hit; if( point.Y >= 0 && point.Y <= getPadTop() && point.X >= 0 && point.X <= width ) { // Hit the title bar, don't use the hit child if it is in the Window's table. Element current = hit; while( current.getParent() != this ) current = current.getParent(); if( getCell( current ) != null ) return this; } return hit; } public bool isMovable() { return _isMovable; } public Window setMovable( bool isMovable ) { _isMovable = isMovable; return this; } public Window setKeepWithinStage( bool keepWithinStage ) { _keepWithinStage = keepWithinStage; return this; } public bool isResizable() { return _isResizable; } public Window setResizable( bool isResizable ) { _isResizable = isResizable; return this; } public Window setResizeBorderSize( int resizeBorderSize ) { this.resizeBorderSize = resizeBorderSize; return this; } public bool isDragging() { return _dragging; } public float getPrefWidth() { return Math.Max( base.preferredWidth, titleLabel.preferredWidth + getPadLeft() + getPadRight() ); } public Table getTitleTable() { return titleTable; } public Label getTitleLabel() { return titleLabel; } } public class WindowStyle { public BitmapFont titleFont; /** Optional. */ public IDrawable background; /** Optional. */ public Color titleFontColor = Color.White; /** Optional. */ public IDrawable stageBackground; public WindowStyle() { titleFont = Graphics.instance.bitmapFont; } public WindowStyle( BitmapFont titleFont, Color titleFontColor, IDrawable background ) { this.titleFont = titleFont ?? Graphics.instance.bitmapFont; this.background = background; this.titleFontColor = titleFontColor; } public WindowStyle clone() { return new WindowStyle { background = background, titleFont = titleFont, titleFontColor = titleFontColor, stageBackground = stageBackground }; } } }
using ClosedXML.Excel; using ClosedXML.Excel.Drawings; using NUnit.Framework; using System; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace ClosedXML.Tests { [TestFixture] public class PictureTests { [Test] public void CanAddPictureFromBitmap() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet1"); using (var resourceStream = Assembly.GetAssembly(typeof(ClosedXML.Examples.BasicTable)).GetManifestResourceStream("ClosedXML.Examples.Resources.SampleImage.jpg")) using (var bitmap = Bitmap.FromStream(resourceStream) as Bitmap) { var picture = ws.AddPicture(bitmap, "MyPicture") .WithPlacement(XLPicturePlacement.FreeFloating) .MoveTo(50, 50) .WithSize(200, 200); Assert.AreEqual(XLPictureFormat.Jpeg, picture.Format); Assert.AreEqual(200, picture.Width); Assert.AreEqual(200, picture.Height); } } } [Test] public void CanAddPictureFromStream() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet1"); using (var resourceStream = Assembly.GetAssembly(typeof(ClosedXML.Examples.BasicTable)).GetManifestResourceStream("ClosedXML.Examples.Resources.SampleImage.jpg")) { var picture = ws.AddPicture(resourceStream, "MyPicture") .WithPlacement(XLPicturePlacement.FreeFloating) .MoveTo(50, 50) .WithSize(200, 200); Assert.AreEqual(XLPictureFormat.Jpeg, picture.Format); Assert.AreEqual(200, picture.Width); Assert.AreEqual(200, picture.Height); } } } [Test] public void CanAddPictureFromFile() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet1"); var path = Path.ChangeExtension(Path.GetTempFileName(), "jpg"); try { using (var resourceStream = Assembly.GetAssembly(typeof(ClosedXML.Examples.BasicTable)).GetManifestResourceStream("ClosedXML.Examples.Resources.SampleImage.jpg")) using (var fileStream = File.Create(path)) { resourceStream.Seek(0, SeekOrigin.Begin); resourceStream.CopyTo(fileStream); fileStream.Close(); } var picture = ws.AddPicture(path) .WithPlacement(XLPicturePlacement.FreeFloating) .MoveTo(50, 50); Assert.AreEqual(XLPictureFormat.Jpeg, picture.Format); Assert.AreEqual(400, picture.Width); Assert.AreEqual(400, picture.Height); } finally { if (File.Exists(path)) File.Delete(path); } } } [Test] public void CanAddPictureConcurrentlyFromFile() { var path = Path.ChangeExtension(Path.GetTempFileName(), "jpg"); try { using (var resourceStream = Assembly.GetAssembly(typeof(ClosedXML.Examples.BasicTable)).GetManifestResourceStream("ClosedXML.Examples.Resources.SampleImage.jpg")) using (var fileStream = File.Create(path)) { resourceStream.Seek(0, SeekOrigin.Begin); resourceStream.CopyTo(fileStream); fileStream.Close(); } Parallel.Invoke(() => verifyAddImageFromFile(path), () => verifyAddImageFromFile(path)); } finally { if (File.Exists(path)) { File.Delete(path); } } } private void verifyAddImageFromFile(string filePath) { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet1"); var picture = ws.AddPicture(filePath) .WithPlacement(XLPicturePlacement.FreeFloating) .MoveTo(50, 50); Assert.AreEqual(XLPictureFormat.Jpeg, picture.Format); Assert.AreEqual(400, picture.Width); Assert.AreEqual(50, picture.Top); } } [Test] public void CanScaleImage() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet1"); using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML.Tests.Resource.Images.ImageHandling.png")) { var pic = ws.AddPicture(resourceStream, "MyPicture") .WithPlacement(XLPicturePlacement.FreeFloating) .MoveTo(50, 50); Assert.AreEqual(252, pic.OriginalWidth); Assert.AreEqual(152, pic.OriginalHeight); Assert.AreEqual(252, pic.Width); Assert.AreEqual(152, pic.Height); pic.ScaleHeight(0.7); pic.ScaleWidth(1.2); Assert.AreEqual(252, pic.OriginalWidth); Assert.AreEqual(152, pic.OriginalHeight); Assert.AreEqual(302, pic.Width); Assert.AreEqual(106, pic.Height); pic.ScaleHeight(0.7); pic.ScaleWidth(1.2); Assert.AreEqual(252, pic.OriginalWidth); Assert.AreEqual(152, pic.OriginalHeight); Assert.AreEqual(362, pic.Width); Assert.AreEqual(74, pic.Height); pic.ScaleHeight(0.8, true); pic.ScaleWidth(1.1, true); Assert.AreEqual(252, pic.OriginalWidth); Assert.AreEqual(152, pic.OriginalHeight); Assert.AreEqual(277, pic.Width); Assert.AreEqual(122, pic.Height); } } } [Test] public void TestDefaultPictureNames() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet1"); using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML.Tests.Resource.Images.ImageHandling.png")) { ws.AddPicture(stream, XLPictureFormat.Png); stream.Position = 0; ws.AddPicture(stream, XLPictureFormat.Png); stream.Position = 0; ws.AddPicture(stream, XLPictureFormat.Png).Name = "Picture 4"; stream.Position = 0; ws.AddPicture(stream, XLPictureFormat.Png); stream.Position = 0; } Assert.AreEqual("Picture 1", ws.Pictures.Skip(0).First().Name); Assert.AreEqual("Picture 2", ws.Pictures.Skip(1).First().Name); Assert.AreEqual("Picture 4", ws.Pictures.Skip(2).First().Name); Assert.AreEqual("Picture 5", ws.Pictures.Skip(3).First().Name); } } [Test] public void TestDefaultIds() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet1"); using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML.Tests.Resource.Images.ImageHandling.png")) { ws.AddPicture(stream, XLPictureFormat.Png); stream.Position = 0; ws.AddPicture(stream, XLPictureFormat.Png); stream.Position = 0; ws.AddPicture(stream, XLPictureFormat.Png).Name = "Picture 4"; stream.Position = 0; ws.AddPicture(stream, XLPictureFormat.Png); stream.Position = 0; } Assert.AreEqual(1, ws.Pictures.Skip(0).First().Id); Assert.AreEqual(2, ws.Pictures.Skip(1).First().Id); Assert.AreEqual(3, ws.Pictures.Skip(2).First().Id); Assert.AreEqual(4, ws.Pictures.Skip(3).First().Id); } } [Test] public void XLMarkerTests() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); XLMarker firstMarker = new XLMarker(ws.Cell(1, 10), new Point(100, 0)); Assert.AreEqual(10, firstMarker.ColumnNumber); Assert.AreEqual(1, firstMarker.RowNumber); Assert.AreEqual(100, firstMarker.Offset.X); Assert.AreEqual(0, firstMarker.Offset.Y); } [Test] public void XLPictureTests() { using (var wb = new XLWorkbook()) { var ws = wb.Worksheets.Add("Sheet1"); using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML.Tests.Resource.Images.ImageHandling.png")) { var pic = ws.AddPicture(stream, XLPictureFormat.Png, "Image1") .WithPlacement(XLPicturePlacement.FreeFloating) .MoveTo(220, 155); Assert.AreEqual(XLPicturePlacement.FreeFloating, pic.Placement); Assert.AreEqual("Image1", pic.Name); Assert.AreEqual(XLPictureFormat.Png, pic.Format); Assert.AreEqual(252, pic.OriginalWidth); Assert.AreEqual(152, pic.OriginalHeight); Assert.AreEqual(252, pic.Width); Assert.AreEqual(152, pic.Height); Assert.AreEqual(220, pic.Left); Assert.AreEqual(155, pic.Top); } } } [Test] public void CanLoadFileWithImagesAndCopyImagesToNewSheet() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageAnchors.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); Assert.AreEqual(2, ws.Pictures.Count); var copy = ws.CopyTo("NewSheet"); Assert.AreEqual(2, copy.Pictures.Count); } } [Test] public void CanDeletePictures() { using (var ms = new MemoryStream()) { int originalCount; using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageAnchors.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); originalCount = ws.Pictures.Count; ws.Pictures.Delete(ws.Pictures.First()); var pictureName = ws.Pictures.First().Name; ws.Pictures.Delete(pictureName); wb.SaveAs(ms); } using (var wb = new XLWorkbook(ms)) { var ws = wb.Worksheets.First(); Assert.AreEqual(originalCount - 2, ws.Pictures.Count); } } } [Test] public void PictureRenameTests() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageAnchors.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheet("Images3"); var picture = ws.Pictures.First(); Assert.AreEqual("Picture 1", picture.Name); picture.Name = "picture 1"; picture.Name = "pICture 1"; picture.Name = "Picture 1"; picture = ws.Pictures.Last(); picture.Name = "new name"; Assert.Throws<ArgumentException>(() => picture.Name = "Picture 1"); Assert.Throws<ArgumentException>(() => picture.Name = "picTURE 1"); } } [Test] public void HandleDuplicatePictureIdsAcrossWorksheets() { using (var wb = new XLWorkbook()) { var ws1 = wb.AddWorksheet("Sheet1"); var ws2 = wb.AddWorksheet("Sheet2"); using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML.Tests.Resource.Images.ImageHandling.png")) { (ws1 as XLWorksheet).AddPicture(stream, "Picture 1", 2); (ws1 as XLWorksheet).AddPicture(stream, "Picture 2", 3); //Internal method - used for loading files var pic = (ws2 as XLWorksheet).AddPicture(stream, "Picture 1", 2) .WithPlacement(XLPicturePlacement.FreeFloating) .MoveTo(220, 155) as XLPicture; var id = pic.Id; pic.Id = id; Assert.AreEqual(id, pic.Id); pic.Id = 3; Assert.AreEqual(3, pic.Id); pic.Id = id; var pic2 = (ws2 as XLWorksheet).AddPicture(stream, "Picture 2", 3) .WithPlacement(XLPicturePlacement.FreeFloating) .MoveTo(440, 300) as XLPicture; } } } [Test] public void CopyImageSameWorksheet() { var wb = new XLWorkbook(); var ws1 = wb.Worksheets.Add("Sheet1"); IXLPicture original; using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML.Tests.Resource.Images.ImageHandling.png")) { original = (ws1 as XLWorksheet).AddPicture(stream, "Picture 1", 2) .WithPlacement(XLPicturePlacement.FreeFloating) .MoveTo(220, 155) as XLPicture; } var copy = original.Duplicate() .MoveTo(300, 200) as XLPicture; Assert.AreEqual(2, ws1.Pictures.Count()); Assert.AreEqual(ws1, copy.Worksheet); Assert.AreEqual(original.Format, copy.Format); Assert.AreEqual(original.Height, copy.Height); Assert.AreEqual(original.Placement, copy.Placement); Assert.AreEqual(original.TopLeftCell.ToString(), copy.TopLeftCell.ToString()); Assert.AreEqual(original.Width, copy.Width); Assert.AreEqual(original.ImageStream.ToArray(), copy.ImageStream.ToArray(), "Image streams differ"); Assert.AreEqual(200, copy.Top); Assert.AreEqual(300, copy.Left); Assert.AreNotEqual(original.Id, copy.Id); Assert.AreNotEqual(original.Name, copy.Name); } [Test] public void CopyImageDifferentWorksheets() { var wb = new XLWorkbook(); var ws1 = wb.Worksheets.Add("Sheet1"); IXLPicture original; using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML.Tests.Resource.Images.ImageHandling.png")) { original = (ws1 as XLWorksheet).AddPicture(stream, "Picture 1", 2) .WithPlacement(XLPicturePlacement.FreeFloating) .MoveTo(220, 155) as XLPicture; } var ws2 = wb.Worksheets.Add("Sheet2"); var copy = original.CopyTo(ws2); Assert.AreEqual(1, ws1.Pictures.Count()); Assert.AreEqual(1, ws2.Pictures.Count()); Assert.AreEqual(ws2, copy.Worksheet); Assert.AreEqual(original.Format, copy.Format); Assert.AreEqual(original.Height, copy.Height); Assert.AreEqual(original.Left, copy.Left); Assert.AreEqual(original.Name, copy.Name); Assert.AreEqual(original.Placement, copy.Placement); Assert.AreEqual(original.Top, copy.Top); Assert.AreEqual(original.TopLeftCell.ToString(), copy.TopLeftCell.ToString()); Assert.AreEqual(original.Width, copy.Width); Assert.AreEqual(original.ImageStream.ToArray(), copy.ImageStream.ToArray(), "Image streams differ"); Assert.AreNotEqual(original.Id, copy.Id); } [Test] public void PictureShiftsWhenInsertingRows() { using (var wb = new XLWorkbook()) using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML.Tests.Resource.Images.ImageHandling.png")) { var ws = wb.Worksheets.Add("ImageShift"); var picture = ws.AddPicture(stream, XLPictureFormat.Png, "PngImage") .MoveTo(ws.Cell(5, 2)) .WithPlacement(XLPicturePlacement.Move); ws.Row(2).InsertRowsBelow(20); Assert.AreEqual(25, picture.TopLeftCell.Address.RowNumber); } } [Test] public void PictureNotFound() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet1"); Assert.Throws<ArgumentOutOfRangeException>(() => ws.Picture("dummy")); Assert.Throws<ArgumentOutOfRangeException>(() => ws.Pictures.Delete("dummy")); } } [Test] public void CanCopyEmfPicture() { // #1621 - There are 2 Bmp Guids: ImageFormat.Bmp and ImageFormat.MemoryBmp using var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Other\Pictures\EmfPicture.xlsx")); using var wb = new XLWorkbook(stream); var ws1 = wb.Worksheets.First(); var img1 = ws1.Pictures.First(); var ws2 = wb.AddWorksheet(); var img2 = img1.CopyTo(ws2); Assert.AreEqual(XLPictureFormat.Emf, img2.Format); using var ms = new MemoryStream(); wb.SaveAs(ms); ms.Seek(0, SeekOrigin.Begin); using var wb2 = new XLWorkbook(ms); ws2 = wb2.Worksheet("Sheet2"); img2 = ws2.Pictures.First(); Assert.AreEqual(XLPictureFormat.Emf, img2.Format); } } }
/* * Qa full api * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: all * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace HostMe.Sdk.Model { /// <summary> /// Restaurant /// </summary> [DataContract] public partial class Restaurant : IEquatable<Restaurant>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="Restaurant" /> class. /// </summary> /// <param name="Id">Id.</param> /// <param name="Name">Name.</param> /// <param name="Address">Address.</param> /// <param name="ImageUrl">ImageUrl.</param> /// <param name="Lat">Lat.</param> /// <param name="Lon">Lon.</param> /// <param name="FacebookId">FacebookId.</param> /// <param name="TwitterAccount">TwitterAccount.</param> /// <param name="WebsiteUrl">WebsiteUrl.</param> /// <param name="FoursquareId">FoursquareId.</param> /// <param name="Phone">Phone.</param> /// <param name="TimeZone">TimeZone.</param> /// <param name="GooglePlaceId">GooglePlaceId.</param> /// <param name="YelpId">YelpId.</param> /// <param name="City">City.</param> /// <param name="State">State.</param> /// <param name="Country">Country.</param> /// <param name="Settings">Settings.</param> public Restaurant(int? Id = null, string Name = null, string Address = null, string ImageUrl = null, double? Lat = null, double? Lon = null, string FacebookId = null, string TwitterAccount = null, string WebsiteUrl = null, string FoursquareId = null, string Phone = null, string TimeZone = null, string GooglePlaceId = null, string YelpId = null, string City = null, string State = null, string Country = null, RestaurantSettings Settings = null) { this.Id = Id; this.Name = Name; this.Address = Address; this.ImageUrl = ImageUrl; this.Lat = Lat; this.Lon = Lon; this.FacebookId = FacebookId; this.TwitterAccount = TwitterAccount; this.WebsiteUrl = WebsiteUrl; this.FoursquareId = FoursquareId; this.Phone = Phone; this.TimeZone = TimeZone; this.GooglePlaceId = GooglePlaceId; this.YelpId = YelpId; this.City = City; this.State = State; this.Country = Country; this.Settings = Settings; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=true)] public int? Id { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=true)] public string Name { get; set; } /// <summary> /// Gets or Sets Address /// </summary> [DataMember(Name="address", EmitDefaultValue=true)] public string Address { get; set; } /// <summary> /// Gets or Sets ImageUrl /// </summary> [DataMember(Name="imageUrl", EmitDefaultValue=true)] public string ImageUrl { get; set; } /// <summary> /// Gets or Sets Lat /// </summary> [DataMember(Name="lat", EmitDefaultValue=true)] public double? Lat { get; set; } /// <summary> /// Gets or Sets Lon /// </summary> [DataMember(Name="lon", EmitDefaultValue=true)] public double? Lon { get; set; } /// <summary> /// Gets or Sets FacebookId /// </summary> [DataMember(Name="facebookId", EmitDefaultValue=true)] public string FacebookId { get; set; } /// <summary> /// Gets or Sets TwitterAccount /// </summary> [DataMember(Name="twitterAccount", EmitDefaultValue=true)] public string TwitterAccount { get; set; } /// <summary> /// Gets or Sets WebsiteUrl /// </summary> [DataMember(Name="websiteUrl", EmitDefaultValue=true)] public string WebsiteUrl { get; set; } /// <summary> /// Gets or Sets FoursquareId /// </summary> [DataMember(Name="foursquareId", EmitDefaultValue=true)] public string FoursquareId { get; set; } /// <summary> /// Gets or Sets Phone /// </summary> [DataMember(Name="phone", EmitDefaultValue=true)] public string Phone { get; set; } /// <summary> /// Gets or Sets TimeZone /// </summary> [DataMember(Name="timeZone", EmitDefaultValue=true)] public string TimeZone { get; set; } /// <summary> /// Gets or Sets GooglePlaceId /// </summary> [DataMember(Name="googlePlaceId", EmitDefaultValue=true)] public string GooglePlaceId { get; set; } /// <summary> /// Gets or Sets YelpId /// </summary> [DataMember(Name="yelpId", EmitDefaultValue=true)] public string YelpId { get; set; } /// <summary> /// Gets or Sets City /// </summary> [DataMember(Name="city", EmitDefaultValue=true)] public string City { get; set; } /// <summary> /// Gets or Sets State /// </summary> [DataMember(Name="state", EmitDefaultValue=true)] public string State { get; set; } /// <summary> /// Gets or Sets Country /// </summary> [DataMember(Name="country", EmitDefaultValue=true)] public string Country { get; set; } /// <summary> /// Gets or Sets Settings /// </summary> [DataMember(Name="settings", EmitDefaultValue=true)] public RestaurantSettings Settings { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Restaurant {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Address: ").Append(Address).Append("\n"); sb.Append(" ImageUrl: ").Append(ImageUrl).Append("\n"); sb.Append(" Lat: ").Append(Lat).Append("\n"); sb.Append(" Lon: ").Append(Lon).Append("\n"); sb.Append(" FacebookId: ").Append(FacebookId).Append("\n"); sb.Append(" TwitterAccount: ").Append(TwitterAccount).Append("\n"); sb.Append(" WebsiteUrl: ").Append(WebsiteUrl).Append("\n"); sb.Append(" FoursquareId: ").Append(FoursquareId).Append("\n"); sb.Append(" Phone: ").Append(Phone).Append("\n"); sb.Append(" TimeZone: ").Append(TimeZone).Append("\n"); sb.Append(" GooglePlaceId: ").Append(GooglePlaceId).Append("\n"); sb.Append(" YelpId: ").Append(YelpId).Append("\n"); sb.Append(" City: ").Append(City).Append("\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append(" Country: ").Append(Country).Append("\n"); sb.Append(" Settings: ").Append(Settings).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Restaurant); } /// <summary> /// Returns true if Restaurant instances are equal /// </summary> /// <param name="other">Instance of Restaurant to be compared</param> /// <returns>Boolean</returns> public bool Equals(Restaurant other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Address == other.Address || this.Address != null && this.Address.Equals(other.Address) ) && ( this.ImageUrl == other.ImageUrl || this.ImageUrl != null && this.ImageUrl.Equals(other.ImageUrl) ) && ( this.Lat == other.Lat || this.Lat != null && this.Lat.Equals(other.Lat) ) && ( this.Lon == other.Lon || this.Lon != null && this.Lon.Equals(other.Lon) ) && ( this.FacebookId == other.FacebookId || this.FacebookId != null && this.FacebookId.Equals(other.FacebookId) ) && ( this.TwitterAccount == other.TwitterAccount || this.TwitterAccount != null && this.TwitterAccount.Equals(other.TwitterAccount) ) && ( this.WebsiteUrl == other.WebsiteUrl || this.WebsiteUrl != null && this.WebsiteUrl.Equals(other.WebsiteUrl) ) && ( this.FoursquareId == other.FoursquareId || this.FoursquareId != null && this.FoursquareId.Equals(other.FoursquareId) ) && ( this.Phone == other.Phone || this.Phone != null && this.Phone.Equals(other.Phone) ) && ( this.TimeZone == other.TimeZone || this.TimeZone != null && this.TimeZone.Equals(other.TimeZone) ) && ( this.GooglePlaceId == other.GooglePlaceId || this.GooglePlaceId != null && this.GooglePlaceId.Equals(other.GooglePlaceId) ) && ( this.YelpId == other.YelpId || this.YelpId != null && this.YelpId.Equals(other.YelpId) ) && ( this.City == other.City || this.City != null && this.City.Equals(other.City) ) && ( this.State == other.State || this.State != null && this.State.Equals(other.State) ) && ( this.Country == other.Country || this.Country != null && this.Country.Equals(other.Country) ) && ( this.Settings == other.Settings || this.Settings != null && this.Settings.Equals(other.Settings) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.Address != null) hash = hash * 59 + this.Address.GetHashCode(); if (this.ImageUrl != null) hash = hash * 59 + this.ImageUrl.GetHashCode(); if (this.Lat != null) hash = hash * 59 + this.Lat.GetHashCode(); if (this.Lon != null) hash = hash * 59 + this.Lon.GetHashCode(); if (this.FacebookId != null) hash = hash * 59 + this.FacebookId.GetHashCode(); if (this.TwitterAccount != null) hash = hash * 59 + this.TwitterAccount.GetHashCode(); if (this.WebsiteUrl != null) hash = hash * 59 + this.WebsiteUrl.GetHashCode(); if (this.FoursquareId != null) hash = hash * 59 + this.FoursquareId.GetHashCode(); if (this.Phone != null) hash = hash * 59 + this.Phone.GetHashCode(); if (this.TimeZone != null) hash = hash * 59 + this.TimeZone.GetHashCode(); if (this.GooglePlaceId != null) hash = hash * 59 + this.GooglePlaceId.GetHashCode(); if (this.YelpId != null) hash = hash * 59 + this.YelpId.GetHashCode(); if (this.City != null) hash = hash * 59 + this.City.GetHashCode(); if (this.State != null) hash = hash * 59 + this.State.GetHashCode(); if (this.Country != null) hash = hash * 59 + this.Country.GetHashCode(); if (this.Settings != null) hash = hash * 59 + this.Settings.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Newtonsoft.Json.Linq; using MigAz.Azure.Asm; using Microsoft.IdentityModel.Clients.ActiveDirectory; using MigAz.Azure.Core.ArmTemplate; using System.Windows.Forms; using Newtonsoft.Json; using MigAz.Azure.Core.Interface; using MigAz.Azure.Arm; using MigAz.Azure.Interface; namespace MigAz.Azure { public class AzureRetriever { private ILogProvider _LogProvider; private IStatusProvider _StatusProvider; private object _lockObject = new object(); public delegate void OnRestResultHandler(AzureRestResponse response); public event OnRestResultHandler OnRestResult; private Dictionary<string, AzureRestResponse> _RestApiCache = new Dictionary<string, AzureRestResponse>(); private Dictionary<AzureSubscription, AzureSubscriptionResourceCache> _AzureSubscriptionResourceCaches = new Dictionary<AzureSubscription, AzureSubscriptionResourceCache>(); private AzureRetriever() { } public AzureRetriever(ILogProvider logProvider, IStatusProvider statusProvider) { _LogProvider = logProvider; _StatusProvider = statusProvider; } public ILogProvider LogProvider { get { return _LogProvider; } } public IStatusProvider StatusProvider { get { return _StatusProvider; } } public void ClearCache() { _RestApiCache = new Dictionary<string, AzureRestResponse>(); } public void LoadRestCache(string filepath) { StreamReader reader = new StreamReader(filepath); _RestApiCache = JsonConvert.DeserializeObject<Dictionary<string, AzureRestResponse>>(reader.ReadToEnd()); } public void SaveRestCache() { string jsontext = JsonConvert.SerializeObject(_RestApiCache, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }); string filedir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\MigAz"; if (!Directory.Exists(filedir)) { Directory.CreateDirectory(filedir); } string filePath = filedir + "\\AzureRestResponse-" + DateTime.UtcNow.Ticks.ToString() + ".json"; StreamWriter saveSelectionWriter = new StreamWriter(filePath); saveSelectionWriter.Write(jsontext); saveSelectionWriter.Close(); } private void writeRetreiverResultToLog(Guid requestGuid, string method, string url, string xml) { lock (_lockObject) { string logfilepath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\MigAz\\MigAz-XML-" + string.Format("{0:yyyyMMdd}", DateTime.Now) + ".log"; string text = DateTime.Now.ToString() + " " + requestGuid.ToString() + " " + url + Environment.NewLine; File.AppendAllText(logfilepath, text); File.AppendAllText(logfilepath, xml + Environment.NewLine); File.AppendAllText(logfilepath, Environment.NewLine); } _LogProvider.WriteLog(method, requestGuid.ToString() + " Received REST Response"); } public async Task<AzureRestResponse> GetAzureRestResponse(AzureRestRequest azureRestRequest) { _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " Url: " + azureRestRequest.Url); if (azureRestRequest.UseCached && _RestApiCache.ContainsKey(azureRestRequest.Url)) { _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " Using Cached Response"); _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " End REST Request"); AzureRestResponse cachedRestResponse = (AzureRestResponse)_RestApiCache[azureRestRequest.Url]; return cachedRestResponse; } HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(azureRestRequest.Url); request.Method = azureRestRequest.Method; if (azureRestRequest.AccessToken != String.Empty) { string authorizationHeader = "Bearer " + azureRestRequest.AccessToken; request.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader); writeRetreiverResultToLog(azureRestRequest.RequestGuid, "GetAzureRestResponse", azureRestRequest.Url, authorizationHeader); } if (request.Method == "POST") request.ContentLength = 0; foreach (String headerKey in azureRestRequest.Headers.Keys) { request.Headers.Add(headerKey, azureRestRequest.Headers[headerKey]); } string webRequesetResult = String.Empty; try { _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " " + azureRestRequest.Method + " " + azureRestRequest.Url); // Retry Guidlines for 500 series with Backoff Timer - https://msdn.microsoft.com/en-us/library/azure/jj878112.aspx https://msdn.microsoft.com/en-us/library/azure/gg185909.aspx HttpWebResponse response = null; const Int32 maxRetrySecond = 32; Int32 retrySeconds = 1; bool boolRetryGetResponse = true; while (boolRetryGetResponse) { try { response = (HttpWebResponse)await request.GetResponseAsync(); boolRetryGetResponse = false; } catch (WebException webException) { _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " EXCEPTION " + webException.Message); HttpWebResponse exceptionResponse = (HttpWebResponse)webException.Response; if (exceptionResponse != null) { _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " EXCEPTION HttpWebResponse Status Code: " + exceptionResponse.StatusCode); if ( (int)exceptionResponse.StatusCode == 429 || // 429 Too Many Requests ((int)exceptionResponse.StatusCode >= 500 && (int)exceptionResponse.StatusCode <= 599) ) { DateTime sleepUntil = DateTime.Now.AddSeconds(retrySeconds); string sleepMessage = "Sleeping for " + retrySeconds.ToString() + " second(s) (until " + sleepUntil.ToString() + ") before web request retry."; _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " " + sleepMessage); _StatusProvider.UpdateStatus(sleepMessage); while (DateTime.Now < sleepUntil) { Application.DoEvents(); } retrySeconds = retrySeconds * 2; if (retrySeconds > maxRetrySecond) { _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " Too many retry."); _StatusProvider.UpdateStatus("Too many retry."); throw webException; // too many retry -> throw exception } _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " Initiating retry of Web Request."); _StatusProvider.UpdateStatus("Initiating retry of Web Request."); } else if (exceptionResponse.StatusCode == HttpStatusCode.Conflict) { boolRetryGetResponse = false; } else throw webException; } else throw webException; } catch (Exception exc) { // todo? } } if (response != null) { _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " Status Code " + response.StatusCode); webRequesetResult = new StreamReader(response.GetResponseStream()).ReadToEnd(); writeRetreiverResultToLog(azureRestRequest.RequestGuid, "GetAzureRestResponse", azureRestRequest.Url, webRequesetResult); } } catch (Exception exception) { _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + azureRestRequest.Url + " EXCEPTION " + exception.Message); throw exception; } _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " End REST Request"); AzureRestResponse azureRestResponse = new AzureRestResponse(azureRestRequest, webRequesetResult); if (!_RestApiCache.ContainsKey(azureRestRequest.Url)) _RestApiCache.Add(azureRestRequest.Url, azureRestResponse); OnRestResult?.Invoke(azureRestResponse); return azureRestResponse; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedRegionCommitmentsClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<RegionCommitments.RegionCommitmentsClient> mockGrpcClient = new moq::Mock<RegionCommitments.RegionCommitmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionCommitmentRequest request = new GetRegionCommitmentRequest { Region = "regionedb20d96", Project = "projectaa6ff846", Commitment = "commitment726158e4", }; Commitment expectedResponse = new Commitment { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Plan = "plan5751c25f", Type = "typee2cc9d59", CreationTimestamp = "creation_timestamp235e59a1", Category = "category2f35efc4", StartTimestamp = "start_timestamp8aac6e77", Region = "regionedb20d96", Resources = { new ResourceCommitment(), }, Status = "status5444cb9a", StatusMessage = "status_message2c618f86", Reservations = { new Reservation(), }, Description = "description2cf9da67", LicenseResource = new LicenseResourceCommitment(), SelfLink = "self_link7e87f12d", EndTimestamp = "end_timestamp91060b72", AutoRenew = true, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionCommitmentsClient client = new RegionCommitmentsClientImpl(mockGrpcClient.Object, null); Commitment response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<RegionCommitments.RegionCommitmentsClient> mockGrpcClient = new moq::Mock<RegionCommitments.RegionCommitmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionCommitmentRequest request = new GetRegionCommitmentRequest { Region = "regionedb20d96", Project = "projectaa6ff846", Commitment = "commitment726158e4", }; Commitment expectedResponse = new Commitment { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Plan = "plan5751c25f", Type = "typee2cc9d59", CreationTimestamp = "creation_timestamp235e59a1", Category = "category2f35efc4", StartTimestamp = "start_timestamp8aac6e77", Region = "regionedb20d96", Resources = { new ResourceCommitment(), }, Status = "status5444cb9a", StatusMessage = "status_message2c618f86", Reservations = { new Reservation(), }, Description = "description2cf9da67", LicenseResource = new LicenseResourceCommitment(), SelfLink = "self_link7e87f12d", EndTimestamp = "end_timestamp91060b72", AutoRenew = true, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Commitment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionCommitmentsClient client = new RegionCommitmentsClientImpl(mockGrpcClient.Object, null); Commitment responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Commitment responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<RegionCommitments.RegionCommitmentsClient> mockGrpcClient = new moq::Mock<RegionCommitments.RegionCommitmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionCommitmentRequest request = new GetRegionCommitmentRequest { Region = "regionedb20d96", Project = "projectaa6ff846", Commitment = "commitment726158e4", }; Commitment expectedResponse = new Commitment { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Plan = "plan5751c25f", Type = "typee2cc9d59", CreationTimestamp = "creation_timestamp235e59a1", Category = "category2f35efc4", StartTimestamp = "start_timestamp8aac6e77", Region = "regionedb20d96", Resources = { new ResourceCommitment(), }, Status = "status5444cb9a", StatusMessage = "status_message2c618f86", Reservations = { new Reservation(), }, Description = "description2cf9da67", LicenseResource = new LicenseResourceCommitment(), SelfLink = "self_link7e87f12d", EndTimestamp = "end_timestamp91060b72", AutoRenew = true, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionCommitmentsClient client = new RegionCommitmentsClientImpl(mockGrpcClient.Object, null); Commitment response = client.Get(request.Project, request.Region, request.Commitment); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<RegionCommitments.RegionCommitmentsClient> mockGrpcClient = new moq::Mock<RegionCommitments.RegionCommitmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionCommitmentRequest request = new GetRegionCommitmentRequest { Region = "regionedb20d96", Project = "projectaa6ff846", Commitment = "commitment726158e4", }; Commitment expectedResponse = new Commitment { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Plan = "plan5751c25f", Type = "typee2cc9d59", CreationTimestamp = "creation_timestamp235e59a1", Category = "category2f35efc4", StartTimestamp = "start_timestamp8aac6e77", Region = "regionedb20d96", Resources = { new ResourceCommitment(), }, Status = "status5444cb9a", StatusMessage = "status_message2c618f86", Reservations = { new Reservation(), }, Description = "description2cf9da67", LicenseResource = new LicenseResourceCommitment(), SelfLink = "self_link7e87f12d", EndTimestamp = "end_timestamp91060b72", AutoRenew = true, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Commitment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionCommitmentsClient client = new RegionCommitmentsClientImpl(mockGrpcClient.Object, null); Commitment responseCallSettings = await client.GetAsync(request.Project, request.Region, request.Commitment, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Commitment responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.Commitment, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// // Mono.Data.TdsTypes.TdsInt64 // // Author: // Tim Coleman <tim@timcoleman.com> // // (C) Copyright Tim Coleman, 2002 // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Mono.Data.TdsClient; using System; using System.Data.SqlTypes; using System.Globalization; namespace Mono.Data.TdsTypes { public struct TdsInt64 : INullable, IComparable { #region Fields long value; private bool notNull; public static readonly TdsInt64 MaxValue = new TdsInt64 (9223372036854775807); public static readonly TdsInt64 MinValue = new TdsInt64 (-9223372036854775808); public static readonly TdsInt64 Null; public static readonly TdsInt64 Zero = new TdsInt64 (0); #endregion #region Constructors public TdsInt64 (long value) { this.value = value; notNull = true; } #endregion #region Properties public bool IsNull { get { return !notNull; } } public long Value { get { if (this.IsNull) throw new TdsNullValueException (); else return value; } } #endregion #region Methods public static TdsInt64 Add (TdsInt64 x, TdsInt64 y) { return (x + y); } public static TdsInt64 BitwiseAnd (TdsInt64 x, TdsInt64 y) { return (x & y); } public static TdsInt64 BitwiseOr (TdsInt64 x, TdsInt64 y) { return (x | y); } public int CompareTo (object value) { if (value == null) return 1; else if (!(value is TdsInt64)) throw new ArgumentException (Locale.GetText ("Value is not a System.Data.TdsTypes.TdsInt64")); else if (((TdsInt64)value).IsNull) return 1; else return this.value.CompareTo (((TdsInt64)value).Value); } public static TdsInt64 Divide (TdsInt64 x, TdsInt64 y) { return (x / y); } public override bool Equals (object value) { if (!(value is TdsInt64)) return false; else return (bool) (this == (TdsInt64)value); } public static TdsBoolean Equals (TdsInt64 x, TdsInt64 y) { return (x == y); } public override int GetHashCode () { return (int)(value & 0xffffffff) ^ (int)(value >> 32); } public static TdsBoolean GreaterThan (TdsInt64 x, TdsInt64 y) { return (x > y); } public static TdsBoolean GreaterThanOrEqual (TdsInt64 x, TdsInt64 y) { return (x >= y); } public static TdsBoolean LessThan (TdsInt64 x, TdsInt64 y) { return (x < y); } public static TdsBoolean LessThanOrEqual (TdsInt64 x, TdsInt64 y) { return (x <= y); } public static TdsInt64 Mod (TdsInt64 x, TdsInt64 y) { return (x % y); } public static TdsInt64 Multiply (TdsInt64 x, TdsInt64 y) { return (x * y); } public static TdsBoolean NotEquals (TdsInt64 x, TdsInt64 y) { return (x != y); } public static TdsInt64 OnesComplement (TdsInt64 x) { return ~x; } public static TdsInt64 Parse (string s) { return new TdsInt64 (Int64.Parse (s)); } public static TdsInt64 Subtract (TdsInt64 x, TdsInt64 y) { return (x - y); } public TdsBoolean ToTdsBoolean () { return ((TdsBoolean)this); } public TdsByte ToTdsByte () { return ((TdsByte)this); } public TdsDecimal ToTdsDecimal () { return ((TdsDecimal)this); } public TdsDouble ToTdsDouble () { return ((TdsDouble)this); } public TdsInt16 ToTdsInt16 () { return ((TdsInt16)this); } public TdsInt32 ToTdsInt32 () { return ((TdsInt32)this); } public TdsMoney ToTdsMoney () { return ((TdsMoney)this); } public TdsSingle ToTdsSingle () { return ((TdsSingle)this); } public TdsString ToTdsString () { return ((TdsString)this); } public override string ToString () { if (this.IsNull) return "Null"; return value.ToString (); } public static TdsInt64 Xor (TdsInt64 x, TdsInt64 y) { return (x ^ y); } public static TdsInt64 operator + (TdsInt64 x, TdsInt64 y) { return new TdsInt64 (x.Value + y.Value); } public static TdsInt64 operator & (TdsInt64 x, TdsInt64 y) { return new TdsInt64 (x.value & y.Value); } public static TdsInt64 operator | (TdsInt64 x, TdsInt64 y) { return new TdsInt64 (x.value | y.Value); } public static TdsInt64 operator / (TdsInt64 x, TdsInt64 y) { return new TdsInt64 (x.Value / y.Value); } public static TdsBoolean operator == (TdsInt64 x, TdsInt64 y) { if (x.IsNull || y.IsNull) return TdsBoolean.Null; else return new TdsBoolean (x.Value == y.Value); } public static TdsInt64 operator ^ (TdsInt64 x, TdsInt64 y) { return new TdsInt64 (x.Value ^ y.Value); } public static TdsBoolean operator > (TdsInt64 x, TdsInt64 y) { if (x.IsNull || y.IsNull) return TdsBoolean.Null; else return new TdsBoolean (x.Value > y.Value); } public static TdsBoolean operator >= (TdsInt64 x, TdsInt64 y) { if (x.IsNull || y.IsNull) return TdsBoolean.Null; else return new TdsBoolean (x.Value >= y.Value); } public static TdsBoolean operator != (TdsInt64 x, TdsInt64 y) { if (x.IsNull || y.IsNull) return TdsBoolean.Null; else return new TdsBoolean (!(x.Value == y.Value)); } public static TdsBoolean operator < (TdsInt64 x, TdsInt64 y) { if (x.IsNull || y.IsNull) return TdsBoolean.Null; else return new TdsBoolean (x.Value < y.Value); } public static TdsBoolean operator <= (TdsInt64 x, TdsInt64 y) { if (x.IsNull || y.IsNull) return TdsBoolean.Null; else return new TdsBoolean (x.Value <= y.Value); } public static TdsInt64 operator % (TdsInt64 x, TdsInt64 y) { return new TdsInt64(x.Value % y.Value); } public static TdsInt64 operator * (TdsInt64 x, TdsInt64 y) { return new TdsInt64 (x.Value * y.Value); } public static TdsInt64 operator ~ (TdsInt64 x) { return new TdsInt64 (~(x.Value)); } public static TdsInt64 operator - (TdsInt64 x, TdsInt64 y) { return new TdsInt64 (x.Value - y.Value); } public static TdsInt64 operator - (TdsInt64 n) { return new TdsInt64 (-(n.Value)); } public static explicit operator TdsInt64 (TdsBoolean x) { if (x.IsNull) return TdsInt64.Null; else return new TdsInt64 ((long)x.ByteValue); } public static explicit operator TdsInt64 (TdsDecimal x) { if (x.IsNull) return TdsInt64.Null; else return new TdsInt64 ((long)x.Value); } public static explicit operator TdsInt64 (TdsDouble x) { if (x.IsNull) return TdsInt64.Null; else return new TdsInt64 ((long)x.Value); } public static explicit operator long (TdsInt64 x) { return x.Value; } public static explicit operator TdsInt64 (TdsMoney x) { if (x.IsNull) return TdsInt64.Null; else return new TdsInt64 ((long)x.Value); } public static explicit operator TdsInt64 (TdsSingle x) { if (x.IsNull) return TdsInt64.Null; else return new TdsInt64 ((long)x.Value); } public static explicit operator TdsInt64 (TdsString x) { return TdsInt64.Parse (x.Value); } public static implicit operator TdsInt64 (long x) { return new TdsInt64 (x); } public static implicit operator TdsInt64 (TdsByte x) { if (x.IsNull) return TdsInt64.Null; else return new TdsInt64 ((long)x.Value); } public static implicit operator TdsInt64 (TdsInt16 x) { if (x.IsNull) return TdsInt64.Null; else return new TdsInt64 ((long)x.Value); } public static implicit operator TdsInt64 (TdsInt32 x) { if (x.IsNull) return TdsInt64.Null; else return new TdsInt64 ((long)x.Value); } #endregion } }
#define AWSSDK_UNITY // // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (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/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using Amazon.DynamoDBv2.DocumentModel; namespace Amazon.DynamoDBv2.DataModel { /// <summary> /// Context object for using the DataModel mode of DynamoDB. /// Used to interact with the service, save/load objects, etc. /// </summary> public partial class DynamoDBContext : IDynamoDBContext { #region Private members private bool disposed; private bool ownClient; internal IAmazonDynamoDB Client { get; private set; } private Dictionary<string, Table> tablesMap; private readonly object tablesMapLock = new object(); internal DynamoDBContextConfig Config { get; private set; } internal ItemStorageConfigCache StorageConfigCache { get; private set; } #endregion #region Public properties /// <summary> /// This cache is a way to store Converters for objects which provides a way to expand Context /// </summary> public Dictionary<Type, IPropertyConverter> ConverterCache { get; private set; } #endregion #region Constructors #if !(WIN_RT || WINDOWS_PHONE || AWSSDK_UNITY) /// <summary> /// Constructs a DynamoDBContext object with a default AmazonDynamoDBClient /// client and a default DynamoDBContextConfig object for configuration. /// </summary> public DynamoDBContext() : this(new AmazonDynamoDBClient()) { } /// <summary> /// Constructs a DynamoDBContext object with a default AmazonDynamoDBClient /// client and a default DynamoDBContextConfig object for configuration. /// </summary> /// <param name="region">The region to configure the AmazonDynamoDBClient to use.</param> public DynamoDBContext(RegionEndpoint region) : this(new AmazonDynamoDBClient(region), true, new DynamoDBContextConfig()) { } /// <summary> /// Constructs a DynamoDBContext object with the specified configuration. /// Uses a default AmazonDynamoDBClient as the client. /// </summary> /// <param name="config"></param> public DynamoDBContext(DynamoDBContextConfig config) : this(new AmazonDynamoDBClient(), config) { } /// <summary> /// Constructs a DynamoDBContext object with the specified configuration. /// Uses a default AmazonDynamoDBClient as the client. /// </summary> /// <param name="region">The region to configure the AmazonDynamoDBClient to use.</param> /// <param name="config"></param> public DynamoDBContext(RegionEndpoint region, DynamoDBContextConfig config) : this(new AmazonDynamoDBClient(region), true, config) { } #endif /// <summary> /// Constructs a DynamoDBContext object with the specified DynamoDB client. /// Uses default DynamoDBContextConfig object for configuration. /// </summary> /// <param name="client">Client to use for making calls</param> public DynamoDBContext(IAmazonDynamoDB client) : this(client, false, new DynamoDBContextConfig()) { } /// <summary> /// Constructs a DynamoDBContext object with the specified DynamoDB client /// and configuration. /// </summary> /// <param name="client">Client to use for making calls</param> /// <param name="config">Configuration to use</param> public DynamoDBContext(IAmazonDynamoDB client, DynamoDBContextConfig config) : this(client, false, config) { } private DynamoDBContext(IAmazonDynamoDB client, bool ownClient, DynamoDBContextConfig config) { if (client == null) throw new ArgumentNullException("client"); this.ConverterCache = new Dictionary<Type, IPropertyConverter>(); this.ConverterCache.Add(typeof(S3Link), new S3Link.S3LinkConverter(this)); this.Client = client; this.tablesMap = new Dictionary<string, Table>(); this.ownClient = ownClient; this.Config = config ?? new DynamoDBContextConfig(); this.StorageConfigCache = new ItemStorageConfigCache(this); } #endregion #region Dispose Pattern Implementation /// <summary> /// Implements the Dispose pattern /// </summary> /// <param name="disposing">Whether this object is being disposed via a call to Dispose /// or garbage collected.</param> protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing && Client != null) { if (ownClient) { Client.Dispose(); } Client = null; } this.disposed = true; } } /// <summary> /// Disposes of all managed and unmanaged resources. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// The destructor for the client class. /// </summary> ~DynamoDBContext() { this.Dispose(false); } #endregion #region Factory Creates /// <summary> /// Creates a strongly-typed BatchGet object, allowing /// a batch-get operation against DynamoDB. /// </summary> /// <typeparam name="T">Type of objects to get</typeparam> /// <returns>Empty strongly-typed BatchGet object</returns> public BatchGet<T> CreateBatchGet<T>() { return CreateBatchGet<T>(null); } /// <summary> /// Creates a strongly-typed BatchGet object, allowing /// a batch-get operation against DynamoDB. /// </summary> /// <typeparam name="T">Type of objects to get</typeparam> /// <param name="operationConfig">Config object which can be used to override that table used.</param> /// <returns>Empty strongly-typed BatchGet object</returns> public BatchGet<T> CreateBatchGet<T>(DynamoDBOperationConfig operationConfig) { DynamoDBFlatConfig config = new DynamoDBFlatConfig(operationConfig, this.Config); return new BatchGet<T>(this, config); } /// <summary> /// Creates a MultiTableBatchGet object, composed of multiple /// individual BatchGet objects. /// </summary> /// <param name="batches">Individual BatchGet objects</param> /// <returns>Composite MultiTableBatchGet object</returns> public MultiTableBatchGet CreateMultiTableBatchGet(params BatchGet[] batches) { return new MultiTableBatchGet(batches); } /// <summary> /// Creates a strongly-typed BatchWrite object, allowing /// a batch-write operation against DynamoDB. /// </summary> /// <typeparam name="T">Type of objects to write</typeparam> /// <returns>Empty strongly-typed BatchWrite object</returns> public BatchWrite<T> CreateBatchWrite<T>() { return CreateBatchWrite<T>(null); } /// <summary> /// Creates a strongly-typed BatchWrite object, allowing /// a batch-write operation against DynamoDB. /// </summary> /// <typeparam name="T">Type of objects to write</typeparam> /// <param name="operationConfig">Config object which can be used to override that table used.</param> /// <returns>Empty strongly-typed BatchWrite object</returns> public BatchWrite<T> CreateBatchWrite<T>(DynamoDBOperationConfig operationConfig) { DynamoDBFlatConfig config = new DynamoDBFlatConfig(operationConfig, this.Config); return new BatchWrite<T>(this, config); } /// <summary> /// Creates a MultiTableBatchWrite object, composed of multiple /// individual BatchWrite objects. /// </summary> /// <param name="batches">Individual BatchWrite objects</param> /// <returns>Composite MultiTableBatchWrite object</returns> public MultiTableBatchWrite CreateMultiTableBatchWrite(params BatchWrite[] batches) { return new MultiTableBatchWrite(batches); } #endregion #region Save/serialize private void SaveHelper<T>(T value, DynamoDBOperationConfig operationConfig, bool isAsync) { if (value == null) return; DynamoDBFlatConfig flatConfig = new DynamoDBFlatConfig(operationConfig, this.Config); ItemStorage storage = ObjectToItemStorage<T>(value, false, flatConfig); if (storage == null) return; Table table = GetTargetTable(storage.Config, flatConfig); if ( (flatConfig.SkipVersionCheck.HasValue && flatConfig.SkipVersionCheck.Value) || !storage.Config.HasVersion) { table.UpdateHelper(storage.Document, table.MakeKey(storage.Document), null, isAsync); } else { Document expectedDocument = CreateExpectedDocumentForVersion(storage); SetNewVersion(storage); table.UpdateHelper( storage.Document, table.MakeKey(storage.Document), new UpdateItemOperationConfig { Expected = expectedDocument, ReturnValues = ReturnValues.None }, isAsync); PopulateInstance(storage, value, flatConfig); } } /// <summary> /// Serializes an object to a Document. /// </summary> /// <typeparam name="T">Type to serialize as.</typeparam> /// <param name="value">Object to serialize.</param> /// <returns>Document with attributes populated from object.</returns> public Document ToDocument<T>(T value) { return ToDocument<T>(value, null); } /// <summary> /// Serializes an object to a Document. /// </summary> /// <typeparam name="T">Type to serialize as.</typeparam> /// <param name="value">Object to serialize.</param> /// <param name="operationConfig">Config object which can be used to override the table used.</param> /// <returns>Document with attributes populated from object.</returns> public Document ToDocument<T>(T value, DynamoDBOperationConfig operationConfig) { if (value == null) return null; DynamoDBFlatConfig flatConfig = new DynamoDBFlatConfig(operationConfig, Config); ItemStorage storage = ObjectToItemStorage<T>(value, false, flatConfig); if (storage == null) return null; return storage.Document; } #endregion #region Load/deserialize private T LoadHelper<T>(object hashKey, object rangeKey, DynamoDBOperationConfig operationConfig, bool isAsync) { DynamoDBFlatConfig flatConfig = new DynamoDBFlatConfig(operationConfig, this.Config); ItemStorageConfig storageConfig = StorageConfigCache.GetConfig<T>(flatConfig); Key key = MakeKey(hashKey, rangeKey, storageConfig, flatConfig); return LoadHelper<T>(key, flatConfig, storageConfig, isAsync); } private T LoadHelper<T>(T keyObject, DynamoDBOperationConfig operationConfig, bool isAsync) { DynamoDBFlatConfig flatConfig = new DynamoDBFlatConfig(operationConfig, this.Config); ItemStorageConfig storageConfig = StorageConfigCache.GetConfig<T>(flatConfig); Key key = MakeKey<T>(keyObject, storageConfig, flatConfig); return LoadHelper<T>(key, flatConfig, storageConfig, isAsync); } private T LoadHelper<T>(Key key, DynamoDBFlatConfig flatConfig, ItemStorageConfig storageConfig, bool isAsync) { GetItemOperationConfig getConfig = new GetItemOperationConfig { ConsistentRead = flatConfig.ConsistentRead.Value, AttributesToGet = storageConfig.AttributesToGet }; Table table = GetTargetTable(storageConfig, flatConfig); ItemStorage storage = new ItemStorage(storageConfig); storage.Document = table.GetItemHelper(key, getConfig, isAsync); T instance = DocumentToObject<T>(storage, flatConfig); return instance; } /// <summary> /// Deserializes a document to an instance of type T. /// </summary> /// <typeparam name="T">Type to populate.</typeparam> /// <param name="document">Document with properties to use.</param> /// <returns> /// Object of type T, populated with properties from the document. /// </returns> public T FromDocument<T>(Document document) { return FromDocument<T>(document, null); } /// <summary> /// Deserializes a document to an instance of type T. /// </summary> /// <typeparam name="T">Type to populate.</typeparam> /// <param name="document">Document with properties to use.</param> /// <param name="operationConfig">Config object which can be used to override the table used.</param> /// <returns> /// Object of type T, populated with properties from the document. /// </returns> public T FromDocument<T>(Document document, DynamoDBOperationConfig operationConfig) { DynamoDBFlatConfig flatConfig = new DynamoDBFlatConfig(operationConfig, Config); return FromDocumentHelper<T>(document, flatConfig); } internal T FromDocumentHelper<T>(Document document, DynamoDBFlatConfig flatConfig) { ItemStorageConfig storageConfig = StorageConfigCache.GetConfig<T>(flatConfig); ItemStorage storage = new ItemStorage(storageConfig); storage.Document = document; T instance = DocumentToObject<T>(storage, flatConfig); return instance; } /// <summary> /// Deserializes a collections of documents to a collection of instances of type T. /// </summary> /// <typeparam name="T">Type to populate.</typeparam> /// <param name="documents">Documents to deserialize.</param> /// <returns> /// Collection of items of type T, each populated with properties from a corresponding document. /// </returns> public IEnumerable<T> FromDocuments<T>(IEnumerable<Document> documents) { return FromDocuments<T>(documents, null); } /// <summary> /// Deserializes a collections of documents to a collection of instances of type T. /// </summary> /// <typeparam name="T">Type to populate.</typeparam> /// <param name="documents">Documents to deserialize.</param> /// <param name="operationConfig">Config object which can be used to override the table used.</param> /// <returns> /// Collection of items of type T, each populated with properties from a corresponding document. /// </returns> public IEnumerable<T> FromDocuments<T>(IEnumerable<Document> documents, DynamoDBOperationConfig operationConfig) { foreach (var document in documents) { T item = FromDocument<T>(document, operationConfig); yield return item; } } internal IEnumerable<T> FromDocumentsHelper<T>(IEnumerable<Document> documents, DynamoDBFlatConfig flatConfig) { foreach (var document in documents) { T item = FromDocumentHelper<T>(document, flatConfig); yield return item; } } #endregion #region Delete private void DeleteHelper<T>(object hashKey, object rangeKey, DynamoDBOperationConfig operationConfig, bool isAsync) { DynamoDBFlatConfig config = new DynamoDBFlatConfig(operationConfig, this.Config); ItemStorageConfig storageConfig = StorageConfigCache.GetConfig<T>(config); Key key = MakeKey(hashKey, rangeKey, storageConfig, config); Table table = GetTargetTable(storageConfig, config); table.DeleteHelper(key, null, isAsync); } private void DeleteHelper<T>(T value, DynamoDBOperationConfig operationConfig, bool isAsync) { if (value == null) throw new ArgumentNullException("value"); DynamoDBFlatConfig flatConfig = new DynamoDBFlatConfig(operationConfig, this.Config); flatConfig.IgnoreNullValues = true; ItemStorage storage = ObjectToItemStorage<T>(value, true, flatConfig); if (storage == null) return; Table table = GetTargetTable(storage.Config, flatConfig); if (flatConfig.SkipVersionCheck.Value || !storage.Config.HasVersion) { table.DeleteHelper(table.MakeKey(storage.Document), null, isAsync); } else { Document expectedDocument = CreateExpectedDocumentForVersion(storage); table.DeleteHelper( table.MakeKey(storage.Document), new DeleteItemOperationConfig { Expected = expectedDocument }, isAsync); } } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.DDF { using System; using System.Text; using System.Collections; using NPOI.Util; using System.Collections.Generic; /// <summary> /// This record is used whenever a escher record is encountered that /// we do not explicitly support. /// @author Glen Stampoultzis (glens at apache.org) /// </summary> public class UnknownEscherRecord : EscherRecord, ICloneable { private static byte[] NO_BYTES = new byte[0]; /** The data for this record not including the the 8 byte header */ private byte[] _thedata = NO_BYTES; private List<EscherRecord> _childRecords = new List<EscherRecord>(); public UnknownEscherRecord() { } /// <summary> /// This method deSerializes the record from a byte array. /// </summary> /// <param name="data"> The byte array containing the escher record information</param> /// <param name="offset">The starting offset into data </param> /// <param name="recordFactory">May be null since this is not a container record.</param> /// <returns>The number of bytes Read from the byte array.</returns> public override int FillFields(byte[] data, int offset, IEscherRecordFactory recordFactory) { int bytesRemaining = ReadHeader(data, offset); /* * Modified by Zhang Zhang * Have a check between avaliable bytes and bytesRemaining, * take the avaliable length if the bytesRemaining out of range. * July 09, 2010 */ int avaliable = data.Length - (offset + 8); if (bytesRemaining > avaliable) { bytesRemaining = avaliable; } if (IsContainerRecord) { int bytesWritten = 0; _thedata = new byte[0]; offset += 8; bytesWritten += 8; while (bytesRemaining > 0) { EscherRecord child = recordFactory.CreateRecord(data, offset); int childBytesWritten = child.FillFields(data, offset, recordFactory); bytesWritten += childBytesWritten; offset += childBytesWritten; bytesRemaining -= childBytesWritten; ChildRecords.Add(child); } return bytesWritten; } else { _thedata = new byte[bytesRemaining]; Array.Copy(data, offset + 8, _thedata, 0, bytesRemaining); return bytesRemaining + 8; } } /// <summary> /// Writes this record and any contained records to the supplied byte /// array. /// </summary> /// <param name="offset"></param> /// <param name="data"></param> /// <param name="listener">a listener for begin and end serialization events.</param> /// <returns>the number of bytes written.</returns> public override int Serialize(int offset, byte[] data, EscherSerializationListener listener) { listener.BeforeRecordSerialize(offset, RecordId, this); LittleEndian.PutShort(data, offset, Options); LittleEndian.PutShort(data, offset + 2, RecordId); int remainingBytes = _thedata.Length; for (IEnumerator iterator = ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord r = (EscherRecord)iterator.Current; remainingBytes += r.RecordSize; } LittleEndian.PutInt(data, offset + 4, remainingBytes); Array.Copy(_thedata, 0, data, offset + 8, _thedata.Length); int pos = offset + 8 + _thedata.Length; for (IEnumerator iterator = ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord r = (EscherRecord)iterator.Current; pos += r.Serialize(pos, data); } listener.AfterRecordSerialize(pos, RecordId, pos - offset, this); return pos - offset; } /// <summary> /// Gets the data. /// </summary> /// <value>The data.</value> public byte[] Data { get { return _thedata; } } /// <summary> /// Returns the number of bytes that are required to Serialize this record. /// </summary> /// <value>Number of bytes</value> public override int RecordSize { get { return 8 + _thedata.Length; } } /// <summary> /// Returns the children of this record. By default this will /// be an empty list. EscherCotainerRecord is the only record /// that may contain children. /// </summary> /// <value></value> public override List<EscherRecord> ChildRecords { get { return _childRecords; } set { this._childRecords = value; } } public override object Clone() { UnknownEscherRecord uer = new UnknownEscherRecord(); uer._thedata = (byte[])this._thedata.Clone(); uer.Options = (this.Options); uer.RecordId = (this.RecordId); return uer; } /// <summary> /// The short name for this record /// </summary> /// <value></value> public override String RecordName { get { return "Unknown 0x" + HexDump.ToHex(RecordId); } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override String ToString() { String nl = Environment.NewLine; StringBuilder children = new StringBuilder(); if (ChildRecords.Count > 0) { children.Append(" children: " + nl); for (IEnumerator iterator = ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord record = (EscherRecord)iterator.Current; children.Append(record.ToString()); children.Append(nl); } } String theDumpHex = ""; try { if (_thedata.Length != 0) { theDumpHex = " Extra Data(" + _thedata.Length + "):" + nl; theDumpHex += HexDump.Dump(_thedata, 0, 0); } } catch (Exception) { theDumpHex = "Error!!"; } return this.GetType().Name + ":" + nl + " isContainer: " + IsContainerRecord + nl + " version: 0x" + HexDump.ToHex(Version) + nl + " instance: 0x" + HexDump.ToHex(Instance) + nl + " recordId: 0x" + HexDump.ToHex(RecordId) + nl + " numchildren: " + ChildRecords.Count + nl + theDumpHex + children.ToString(); } public override String ToXml(String tab) { String theDumpHex = HexDump.ToHex(_thedata, 32); StringBuilder builder = new StringBuilder(); builder.Append(tab).Append(FormatXmlRecordHeader(GetType().Name, HexDump.ToHex(RecordId), HexDump.ToHex(Version), HexDump.ToHex(Instance))) .Append(tab).Append("\t").Append("<IsContainer>").Append(IsContainerRecord).Append("</IsContainer>\n") .Append(tab).Append("\t").Append("<Numchildren>").Append(HexDump.ToHex(_childRecords.Count)).Append("</Numchildren>\n"); for (IEnumerator<EscherRecord> iterator = _childRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord record = iterator.Current; builder.Append(record.ToXml(tab + "\t")); } builder.Append(theDumpHex).Append("\n"); builder.Append(tab).Append("</").Append(GetType().Name).Append(">\n"); return builder.ToString(); } /// <summary> /// Adds the child record. /// </summary> /// <param name="childRecord">The child record.</param> public void AddChildRecord(EscherRecord childRecord) { ChildRecords.Add(childRecord); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Diagnostics.Contracts; using System; using System.Collections; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization; using Microsoft.Contracts; namespace System.Collections.Generic { // Summary: // Represents a collection of keys and values. public class Dictionary<TKey, TValue> { // Summary: // Initializes a new instance of the System.Collections.Generic.Dictionary<TKey,TValue> // class that is empty, has the default initial capacity, and uses the default // equality comparer for the key type. public Dictionary() CodeContract.Ensures(Count == 0); // // Summary: // Initializes a new instance of the System.Collections.Generic.Dictionary<TKey,TValue> // class that contains elements copied from the specified System.Collections.Generic.IDictionary<TKey,TValue> // and uses the default equality comparer for the key type. // // Parameters: // dictionary: // The System.Collections.Generic.IDictionary<TKey,TValue> whose elements are // copied to the new System.Collections.Generic.Dictionary<TKey,TValue>. // // Exceptions: // System.ArgumentException: // dictionary contains one or more duplicate keys. // // System.ArgumentNullException: // dictionary is null. public Dictionary(IDictionary<TKey, TValue> dictionary) { CodeContract.Ensures(Count == dictionary.Count); // // Summary: // Initializes a new instance of the System.Collections.Generic.Dictionary<TKey,TValue> // class that is empty, has the default initial capacity, and uses the specified // System.Collections.Generic.IEqualityComparer<T>. // // Parameters: // comparer: // The System.Collections.Generic.IEqualityComparer<T> implementation to use // when comparing keys, or null to use the default System.Collections.Generic.EqualityComparer<T> // for the type of the key. return default(Dictionary(IDictionary<TKey,); } public Dictionary(IEqualityComparer<TKey> comparer) { CodeContract.Ensures(Count == 0); // // Summary: // Initializes a new instance of the System.Collections.Generic.Dictionary<TKey,TValue> // class that is empty, has the specified initial capacity, and uses the default // equality comparer for the key type. // // Parameters: // capacity: // The initial number of elements that the System.Collections.Generic.Dictionary<TKey,TValue> // can contain. // // Exceptions: // System.ArgumentOutOfRangeException: // capacity is less than 0. return default(Dictionary(IEqualityComparer<TKey>); } public Dictionary(int capacity) { CodeContract.Ensures(Count == 0); // // Summary: // Initializes a new instance of the System.Collections.Generic.Dictionary<TKey,TValue> // class that contains elements copied from the specified System.Collections.Generic.IDictionary<TKey,TValue> // and uses the specified System.Collections.Generic.IEqualityComparer<T>. // // Parameters: // dictionary: // The System.Collections.Generic.IDictionary<TKey,TValue> whose elements are // copied to the new System.Collections.Generic.Dictionary<TKey,TValue>. // // comparer: // The System.Collections.Generic.IEqualityComparer<T> implementation to use // when comparing keys, or null to use the default System.Collections.Generic.EqualityComparer<T> // for the type of the key. // // Exceptions: // System.ArgumentException: // dictionary contains one or more duplicate keys. // // System.ArgumentNullException: // dictionary is null. return default(Dictionary(int); } public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) { CodeContract.Ensures(Count == dictionary.Count); // // Summary: // Initializes a new instance of the System.Collections.Generic.Dictionary<TKey,TValue> // class that is empty, has the specified initial capacity, and uses the specified // System.Collections.Generic.IEqualityComparer<T>. // // Parameters: // capacity: // The initial number of elements that the System.Collections.Generic.Dictionary<TKey,TValue> // can contain. // // comparer: // The System.Collections.Generic.IEqualityComparer<T> implementation to use // when comparing keys, or null to use the default System.Collections.Generic.EqualityComparer<T> // for the type of the key. // // Exceptions: // System.ArgumentOutOfRangeException: // capacity is less than 0. return default(Dictionary(IDictionary<TKey,); } public Dictionary(int capacity, IEqualityComparer<TKey> comparer) { CodeContract.Ensures(Count == 0); // // Summary: // Initializes a new instance of the System.Collections.Generic.Dictionary<TKey,TValue> // class with serialized data. // // Parameters: // context: // A System.Runtime.Serialization.StreamingContext structure containing the // source and destination of the serialized stream associated with the System.Collections.Generic.Dictionary<TKey,TValue>. // // info: // A System.Runtime.Serialization.SerializationInfo object containing the information // required to serialize the System.Collections.Generic.Dictionary<TKey,TValue>. protected Dictionary(SerializationInfo info, StreamingContext context); // Summary: // Gets the System.Collections.Generic.IEqualityComparer<T> that is used to // determine equality of keys for the dictionary. // // Returns: // The System.Collections.Generic.IEqualityComparer<T> generic interface implementation // that is used to determine equality of keys for the current System.Collections.Generic.Dictionary<TKey,TValue> // and to provide hash values for the keys. return default(Dictionary(int); } public IEqualityComparer<TKey> Comparer { get; } // // Summary: // Gets the number of key/value pairs contained in the System.Collections.Generic.Dictionary<TKey,TValue>. // // Returns: // The number of key/value pairs contained in the System.Collections.Generic.Dictionary<TKey,TValue>. public int Count { get; } // // Summary: // Gets a collection containing the keys in the System.Collections.Generic.Dictionary<TKey,TValue>. // // Returns: // A System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection containing // the keys in the System.Collections.Generic.Dictionary<TKey,TValue>. public Dictionary<TKey, TValue>.KeyCollection! Keys { [ElementCollection] get; } // // Summary: // Gets a collection containing the values in the System.Collections.Generic.Dictionary<TKey,TValue>. // // Returns: // A System.Collections.Generic.Dictionary<TKey,TValue>.ValueCollection containing // the values in the System.Collections.Generic.Dictionary<TKey,TValue>. public Dictionary<TKey, TValue>.ValueCollection! Values { [ElementCollection] get; } // Summary: // Gets or sets the value associated with the specified key. // // Parameters: // key: // The key of the value to get or set. // // Returns: // The value associated with the specified key. If the specified key is not // found, a get operation throws a System.Collections.Generic.KeyNotFoundException, // and a set operation creates a new element with the specified key. // // Exceptions: // System.ArgumentNullException: // key is null. // // System.Collections.Generic.KeyNotFoundException: // The property is retrieved and key does not exist in the collection. public TValue this[TKey key] { [ResultNotNewlyAllocated] get; CodeContract.Requires(ContainsKey(key)); set; modifies this.*; CodeContract.Ensures(ContainsKey(key)); CodeContract.Ensures(old(ContainsKey(key)) ==> Count == old(Count)); CodeContract.Ensures(!old(ContainsKey(key)) ==> Count == old(Count) + 1); } // Summary: // Adds the specified key and value to the dictionary. // // Parameters: // value: // The value of the element to add. The value can be null for reference types. // // key: // The key of the element to add. // // Exceptions: // System.ArgumentException: // An element with the same key already exists in the System.Collections.Generic.Dictionary<TKey,TValue>. // // System.ArgumentNullException: // key is null. [WriteConfined] public void Add(TKey key, TValue value) { CodeContract.Requires(!ContainsKey(key)); modifies this.*; CodeContract.Ensures(ContainsKey(key)); CodeContract.Ensures(Count == old(Count) + 1); // // Summary: // Removes all keys and values from the System.Collections.Generic.Dictionary<TKey,TValue>. } [WriteConfined] public void Clear() { modifies this.*; CodeContract.Ensures(Count == 0); // // Summary: // Determines whether the System.Collections.Generic.Dictionary<TKey,TValue> // contains the specified key. // // Parameters: // key: // The key to locate in the System.Collections.Generic.Dictionary<TKey,TValue>. // // Returns: // true if the System.Collections.Generic.Dictionary<TKey,TValue> contains an // element with the specified key; otherwise, false. // // Exceptions: // System.ArgumentNullException: // key is null. } [Pure][Reads(ReadsAttribute.Reads.Owned)] public bool ContainsKey(TKey key) { CodeContract.Ensures(result ==> Count > 0); // // Summary: // Determines whether the System.Collections.Generic.Dictionary<TKey,TValue> // contains a specific value. // // Parameters: // value: // The value to locate in the System.Collections.Generic.Dictionary<TKey,TValue>. // The value can be null for reference types. // // Returns: // true if the System.Collections.Generic.Dictionary<TKey,TValue> contains an // element with the specified value; otherwise, false. return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Owned)] public bool ContainsValue(TValue value) { CodeContract.Ensures(result ==> Count > 0); // // Summary: // Returns an enumerator that iterates through the System.Collections.Generic.Dictionary<TKey,TValue>. // // Returns: // A System.Collections.Generic.Dictionary<TKey,TValue>.Enumerator structure // for the System.Collections.Generic.Dictionary<TKey,TValue>. return default(bool); } [Pure] [GlobalAccess(false)] [Escapes(true,false)] public Dictionary<TKey, TValue>.Enumerator GetEnumerator() { // // Summary: // Implements the System.Runtime.Serialization.ISerializable interface and returns // the data needed to serialize the System.Collections.Generic.Dictionary<TKey,TValue> // instance. // // Parameters: // context: // A System.Runtime.Serialization.StreamingContext structure that contains the // source and destination of the serialized stream associated with the System.Collections.Generic.Dictionary<TKey,TValue> // instance. // // info: // A System.Runtime.Serialization.SerializationInfo object that contains the // information required to serialize the System.Collections.Generic.Dictionary<TKey,TValue> // instance. // // Exceptions: // System.ArgumentNullException: // info is null. return default(Dictionary<TKey,); } [Pure][Reads(ReadsAttribute.Reads.Owned)] public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { // // Summary: // Implements the System.Runtime.Serialization.ISerializable interface and raises // the deserialization event when the deserialization is complete. // // Parameters: // sender: // The source of the deserialization event. // // Exceptions: // System.Runtime.Serialization.SerializationException: // The System.Runtime.Serialization.SerializationInfo object associated with // the current System.Collections.Generic.Dictionary<TKey,TValue> instance is // invalid. return default(virtual); } public virtual void OnDeserialization(object sender) { // // Summary: // Removes the value with the specified key from the System.Collections.Generic.Dictionary<TKey,TValue>. // // Parameters: // key: // The key of the element to remove. // // Returns: // true if the element is successfully found and removed; otherwise, false. // This method returns false if key is not found in the System.Collections.Generic.Dictionary<TKey,TValue>. // // Exceptions: // System.ArgumentNullException: // key is null. return default(virtual); } [WriteConfined] public bool Remove(TKey key) { modifies this.*; CodeContract.Ensures(result ==> old(ContainsKey(key)) && !ContainsKey(key)); CodeContract.Ensures(result ==> Count == old(Count) - 1); CodeContract.Ensures(!result ==> Count == old(Count)); return default(bool); } //[Pure][Reads(ReadsAttribute.Reads.Owned)] public bool TryGetValue(TKey key, out TValue? value) { CodeContract.Ensures(result == ContainsKey(key)); CodeContract.Ensures(Count == old(Count)); // Summary: // Represents the collection of keys in a System.Collections.Generic.Dictionary<TKey,TValue>. // This class cannot be inherited. [Serializable] return default(bool); } [DebuggerDisplay("Count = {Count}")] public sealed class KeyCollection { // Summary: // Initializes a new instance of the System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection // class that reflects the keys in the specified System.Collections.Generic.Dictionary<TKey,TValue>. // // Parameters: // dictionary: // The System.Collections.Generic.Dictionary<TKey,TValue> whose keys are reflected // in the new System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection. // // Exceptions: // System.ArgumentNullException: // dictionary is null. public KeyCollection(Dictionary<TKey, TValue> dictionary) { // Summary: // Gets the number of elements contained in the System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection. // // Returns: // The number of elements contained in the System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection.Retrieving // the value of this property is an O(1) operation. return default(KeyCollection(Dictionary<TKey,); } public int Count { get; } public void CopyTo(TKey[] array, int index) { CodeContract.Requires(0 <= index); CodeContract.Requires(index + Count <= array.Length); modifies array[*]; // // Summary: // Returns an enumerator that iterates through the System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection. // // Returns: // A System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection.Enumerator // for the System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection. } [Pure] [GlobalAccess(false)] [Escapes(true,false)] public Dictionary<TKey, TValue>.KeyCollection.Enumerator GetEnumerator() { // Summary: // Enumerates the elements of a System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection. return default(Dictionary<TKey,); } [Serializable] public struct Enumerator { // Summary: // Gets the element at the current position of the enumerator. // // Returns: // The element in the System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection // at the current position of the enumerator. public TKey Current { get; } // Summary: // Releases all resources used by the System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection.Enumerator. public void Dispose() { // // Summary: // Advances the enumerator to the next element of the System.Collections.Generic.Dictionary<TKey,TValue>.KeyCollection. // // Returns: // true if the enumerator was successfully advanced to the next element; false // if the enumerator has passed the end of the collection. // // Exceptions: // System.InvalidOperationException: // The collection was modified after the enumerator was created. } public bool MoveNext() { return default(bool); } } } // Summary: // Represents the collection of values in a System.Collections.Generic.Dictionary<TKey,TValue>. // This class cannot be inherited. [Serializable] [DebuggerDisplay("Count = {Count}")] public sealed class ValueCollection { // Summary: // Initializes a new instance of the System.Collections.Generic.Dictionary<TKey,TValue>.ValueCollection // class that reflects the values in the specified System.Collections.Generic.Dictionary<TKey,TValue>. // // Parameters: // dictionary: // The System.Collections.Generic.Dictionary<TKey,TValue> whose values are reflected // in the new System.Collections.Generic.Dictionary<TKey,TValue>.ValueCollection. // // Exceptions: // System.ArgumentNullException: // dictionary is null. public ValueCollection(Dictionary<TKey, TValue> dictionary) { // Summary: // Gets the number of elements contained in the System.Collections.Generic.Dictionary<TKey,TValue>.ValueCollection. // // Returns: // The number of elements contained in the System.Collections.Generic.Dictionary<TKey,TValue>.ValueCollection. return default(ValueCollection(Dictionary<TKey,); } public int Count { get) { CodeContract.Ensures(0 <= result) { } return default(int); } public void CopyTo(TValue[] array, int index) { CodeContract.Requires(0 <= index); CodeContract.Requires(index + Count <= array.Length); modifies array[*]; // // Summary: // Returns an enumerator that iterates through the System.Collections.Generic.Dictionary<TKey,TValue>.ValueCollection. // // Returns: // A System.Collections.Generic.Dictionary<TKey,TValue>.ValueCollection.Enumerator // for the System.Collections.Generic.Dictionary<TKey,TValue>.ValueCollection. } [Pure] [GlobalAccess(false)] [Escapes(true,false)] public Dictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator() { // Summary: // Enumerates the elements of a System.Collections.Generic.Dictionary<TKey,TValue>.ValueCollection. return default(Dictionary<TKey,); } [Serializable] public struct Enumerator { // Summary: // Gets the element at the current position of the enumerator. // // Returns: // The element in the System.Collections.Generic.Dictionary<TKey,TValue>.ValueCollection // at the current position of the enumerator. public TValue Current { get; } // Summary: // Releases all resources used by the System.Collections.Generic.Dictionary<TKey,TValue>.ValueCollection.Enumerator. public void Dispose() { // // Summary: // Advances the enumerator to the next element of the System.Collections.Generic.Dictionary<TKey,TValue>.ValueCollection. // // Returns: // true if the enumerator was successfully advanced to the next element; false // if the enumerator has passed the end of the collection. // // Exceptions: // System.InvalidOperationException: // The collection was modified after the enumerator was created. } public bool MoveNext() { return default(bool); } } } // Summary: // Enumerates the elements of a System.Collections.Generic.Dictionary<TKey,TValue>. [Serializable] public struct Enumerator { // Summary: // Gets the element at the current position of the enumerator. // // Returns: // The element in the System.Collections.Generic.Dictionary<TKey,TValue> at // the current position of the enumerator. public KeyValuePair<TKey, TValue> Current { get; } // Summary: // Releases all resources used by the System.Collections.Generic.Dictionary<TKey,TValue>.Enumerator. public void Dispose() { // // Summary: // Advances the enumerator to the next element of the System.Collections.Generic.Dictionary<TKey,TValue>. // // Returns: // true if the enumerator was successfully advanced to the next element; false // if the enumerator has passed the end of the collection. // // Exceptions: // System.InvalidOperationException: // The collection was modified after the enumerator was created. } public bool MoveNext() { return default(bool); } } } }
// 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.Text; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageService(typeof(ISyntaxFactsService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxFactsService : ISyntaxFactsService { public bool IsAwaitKeyword(SyntaxToken token) { return token.IsKind(SyntaxKind.AwaitKeyword); } public bool IsIdentifier(SyntaxToken token) { return token.IsKind(SyntaxKind.IdentifierToken); } public bool IsGlobalNamespaceKeyword(SyntaxToken token) { return token.IsKind(SyntaxKind.GlobalKeyword); } public bool IsVerbatimIdentifier(SyntaxToken token) { return token.IsVerbatimIdentifier(); } public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsKeywordKind(kind); // both contextual and reserved keywords } public bool IsContextualKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsContextualKeyword(kind); } public bool IsPreprocessorKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsPreprocessorKeyword(kind); } public bool IsHashToken(SyntaxToken token) { return (SyntaxKind)token.RawKind == SyntaxKind.HashToken; } public bool IsInInactiveRegion(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsInInactiveRegion(position, cancellationToken); } public bool IsInNonUserCode(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsInNonUserCode(position, cancellationToken); } public bool IsEntirelyWithinStringOrCharOrNumericLiteral(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective(SyntaxNode node) { return node is DirectiveTriviaSyntax; } public bool TryGetExternalSourceInfo(SyntaxNode node, out ExternalSourceInfo info) { var lineDirective = node as LineDirectiveTriviaSyntax; if (lineDirective != null) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default(ExternalSourceInfo); return false; } public bool IsRightSideOfQualifiedName(SyntaxNode node) { var name = node as SimpleNameSyntax; return name.IsRightSideOfQualifiedName(); } public bool IsMemberAccessExpressionName(SyntaxNode node) { var name = node as SimpleNameSyntax; return name.IsMemberAccessExpressionName(); } public bool IsObjectCreationExpressionType(SyntaxNode node) { return node.IsParentKind(SyntaxKind.ObjectCreationExpression) && ((ObjectCreationExpressionSyntax)node.Parent).Type == node; } public bool IsAttributeName(SyntaxNode node) { return SyntaxFacts.IsAttributeName(node); } public bool IsInvocationExpression(SyntaxNode node) { return node is InvocationExpressionSyntax; } public bool IsAnonymousFunction(SyntaxNode node) { return node is ParenthesizedLambdaExpressionSyntax || node is SimpleLambdaExpressionSyntax || node is AnonymousMethodExpressionSyntax; } public bool IsGenericName(SyntaxNode node) { return node is GenericNameSyntax; } public bool IsNamedParameter(SyntaxNode node) { return node.CheckParent<NameColonSyntax>(p => p.Name == node); } public bool IsSkippedTokensTrivia(SyntaxNode node) { return node is SkippedTokensTriviaSyntax; } public bool HasIncompleteParentMember(SyntaxNode node) { return node.IsParentKind(SyntaxKind.IncompleteMember); } public SyntaxToken GetIdentifierOfGenericName(SyntaxNode genericName) { var csharpGenericName = genericName as GenericNameSyntax; return csharpGenericName != null ? csharpGenericName.Identifier : default(SyntaxToken); } public bool IsCaseSensitive { get { return true; } } public bool IsUsingDirectiveName(SyntaxNode node) { return node.IsParentKind(SyntaxKind.UsingDirective) && ((UsingDirectiveSyntax)node.Parent).Name == node; } public bool IsForEachStatement(SyntaxNode node) { return node is ForEachStatementSyntax; } public bool IsLockStatement(SyntaxNode node) { return node is LockStatementSyntax; } public bool IsUsingStatement(SyntaxNode node) { return node is UsingStatementSyntax; } public bool IsThisConstructorInitializer(SyntaxToken token) { return token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) && ((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token; } public bool IsBaseConstructorInitializer(SyntaxToken token) { return token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer) && ((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token; } public bool IsQueryExpression(SyntaxNode node) { return node is QueryExpressionSyntax; } public bool IsPredefinedType(SyntaxToken token) { PredefinedType actualType; return TryGetPredefinedType(token, out actualType) && actualType != PredefinedType.None; } public bool IsPredefinedType(SyntaxToken token, PredefinedType type) { PredefinedType actualType; return TryGetPredefinedType(token, out actualType) && actualType == type; } public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private PredefinedType GetPredefinedType(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.BoolKeyword: return PredefinedType.Boolean; case SyntaxKind.ByteKeyword: return PredefinedType.Byte; case SyntaxKind.SByteKeyword: return PredefinedType.SByte; case SyntaxKind.IntKeyword: return PredefinedType.Int32; case SyntaxKind.UIntKeyword: return PredefinedType.UInt32; case SyntaxKind.ShortKeyword: return PredefinedType.Int16; case SyntaxKind.UShortKeyword: return PredefinedType.UInt16; case SyntaxKind.LongKeyword: return PredefinedType.Int64; case SyntaxKind.ULongKeyword: return PredefinedType.UInt64; case SyntaxKind.FloatKeyword: return PredefinedType.Single; case SyntaxKind.DoubleKeyword: return PredefinedType.Double; case SyntaxKind.DecimalKeyword: return PredefinedType.Decimal; case SyntaxKind.StringKeyword: return PredefinedType.String; case SyntaxKind.CharKeyword: return PredefinedType.Char; case SyntaxKind.ObjectKeyword: return PredefinedType.Object; case SyntaxKind.VoidKeyword: return PredefinedType.Void; default: return PredefinedType.None; } } public bool IsPredefinedOperator(SyntaxToken token) { PredefinedOperator actualOperator; return TryGetPredefinedOperator(token, out actualOperator) && actualOperator != PredefinedOperator.None; } public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) { PredefinedOperator actualOperator; return TryGetPredefinedOperator(token, out actualOperator) && actualOperator == op; } public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) { return SyntaxFacts.GetText((SyntaxKind)kind); } public bool IsIdentifierStartCharacter(char c) { return SyntaxFacts.IsIdentifierStartCharacter(c); } public bool IsIdentifierPartCharacter(char c) { return SyntaxFacts.IsIdentifierPartCharacter(c); } public bool IsIdentifierEscapeCharacter(char c) { return c == '@'; } public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) { return false; } public bool IsStartOfUnicodeEscapeSequence(char c) { return c == '\\'; } public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; } return false; } public bool IsStringLiteral(SyntaxToken token) { return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); } public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, SyntaxNode parent) { var typedToken = token; var typedParent = parent; if (typedParent.IsKind(SyntaxKind.IdentifierName)) { TypeSyntax declaredType = null; if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration)) { declaredType = ((VariableDeclarationSyntax)typedParent.Parent).Type; } else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration)) { declaredType = ((FieldDeclarationSyntax)typedParent.Parent).Declaration.Type; } return declaredType == typedParent && typedToken.ValueText == "var"; } return false; } public bool IsTypeNamedDynamic(SyntaxToken token, SyntaxNode parent) { var typedParent = parent as ExpressionSyntax; if (typedParent != null) { if (SyntaxFacts.IsInTypeOnlyContext(typedParent) && typedParent.IsKind(SyntaxKind.IdentifierName) && token.ValueText == "dynamic") { return true; } } return false; } public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } return false; } public bool IsMemberAccessExpression(SyntaxNode node) { return node is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.SimpleMemberAccessExpression; } public bool IsConditionalMemberAccessExpression(SyntaxNode node) { return node is ConditionalAccessExpressionSyntax; } public bool IsPointerMemberAccessExpression(SyntaxNode node) { return node is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.PointerMemberAccessExpression; } public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity) { name = null; arity = 0; var simpleName = node as SimpleNameSyntax; if (simpleName != null) { name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } } public SyntaxNode GetExpressionOfMemberAccessExpression(SyntaxNode node) { if (node.IsKind(SyntaxKind.MemberBindingExpression)) { if (node.IsParentKind(SyntaxKind.ConditionalAccessExpression)) { return GetExpressionOfConditionalMemberAccessExpression(node.Parent); } if (node.IsParentKind(SyntaxKind.InvocationExpression) && node.Parent.IsParentKind(SyntaxKind.ConditionalAccessExpression)) { return GetExpressionOfConditionalMemberAccessExpression(node.Parent.Parent); } } return (node as MemberAccessExpressionSyntax)?.Expression; } public SyntaxNode GetExpressionOfConditionalMemberAccessExpression(SyntaxNode node) { return (node as ConditionalAccessExpressionSyntax)?.Expression; } public bool IsInStaticContext(SyntaxNode node) { return node.IsInStaticContext(); } public bool IsInNamespaceOrTypeContext(SyntaxNode node) { return SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); } public SyntaxNode GetExpressionOfArgument(SyntaxNode node) { return ((ArgumentSyntax)node).Expression; } public RefKind GetRefKindOfArgument(SyntaxNode node) { return (node as ArgumentSyntax).GetRefKind(); } public bool IsInConstantContext(SyntaxNode node) { return (node as ExpressionSyntax).IsInConstantContext(); } public bool IsInConstructor(SyntaxNode node) { return node.GetAncestor<ConstructorDeclarationSyntax>() != null; } public bool IsUnsafeContext(SyntaxNode node) { return node.IsUnsafeContext(); } public SyntaxNode GetNameOfAttribute(SyntaxNode node) { return ((AttributeSyntax)node).Name; } public bool IsAttribute(SyntaxNode node) { return node is AttributeSyntax; } public bool IsAttributeNamedArgumentIdentifier(SyntaxNode node) { var identifier = node as IdentifierNameSyntax; return identifier != null && identifier.IsParentKind(SyntaxKind.NameEquals) && identifier.Parent.IsParentKind(SyntaxKind.AttributeArgument); } public SyntaxNode GetContainingTypeDeclaration(SyntaxNode root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode node) { throw ExceptionUtilities.Unreachable; } public SyntaxToken FindTokenOnLeftOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public SyntaxToken FindTokenOnRightOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public bool IsObjectCreationExpression(SyntaxNode node) { return node is ObjectCreationExpressionSyntax; } public bool IsObjectInitializerNamedAssignmentIdentifier(SyntaxNode node) { var identifier = node as IdentifierNameSyntax; return identifier != null && identifier.IsLeftSideOfAssignExpression() && identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression); } public bool IsElementAccessExpression(SyntaxNode node) { return node.Kind() == SyntaxKind.ElementAccessExpression; } public SyntaxNode ConvertToSingleLine(SyntaxNode node) { return node.ConvertToSingleLine(); } public SyntaxToken ToIdentifierToken(string name) { return name.ToIdentifierToken(); } public SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia) { return ((ExpressionSyntax)expression).Parenthesize(includeElasticTrivia); } public bool IsIndexerMemberCRef(SyntaxNode node) { return node.Kind() == SyntaxKind.IndexerMemberCref; } public SyntaxNode GetContainingMemberDeclaration(SyntaxNode root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { if ((node.Kind() != SyntaxKind.GlobalStatement) && (node is MemberDeclarationSyntax)) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember(SyntaxNode node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers(SyntaxNode node) { return node is NamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } public bool TryGetDeclaredSymbolInfo(SyntaxNode node, out DeclaredSymbolInfo declaredSymbolInfo) { switch (node.Kind()) { case SyntaxKind.ClassDeclaration: var classDecl = (ClassDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(classDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Class, classDecl.Identifier.Span); return true; case SyntaxKind.ConstructorDeclaration: var ctorDecl = (ConstructorDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo( ctorDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Constructor, ctorDecl.Identifier.Span, parameterCount: (ushort)(ctorDecl.ParameterList?.Parameters.Count ?? 0)); return true; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(delegateDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Delegate, delegateDecl.Identifier.Span); return true; case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(enumDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Enum, enumDecl.Identifier.Span); return true; case SyntaxKind.EnumMemberDeclaration: var enumMember = (EnumMemberDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(enumMember.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.EnumMember, enumMember.Identifier.Span); return true; case SyntaxKind.EventDeclaration: var eventDecl = (EventDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(eventDecl.Identifier.ValueText, eventDecl.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Event, eventDecl.Identifier.Span); return true; case SyntaxKind.IndexerDeclaration: var indexerDecl = (IndexerDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(WellKnownMemberNames.Indexer, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Indexer, indexerDecl.ThisKeyword.Span); return true; case SyntaxKind.InterfaceDeclaration: var interfaceDecl = (InterfaceDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(interfaceDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Interface, interfaceDecl.Identifier.Span); return true; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo( ExpandExplicitInterfaceName(method.Identifier.ValueText, method.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Method, method.Identifier.Span, parameterCount: (ushort)(method.ParameterList?.Parameters.Count ?? 0), typeParameterCount: (ushort)(method.TypeParameterList?.Parameters.Count ?? 0)); return true; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(property.Identifier.ValueText, property.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Property, property.Identifier.Span); return true; case SyntaxKind.StructDeclaration: var structDecl = (StructDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(structDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Struct, structDecl.Identifier.Span); return true; case SyntaxKind.VariableDeclarator: // could either be part of a field declaration or an event field declaration var variableDeclarator = (VariableDeclaratorSyntax)node; var variableDeclaration = variableDeclarator.Parent as VariableDeclarationSyntax; var fieldDeclaration = variableDeclaration?.Parent as BaseFieldDeclarationSyntax; if (fieldDeclaration != null) { var kind = fieldDeclaration is EventFieldDeclarationSyntax ? DeclaredSymbolInfoKind.Event : fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword) ? DeclaredSymbolInfoKind.Constant : DeclaredSymbolInfoKind.Field; declaredSymbolInfo = new DeclaredSymbolInfo(variableDeclarator.Identifier.ValueText, GetContainerDisplayName(fieldDeclaration.Parent), GetFullyQualifiedContainerName(fieldDeclaration.Parent), kind, variableDeclarator.Identifier.Span); return true; } break; } declaredSymbolInfo = default(DeclaredSymbolInfo); return false; } private static string ExpandExplicitInterfaceName(string identifier, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier) { if (explicitInterfaceSpecifier == null) { return identifier; } else { var builder = new StringBuilder(); ExpandTypeName(explicitInterfaceSpecifier.Name, builder); builder.Append('.'); builder.Append(identifier); return builder.ToString(); } } private static void ExpandTypeName(TypeSyntax type, StringBuilder builder) { switch (type.Kind()) { case SyntaxKind.AliasQualifiedName: var alias = (AliasQualifiedNameSyntax)type; builder.Append(alias.Alias.Identifier.ValueText); break; case SyntaxKind.ArrayType: var array = (ArrayTypeSyntax)type; ExpandTypeName(array.ElementType, builder); for (int i = 0; i < array.RankSpecifiers.Count; i++) { var rankSpecifier = array.RankSpecifiers[i]; builder.Append(rankSpecifier.OpenBracketToken.Text); for (int j = 1; j < rankSpecifier.Sizes.Count; j++) { builder.Append(','); } builder.Append(rankSpecifier.CloseBracketToken.Text); } break; case SyntaxKind.GenericName: var generic = (GenericNameSyntax)type; builder.Append(generic.Identifier.ValueText); if (generic.TypeArgumentList != null) { var arguments = generic.TypeArgumentList.Arguments; builder.Append(generic.TypeArgumentList.LessThanToken.Text); for (int i = 0; i < arguments.Count; i++) { if (i != 0) { builder.Append(','); } ExpandTypeName(arguments[i], builder); } builder.Append(generic.TypeArgumentList.GreaterThanToken.Text); } break; case SyntaxKind.IdentifierName: var identifierName = (IdentifierNameSyntax)type; builder.Append(identifierName.Identifier.ValueText); break; case SyntaxKind.NullableType: var nullable = (NullableTypeSyntax)type; ExpandTypeName(nullable.ElementType, builder); builder.Append(nullable.QuestionToken.Text); break; case SyntaxKind.OmittedTypeArgument: // do nothing since it was omitted, but don't reach the default block break; case SyntaxKind.PointerType: var pointer = (PointerTypeSyntax)type; ExpandTypeName(pointer.ElementType, builder); builder.Append(pointer.AsteriskToken.Text); break; case SyntaxKind.PredefinedType: var predefined = (PredefinedTypeSyntax)type; builder.Append(predefined.Keyword.Text); break; case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)type; ExpandTypeName(qualified.Left, builder); builder.Append(qualified.DotToken.Text); ExpandTypeName(qualified.Right, builder); break; default: Debug.Assert(false, "Unexpected type syntax " + type.Kind()); break; } } private string GetContainerDisplayName(SyntaxNode node) { return GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters); } private string GetFullyQualifiedContainerName(SyntaxNode node) { return GetDisplayName(node, DisplayNameOptions.IncludeNamespaces); } private const string dotToken = "."; public string GetDisplayName(SyntaxNode node, DisplayNameOptions options, string rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string>.GetInstance(); // containing type(s) var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent != null && parent.Kind() == SyntaxKind.NamespaceDeclaration) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.NamespaceDeclaration: return GetName(((NamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string name = null; var memberDeclaration = node as MemberDeclarationSyntax; if (memberDeclaration != null) { var nameToken = memberDeclaration.GetNameToken(); if (nameToken == default(SyntaxToken)) { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration); name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } } else { var fieldDeclarator = node as VariableDeclaratorSyntax; if (fieldDeclarator != null) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default(SyntaxToken)) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (int i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode root) { var list = new List<SyntaxNode>(); AppendMethodLevelMembers(root, list); return list; } private void AppendMethodLevelMembers(SyntaxNode node, List<SyntaxNode> list) { foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { AppendMethodLevelMembers(member, list); continue; } if (IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default(TextSpan); } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default(TextSpan); } // TODO: currently we only support method for now var method = member as BaseMethodDeclarationSyntax; if (method != null) { if (method.Body == null) { return default(TextSpan); } return GetBlockBodySpan(method.Body); } return default(TextSpan); } public bool ContainsInMemberBody(SyntaxNode node, TextSpan span) { var constructor = node as ConstructorDeclarationSyntax; if (constructor != null) { return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); } var method = node as BaseMethodDeclarationSyntax; if (method != null) { return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); } var property = node as BasePropertyDeclarationSyntax; if (property != null) { return property.AccessorList != null && property.AccessorList.Span.Contains(span); } var @enum = node as EnumMemberDeclarationSyntax; if (@enum != null) { return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); } var field = node as BaseFieldDeclarationSyntax; if (field != null) { return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private TextSpan GetBlockBodySpan(BlockSyntax body) { return TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); } public int GetMethodLevelMemberId(SyntaxNode root, SyntaxNode node) { Contract.Requires(root.SyntaxTree == node.SyntaxTree); int currentId = 0; SyntaxNode currentNode; Contract.ThrowIfFalse(TryGetMethodLevelMember(root, (n, i) => n == node, ref currentId, out currentNode)); Contract.ThrowIfFalse(currentId >= 0); CheckMemberId(root, node, currentId); return currentId; } public SyntaxNode GetMethodLevelMember(SyntaxNode root, int memberId) { int currentId = 0; SyntaxNode currentNode; if (!TryGetMethodLevelMember(root, (n, i) => i == memberId, ref currentId, out currentNode)) { return null; } Contract.ThrowIfNull(currentNode); CheckMemberId(root, currentNode, memberId); return currentNode; } private bool TryGetMethodLevelMember( SyntaxNode node, Func<SyntaxNode, int, bool> predicate, ref int currentId, out SyntaxNode currentNode) { foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (TryGetMethodLevelMember(member, predicate, ref currentId, out currentNode)) { return true; } continue; } if (IsMethodLevelMember(member)) { if (predicate(member, currentId)) { currentNode = member; return true; } currentId++; } } currentNode = null; return false; } [Conditional("DEBUG")] private void CheckMemberId(SyntaxNode root, SyntaxNode node, int memberId) { var list = GetMethodLevelMembers(root); var index = list.IndexOf(node); Contract.ThrowIfFalse(index == memberId); } public SyntaxNode GetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. var memberAccess = parent as MemberAccessExpressionSyntax; if (memberAccess != null) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. var qualifiedName = parent as QualifiedNameSyntax; if (qualifiedName != null) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. var aliasQualifiedName = parent as AliasQualifiedNameSyntax; if (aliasQualifiedName != null) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. var objectCreation = parent as ObjectCreationExpressionSyntax; if (objectCreation != null) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. var name = parent as NameSyntax; if (name == null) { break; } node = parent; } return node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode root, CancellationToken cancellationToken) { var compilationUnit = root as CompilationUnitSyntax; if (compilationUnit == null) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); var constructor = member as ConstructorDeclarationSyntax; if (constructor != null) { constructors.Add(constructor); continue; } var @namespace = member as NamespaceDeclarationSyntax; if (@namespace != null) { AppendConstructors(@namespace.Members, constructors, cancellationToken); } var @class = member as ClassDeclarationSyntax; if (@class != null) { AppendConstructors(@class.Members, constructors, cancellationToken); } var @struct = member as StructDeclarationSyntax; if (@struct != null) { AppendConstructors(@struct.Members, constructors, cancellationToken); } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.Item1; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default(SyntaxToken); return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using StructureMap.Building.Interception; using StructureMap.Configuration.DSL; using StructureMap.Configuration.DSL.Expressions; using StructureMap.Graph; using StructureMap.Pipeline; using StructureMap.TypeRules; namespace StructureMap { /// <summary> /// A Registry class provides methods and grammars for configuring a Container or ObjectFactory. /// Using a Registry subclass is the recommended way of configuring a StructureMap Container. /// </summary> /// <example> /// public class MyRegistry : Registry /// { /// public MyRegistry() /// { /// ForRequestedType(typeof(IService)).TheDefaultIsConcreteType(typeof(Service)); /// } /// } /// </example> public class Registry : IRegistry { private readonly IList<Action<PluginGraph>> _actions = new List<Action<PluginGraph>>(); internal readonly IList<AssemblyScanner> Scanners = new List<AssemblyScanner>(); internal Action<PluginGraph> alter { set { _actions.Add(value); } } /// <summary> /// Adds the concreteType as an Instance of the pluginType. Mostly useful /// for conventions /// </summary> /// <param name="pluginType"></param> /// <param name="concreteType"></param> public void AddType(Type pluginType, Type concreteType) { alter = g => g.AddType(pluginType, concreteType); } /// <summary> /// Adds the concreteType as an Instance of the pluginType with a name. Mostly /// useful for conventions /// </summary> /// <param name="pluginType"></param> /// <param name="concreteType"></param> /// <param name="name"></param> public virtual void AddType(Type pluginType, Type concreteType, string name) { alter = g => g.AddType(pluginType, concreteType, name); } /// <summary> /// Imports the configuration from another registry into this registry. /// </summary> /// <typeparam name="T"></typeparam> public void IncludeRegistry<T>() where T : Registry, new() { IncludeRegistry(new T()); } /// <summary> /// Imports the configuration from another registry into this registry. /// </summary> /// <param name="registry"></param> public void IncludeRegistry(Registry registry) { foreach (var scanner in registry.Scanners) { Scanners.Add(scanner); } foreach (var action in registry._actions) { _actions.Add(action); } } /// <summary> /// This method is a shortcut for specifying the default constructor and /// setter arguments for a ConcreteType. ForConcreteType is shorthand for: /// For[T]().Use[T].************** /// when the PluginType and ConcreteType are the same Type /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public BuildWithExpression<T> ForConcreteType<T>() { var instance = For<T>().Use<T>(); return new BuildWithExpression<T>(instance); } /// <summary> /// Convenience method. Equivalent of ForRequestedType[PluginType]().Singletons() /// </summary> /// <typeparam name="TPluginType"></typeparam> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> ForSingletonOf<TPluginType>() { return For<TPluginType>().Singleton(); } /// <summary> /// Shorthand way of saying For(pluginType).Singleton() /// </summary> /// <param name="pluginType"></param> /// <returns></returns> public GenericFamilyExpression ForSingletonOf(Type pluginType) { return For(pluginType).Singleton(); } /// <summary> /// An alternative way to use CreateProfile that uses ProfileExpression /// as a Nested Closure. This usage will result in cleaner code for /// multiple declarations /// </summary> /// <param name="profileName"></param> /// <param name="action"></param> public void Profile(string profileName, Action<IProfileRegistry> action) { var registry = new Registry(); action(registry); alter = x => registry.Configure(x.Profile(profileName)); } /// <summary> /// Designates a policy for scanning assemblies to auto /// register types /// </summary> /// <returns></returns> public void Scan(Action<IAssemblyScanner> action) { var scanner = new AssemblyScanner(); if (GetType().GetTypeInfo().Assembly == typeof(Registry).GetTypeInfo().Assembly) { scanner.Description = "Scanner #" + (Scanners.Count + 1); } else { scanner.Description = "{0} Scanner #{1}".ToFormat(GetType().Name, (Scanners.Count + 1)); } action(scanner); if (!scanner.Conventions.Any()) { throw new StructureMapConfigurationException($"Must be at least one {nameof(IRegistrationConvention)} in the scanning operation"); } Scanners.Add(scanner); } /// <summary> /// All requests For the "TO" types will be filled by fetching the "FROM" /// type and casting it to "TO" /// GetInstance(typeof(TO)) basically becomes (TO)GetInstance(typeof(FROM)) /// </summary> /// <typeparam name="TFrom"></typeparam> /// <typeparam name="TTo"></typeparam> public void Forward<TFrom, TTo>() where TFrom : class where TTo : class { For<TTo>().AddInstances(x => x.ConstructedBy(c => c.GetInstance<TFrom>() as TTo)); } /// <summary> /// Expression Builder used to define policies for a PluginType including /// Scoping, the Default Instance, and interception. BuildInstancesOf() /// and ForRequestedType() are synonyms /// </summary> /// <typeparam name="TPluginType"></typeparam> /// <param name="lifecycle">Optionally specify the instance scoping for this PluginType</param> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> For<TPluginType>(ILifecycle lifecycle = null) { return new CreatePluginFamilyExpression<TPluginType>(this, lifecycle); } /// <summary> /// Expression Builder used to define policies for a PluginType including /// Scoping, the Default Instance, and interception. This method is specifically /// meant for registering open generic types /// </summary> /// <param name="lifecycle">Optionally specify the instance scoping for this PluginType</param> /// <returns></returns> public GenericFamilyExpression For(Type pluginType, ILifecycle lifecycle = null) { return new GenericFamilyExpression(pluginType, lifecycle, this); } /// <summary> /// Shortcut to make StructureMap return the default object of U casted to T /// whenever T is requested. I.e.: /// For<T>().TheDefault.Is.ConstructedBy(c => c.GetInstance<U>() as T); /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="U"></typeparam> /// <returns></returns> public LambdaInstance<T, T> Redirect<T, U>() where T : class where U : class { return For<T>() .Use( "Redirect requests for {0} to the configured default of {1} with a cast".ToFormat( typeof (T).GetFullName(), typeof (U).GetFullName()), c => { var raw = c.GetInstance<U>(); var t = raw as T; if (t == null) throw new InvalidCastException(raw.GetType().AssemblyQualifiedName + " could not be cast to " + typeof (T).AssemblyQualifiedName); return t; }); } /// <summary> /// Advanced Usage Only! Skips the Registry and goes right to the inner /// Semantic Model of StructureMap. Use with care /// </summary> /// <param name="configure"></param> public void Configure(Action<PluginGraph> configure) { alter = configure; } internal void Configure(PluginGraph graph) { _actions.Each(action => action(graph)); } public TransientTracking TransientTracking { set { alter = graph => graph.TransientTracking = value; } } internal static bool IsPublicRegistry(Type type) { var ti = type.GetTypeInfo(); if (Equals(ti.Assembly, typeof (Registry).GetTypeInfo().Assembly)) { return false; } if (!typeof (Registry).GetTypeInfo().IsAssignableFrom(ti)) { return false; } if (ti.IsInterface || ti.IsAbstract || ti.IsGenericType) { return false; } return (type.GetConstructor(new Type[0]) != null); } public bool Equals(Registry other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (other.GetType() == typeof (Registry) && GetType() == typeof (Registry)) return false; if (other.GetType() == GetType() || other.GetType().AssemblyQualifiedName == GetType().AssemblyQualifiedName) { return !GetType().GetTypeInfo().IsNotPublic; } return false; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (!typeof(Registry).GetTypeInfo().IsAssignableFrom(obj.GetType().GetTypeInfo())) return false; return Equals((Registry) obj); } public override int GetHashCode() { return GetType().GetHashCode(); } /// <summary> /// Define the constructor and setter arguments for the default T /// </summary> /// <typeparam name="T"></typeparam> public class BuildWithExpression<T> { private readonly SmartInstance<T, T> _instance; public BuildWithExpression(SmartInstance<T, T> instance) { _instance = instance; } public SmartInstance<T, T> Configure { get { return _instance; } } } /// <summary> /// Configure Container-wide policies and conventions /// </summary> public PoliciesExpression Policies { get { return new PoliciesExpression(this); } } public class PoliciesExpression { private readonly Registry _parent; private Action<PluginGraph> alter { set { _parent.PoliciesChanged = true; _parent.alter = value; } } public PoliciesExpression(Registry parent) { _parent = parent; } /// <summary> /// Adds a new instance policy to this container /// that can apply to every object instance created /// by this container /// </summary> /// <param name="policy"></param> public void Add(IInstancePolicy policy) { alter = graph => graph.Policies.Add(policy); } /// <summary> /// Adds a new instance policy to this container /// that can apply to every object instance created /// by this container /// </summary> public void Add<T>() where T : IInstancePolicy, new() { Add(new T()); } /// <summary> /// Register an interception policy /// </summary> /// <param name="policy"></param> public void Interceptors(IInterceptorPolicy policy) { alter = graph => graph.Policies.Add(policy); } /// <summary> /// Register a strategy for automatically resolving "missing" families /// when an unknown PluginType is first encountered /// </summary> /// <typeparam name="T"></typeparam> public void OnMissingFamily<T>() where T : IFamilyPolicy, new() { alter = graph => graph.AddFamilyPolicy(new T()); } /// <summary> /// Register a strategy for automatically resolving "missing" families /// when an unknown PluginType is first encountered /// </summary> /// <param name="policy"></param> public void OnMissingFamily(IFamilyPolicy policy) { alter = graph => graph.AddFamilyPolicy(policy); } /// <summary> /// Register a custom constructor selection policy /// </summary> /// <typeparam name="T"></typeparam> public void ConstructorSelector<T>() where T : IConstructorSelector, new() { ConstructorSelector(new T()); } /// <summary> /// Register a custom constructor selection policy /// </summary> /// <param name="constructorSelector"></param> public void ConstructorSelector(IConstructorSelector constructorSelector) { alter = x => x.Policies.ConstructorSelector.Add(constructorSelector); } /// <summary> /// Creates automatic "policies" for which public setters are considered mandatory /// properties by StructureMap that will be "setter injected" as part of the /// construction process. /// </summary> /// <param name="action"></param> public void SetAllProperties(Action<SetterConvention> action) { var convention = new SetterConvention(); action(convention); alter = graph => convention.As<SetterConventionRule>().Configure(graph.Policies.SetterRules); } /// <summary> /// Directs StructureMap to always inject dependencies into any and all public Setter properties /// of the type TPluginType. /// </summary> /// <typeparam name="TPluginType"></typeparam> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> FillAllPropertiesOfType<TPluginType>() { Func<PropertyInfo, bool> predicate = prop => prop.PropertyType == typeof (TPluginType); alter = graph => graph.Policies.SetterRules.Add(predicate); return _parent.For<TPluginType>(); } } internal bool PoliciesChanged { get; set; } private static int mutation = 0; public static bool RegistryExists(IEnumerable<Registry> all, Registry registry) { if (all.Contains(registry)) return true; var type = registry.GetType(); if (type == typeof (Registry)) return false; if (type == typeof (ConfigurationExpression)) return false; var constructors = type.GetConstructors(); if (constructors.Count() == 1 && !constructors.Single().GetParameters().Any()) { if (all.Any(x => x.GetType() == type)) return true; if (all.Any(x => x.GetType().AssemblyQualifiedName == type.AssemblyQualifiedName)) return true; } return false; } } }
// // Mono.Data.SybaseTypes.SybaseMoney // // Author: // Tim Coleman <tim@timcoleman.com> // // Based on System.Data.SqlTypes.SqlMoney // // (C) Ximian, Inc. 2002-2003 // (C) Copyright Tim Coleman, 2002-2003 // // // 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 Mono.Data.SybaseClient; using System; using System.Data.SqlTypes; using System.Globalization; namespace Mono.Data.SybaseTypes { public struct SybaseMoney : INullable, IComparable { #region Fields decimal value; private bool notNull; public static readonly SybaseMoney MaxValue = new SybaseMoney (922337203685477.5807); public static readonly SybaseMoney MinValue = new SybaseMoney (-922337203685477.5808); public static readonly SybaseMoney Null; public static readonly SybaseMoney Zero = new SybaseMoney (0); #endregion #region Constructors public SybaseMoney (decimal value) { this.value = value; notNull = true; } public SybaseMoney (double value) { this.value = (decimal)value; notNull = true; } public SybaseMoney (int value) { this.value = (decimal)value; notNull = true; } public SybaseMoney (long value) { this.value = (decimal)value; notNull = true; } #endregion #region Properties public bool IsNull { get { return !notNull; } } public decimal Value { get { if (this.IsNull) throw new SybaseNullValueException (); else return value; } } #endregion #region Methods public static SybaseMoney Add (SybaseMoney x, SybaseMoney y) { return (x + y); } public int CompareTo (object value) { if (value == null) return 1; else if (!(value is SybaseMoney)) throw new ArgumentException (Locale.GetText ("Value is not a System.Data.SybaseTypes.SybaseMoney")); else if (((SybaseMoney)value).IsNull) return 1; else return this.value.CompareTo (((SybaseMoney)value).Value); } public static SybaseMoney Divide (SybaseMoney x, SybaseMoney y) { return (x / y); } public override bool Equals (object value) { if (!(value is SybaseMoney)) return false; else return (bool) (this == (SybaseMoney)value); } public static SybaseBoolean Equals (SybaseMoney x, SybaseMoney y) { return (x == y); } public override int GetHashCode () { return (int)value; } public static SybaseBoolean GreaterThan (SybaseMoney x, SybaseMoney y) { return (x > y); } public static SybaseBoolean GreaterThanOrEqual (SybaseMoney x, SybaseMoney y) { return (x >= y); } public static SybaseBoolean LessThan (SybaseMoney x, SybaseMoney y) { return (x < y); } public static SybaseBoolean LessThanOrEqual (SybaseMoney x, SybaseMoney y) { return (x <= y); } public static SybaseMoney Multiply (SybaseMoney x, SybaseMoney y) { return (x * y); } public static SybaseBoolean NotEquals (SybaseMoney x, SybaseMoney y) { return (x != y); } public static SybaseMoney Parse (string s) { decimal d = Decimal.Parse (s); if (d > SybaseMoney.MaxValue.Value || d < SybaseMoney.MinValue.Value) throw new OverflowException (""); return new SybaseMoney (d); } public static SybaseMoney Subtract (SybaseMoney x, SybaseMoney y) { return (x - y); } public decimal ToDecimal () { return value; } public double ToDouble () { return (double)value; } public int ToInt32 () { return (int)value; } public long ToInt64 () { return (long)value; } public SybaseBoolean ToSybaseBoolean () { return ((SybaseBoolean)this); } public SybaseByte ToSybaseByte () { return ((SybaseByte)this); } public SybaseDecimal ToSybaseDecimal () { return ((SybaseDecimal)this); } public SybaseDouble ToSybaseDouble () { return ((SybaseDouble)this); } public SybaseInt16 ToSybaseInt16 () { return ((SybaseInt16)this); } public SybaseInt32 ToSybaseInt32 () { return ((SybaseInt32)this); } public SybaseInt64 ToSybaseInt64 () { return ((SybaseInt64)this); } public SybaseSingle ToSybaseSingle () { return ((SybaseSingle)this); } public SybaseString ToSybaseString () { return ((SybaseString)this); } public override string ToString () { if (this.IsNull) return String.Empty; else return value.ToString (); } public static SybaseMoney operator + (SybaseMoney x, SybaseMoney y) { return new SybaseMoney (x.Value + y.Value); } public static SybaseMoney operator / (SybaseMoney x, SybaseMoney y) { return new SybaseMoney (x.Value / y.Value); } public static SybaseBoolean operator == (SybaseMoney x, SybaseMoney y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; else return new SybaseBoolean (x.Value == y.Value); } public static SybaseBoolean operator > (SybaseMoney x, SybaseMoney y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; else return new SybaseBoolean (x.Value > y.Value); } public static SybaseBoolean operator >= (SybaseMoney x, SybaseMoney y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; else return new SybaseBoolean (x.Value >= y.Value); } public static SybaseBoolean operator != (SybaseMoney x, SybaseMoney y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; else return new SybaseBoolean (!(x.Value == y.Value)); } public static SybaseBoolean operator < (SybaseMoney x, SybaseMoney y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; else return new SybaseBoolean (x.Value < y.Value); } public static SybaseBoolean operator <= (SybaseMoney x, SybaseMoney y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; return new SybaseBoolean (x.Value <= y.Value); } public static SybaseMoney operator * (SybaseMoney x, SybaseMoney y) { return new SybaseMoney (x.Value * y.Value); } public static SybaseMoney operator - (SybaseMoney x, SybaseMoney y) { return new SybaseMoney (x.Value - y.Value); } public static SybaseMoney operator - (SybaseMoney n) { return new SybaseMoney (-(n.Value)); } public static explicit operator SybaseMoney (SybaseBoolean x) { if (x.IsNull) return Null; else return new SybaseMoney ((decimal)x.ByteValue); } public static explicit operator SybaseMoney (SybaseDecimal x) { if (x.IsNull) return Null; else return new SybaseMoney (x.Value); } public static explicit operator SybaseMoney (SybaseDouble x) { if (x.IsNull) return Null; else return new SybaseMoney ((decimal)x.Value); } public static explicit operator decimal (SybaseMoney x) { return x.Value; } public static explicit operator SybaseMoney (SybaseSingle x) { if (x.IsNull) return Null; else return new SybaseMoney ((decimal)x.Value); } public static explicit operator SybaseMoney (SybaseString x) { return SybaseMoney.Parse (x.Value); } public static implicit operator SybaseMoney (decimal x) { return new SybaseMoney (x); } public static implicit operator SybaseMoney (SybaseByte x) { if (x.IsNull) return Null; else return new SybaseMoney ((decimal)x.Value); } public static implicit operator SybaseMoney (SybaseInt16 x) { if (x.IsNull) return Null; else return new SybaseMoney ((decimal)x.Value); } public static implicit operator SybaseMoney (SybaseInt32 x) { if (x.IsNull) return Null; else return new SybaseMoney ((decimal)x.Value); } public static implicit operator SybaseMoney (SybaseInt64 x) { if (x.IsNull) return Null; else return new SybaseMoney ((decimal)x.Value); } #endregion } }
#region CopyrightHeader // // Copyright by Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0.txt // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Collections; using System.Collections.Specialized; using System.Text; using gov.va.medora.utils; using gov.va.medora.mdo.src.mdo; namespace gov.va.medora.mdo.dao.vista { public class VistaQuery : MdoQuery { string rpcName; ArrayList parameters = new ArrayList(); internal int LITERAL = 1; internal int REFERENCE = 2; internal int LIST = 3; internal int WORDPROC = 4; // These are only valid if the VistA system is NOT backward compatible and the // Delphi RPC Broker is hardwired on creation to set backward compatibility to // true. Therefore, this is not something to worry about until there's a change // in the broker.pre //internal int GLOBAL = 5; //internal int EMPTY = 6; //internal int STREAM = 7; public VistaQuery() {} public VistaQuery(string rpcName) { RpcName = rpcName; } public override string RpcName { get { return rpcName; } set { rpcName = value; } } public override ArrayList Parameters { get { return parameters; } set { parameters = value; } } public void addParameter(int type, string value) { Parameter vp = new Parameter(type,value); parameters.Add(vp); } public void addParameter(int type, string value, string text) { Parameter vp = new Parameter(type,value,text); parameters.Add(vp); } public void addParameter(int type, DictionaryHashList lst) { Parameter vp = new Parameter(type,lst); parameters.Add(vp); } public void addEncryptedParameter(int type, string value) { Parameter vp = new Parameter(type, value, true); parameters.Add(vp); } private string buildApi(string rpcName, string parameters, string fText) { string sParams = StringUtils.strPack(parameters, 5); return StringUtils.strPack(fText + rpcName + '^' + sParams, 5); } public override string buildMessage() { //return buildMessage_DirectBroker(); return buildMessage_NatBroker(); } // Use this builder for the old broker... public string buildMessage_DirectBroker() { const string PREFIX = "{XWB}"; const string HDR = "007XWB;;;;"; string sParams = ""; DictionaryHashList lst = null; string text = null; for (int i=0; i<parameters.Count; i++) { Parameter vp = (Parameter)parameters[i]; int pType = vp.Type; if (pType == LITERAL) { sParams += StringUtils.strPack('0' + vp.Value,3); } else if (pType == REFERENCE) { sParams += StringUtils.strPack('1' + vp.Value,3); } else if (pType == LIST) { sParams += StringUtils.strPack('2' + vp.Value,3); lst = vp.List; } else if (pType == WORDPROC) { sParams += StringUtils.strPack('2' + vp.Value,3); text = vp.Text; } } string msg = ""; if (lst == null && text == null) { msg = StringUtils.strPack(HDR + buildApi(rpcName,sParams,"0"),5); } else if (lst != null) { msg = StringUtils.strPack(HDR + buildApi(rpcName,sParams,"1"),5); for (int j = 0; j < lst.Count; j++) { DictionaryEntry entry = lst[j]; string key = (string)entry.Key; string value = (string)entry.Value; if (value == null || value == "") { value = "\u0001"; } msg += StringUtils.strPack(key, 3) + StringUtils.strPack(value, 3); } msg += "000"; } else { msg = StringUtils.strPack(HDR + buildApi(rpcName,sParams,"1"),5); string[] lines = StringUtils.split(text,StringUtils.CRLF); for (int i=0; i<lines.Length; i++) { msg += StringUtils.strPack(i.ToString(),3) + StringUtils.strPack(lines[i] + StringUtils.CRLF,3); } msg += "000"; } msg = getVersion() + msg; msg = PREFIX + StringUtils.strPack(msg,5); return msg; } internal string buildMessage_NatBroker() { const string PREFIX = "[XWB]"; const int COUNT_WIDTH = 3; const string RPC_VERSION = "1.108"; string sParams = "5"; // Don't ask my why - from the broker code for (int i = 0; i < parameters.Count; i++) { Parameter vp = (Parameter)parameters[i]; int pType = vp.Type; if (pType == LITERAL) { sParams += '0' + StringUtils.LPack(vp.Value, COUNT_WIDTH) + 'f'; } else if (pType == REFERENCE) { sParams += '1' + StringUtils.LPack(vp.Value, COUNT_WIDTH) + 'f'; } //else if (pType == EMPTY) //{ // sParams += "4f"; //} else if (pType == LIST) { sParams += '2' + list2string(vp.List); } //else if (pType == GLOBAL) //{ // sParams += '3' + list2string(vp.List); //} //else if (pType == STREAM) //{ // sParams += '5' + StringUtils.LPack(vp.Value, COUNT_WIDTH) + 'f'; //} } string msg = ""; // More inscrutable ugliness from the Delphi broker if (sParams == "5") { sParams += "4f"; } msg = PREFIX + "11" + Convert.ToString(COUNT_WIDTH) + "02" + StringUtils.SPack(RPC_VERSION) + StringUtils.SPack(rpcName) + sParams + '\x0004'; return msg; } internal string list2string(DictionaryHashList lst) { if (lst == null || lst.Count == 0) { return StringUtils.LPack("", 3) + 'f'; } string result = ""; for (int i = 0; i < lst.Count; i++) { DictionaryEntry entry = lst[i]; string key = (string)entry.Key; string value = (string)entry.Value; if (String.IsNullOrEmpty(value)) { value = "\u0001"; } result += StringUtils.LPack(key, 3) + StringUtils.LPack(value, 3) + 't'; } result = result.Substring(0, result.Length - 1) + 'f'; return result; } private string getVersion() { return "|" + Convert.ToChar(1) + "1"; } public class Parameter { bool encrypted = false; int myType; string myValue; string myText; string original; DictionaryHashList myList; public Parameter() { Type = -1; Value = ""; } public Parameter(int type, string value, bool encrypted = false) { Type = type; Value = value; this.encrypted = encrypted; if (encrypted) { Value = encrypt(value); original = value; } } public Parameter(int type, string value, string text) { Type = type; Value = value; Text = text; } public Parameter(int type, DictionaryHashList lst) { Type = type; Value = ".x"; List = lst; } public int Type { get { return myType; } set { myType = value; } } public string Value { get { return myValue; } set { myValue = value; } } public string Text { get { return myText; } set { myText = value; } } public string Original { get { return original; } } public bool Encrypted { get { return encrypted; } } public DictionaryHashList List { get { return myList; } set { myList = value; } } public static string encrypt(string inString) { const int MAXKEY = 19; string[] cipherPad = { "wkEo-ZJt!dG)49K{nX1BS$vH<&:Myf*>Ae0jQW=;|#PsO`\'%+rmb[gpqN,l6/hFC@DcUa ]z~R}\"V\\iIxu?872.(TYL5_3", "rKv`R;M/9BqAF%&tSs#Vh)dO1DZP> *fX\'u[.4lY=-mg_ci802N7LTG<]!CWo:3?{+,5Q}(@jaExn$~p\\IyHwzU\"|k6Jeb", "\\pV(ZJk\"WQmCn!Y,y@1d+~8s?[lNMxgHEt=uw|X:qSLjAI*}6zoF{T3#;ca)/h5%`P4$r]G\'9e2if_>UDKb7<v0&- RBO.", "depjt3g4W)qD0V~NJar\\B \"?OYhcu[<Ms%Z`RIL_6:]AX-zG.#}$@vk7/5x&*m;(yb2Fn+l\'PwUof1K{9,|EQi>H=CT8S!", "NZW:1}K$byP;jk)7\'`x90B|cq@iSsEnu,(l-hf.&Y_?J#R]+voQXU8mrV[!p4tg~OMez CAaGFD6H53%L/dT2<*>\"{\\wI=", "vCiJ<oZ9|phXVNn)m K`t/SI%]A5qOWe\\&?;jT~M!fz1l>[D_0xR32c*4.P\"G{r7}E8wUgyudF+6-:B=$(sY,LkbHa#\'@Q", "hvMX,\'4Ty;[a8/{6l~F_V\"}qLI\\!@x(D7bRmUH]W15J%N0BYPkrs&9:$)Zj>u|zwQ=ieC-oGA.#?tfdcO3gp`S+En K2*<", "jd!W5[];4\'<C$/&x|rZ(k{>?ghBzIFN}fAK\"#`p_TqtD*1E37XGVs@0nmSe+Y6Qyo-aUu%i8c=H2vJ\\) R:MLb.9,wlO~P", "2ThtjEM+!=xXb)7,ZV{*ci3\"8@_l-HS69L>]\\AUF/Q%:qD?1~m(yvO0e\'<#o$p4dnIzKP|`NrkaGg.ufCRB[; sJYwW}5&", "vB\\5/zl-9y:Pj|=(R\'7QJI *&CTX\"p0]_3.idcuOefVU#omwNZ`$Fs?L+1Sk<,b)hM4A6[Y%aDrg@~KqEW8t>H};n!2xG{", "sFz0Bo@_HfnK>LR}qWXV+D6`Y28=4Cm~G/7-5A\\b9!a#rP.l&M$hc3ijQk;),TvUd<[:I\"u1\'NZSOw]*gxtE{eJp|y (?%", "M@,D}|LJyGO8`$*ZqH .j>c~h<d=fimszv[#-53F!+a;NC\'6T91IV?(0x&/{B)w\"]Q\\YUWprk4:ol%g2nE7teRKbAPuS_X", ".mjY#_0*H<B=Q+FML6]s;r2:e8R}[ic&KA 1w{)vV5d,$u\"~xD/Pg?IyfthO@CzWp%!`N4Z\'3-(o|J9XUE7k\\TlqSb>anG", "xVa1\']_GU<X`|\\NgM?LS9{\"jT%s$}y[nvtlefB2RKJW~(/cIDCPow4,>#zm+:5b@06O3Ap8=*7ZFY!H-uEQk; .q)i&rhd", "I]Jz7AG@QX.\"%3Lq>METUo{Pp_ |a6<0dYVSv8:b)~W9NK`(r\'4fs&wim\\kReC2hg=HOj$1B*/nxt,;c#y+![?lFuZ-5D}", "Rr(Ge6F Hx>q$m&C%M~Tn,:\"o\'tX/*yP.{lZ!YkiVhuw_<KE5a[;}W0gjsz3]@7cI2\\QN?f#4p|vb1OUBD9)=-LJA+d`S8", "I~k>y|m};d)-7DZ\"Fe/Y<B:xwojR,Vh]O0Sc[`$sg8GXE!1&Qrzp._W%TNK(=J 3i*2abuHA4C\'?Mv\\Pq{n#56LftUl@9+", "~A*>9 WidFN,1KsmwQ)GJM{I4:C%}#Ep(?HB/r;t.&U8o|l[\'Lg\"2hRDyZ5`nbf]qjc0!zS-TkYO<_=76a\\X@$Pe3+xVvu", "yYgjf\"5VdHc#uA,W1i+v\'6|@pr{n;DJ!8(btPGaQM.LT3oe?NB/&9>Z`-}02*%x<7lsqz4OS ~E$\\R]KI[:UwC_=h)kXmF", "5:iar.{YU7mBZR@-K|2 \"+~`M%8sq4JhPo<_X\\Sg3WC;Tuxz,fvEQ1p9=w}FAI&j/keD0c?)LN6OHV]lGy\'$*>nd[(tb!#" }; Random r = new Random(); int associatorIndex = r.Next(MAXKEY); int identifierIndex = r.Next(MAXKEY); while (associatorIndex == identifierIndex) { identifierIndex = r.Next(MAXKEY); } string xlatedString = ""; for (int i = 0; i < inString.Length; i++) { char inChar = inString[i]; int pos = cipherPad[associatorIndex].IndexOf(inChar); if (pos == -1) { xlatedString += inChar; } else { xlatedString += cipherPad[identifierIndex][pos]; } } return (char)(associatorIndex + 32) + xlatedString + (char)(identifierIndex + 32); } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of 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.LayoutRenderers { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using NLog.Config; using NLog.Internal; using NLog.Targets; /// <summary> /// XML event description compatible with log4j, Chainsaw and NLogViewer. /// </summary> [LayoutRenderer("log4jxmlevent")] public class Log4JXmlEventLayoutRenderer : LayoutRenderer, IUsesStackTrace { private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1); private static readonly string dummyNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid(); private static readonly string dummyNLogNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid(); /// <summary> /// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class. /// </summary> public Log4JXmlEventLayoutRenderer() { this.IncludeNLogData = true; this.NdcItemSeparator = " "; #if NET_CF this.AppInfo = ".NET CF Application"; #elif SILVERLIGHT this.AppInfo = "Silverlight Application"; #else this.AppInfo = string.Format( CultureInfo.InvariantCulture, "{0}({1})", AppDomain.CurrentDomain.FriendlyName, ThreadIDHelper.Instance.CurrentProcessID); #endif this.Parameters = new List<NLogViewerParameterInfo>(); } /// <summary> /// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema. /// </summary> /// <docgen category='Payload Options' order='10' /> [DefaultValue(true)] public bool IncludeNLogData { get; set; } /// <summary> /// Gets or sets a value indicating whether the XML should use spaces for indentation. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IndentXml { get; set; } /// <summary> /// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain. /// </summary> /// <docgen category='Payload Options' order='10' /> public string AppInfo { get; set; } #if !NET_CF /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeCallSite { get; set; } /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeSourceInfo { get; set; } #endif /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeMdc { get; set; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsContext"/> stack. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNdc { get; set; } /// <summary> /// Gets or sets the NDC item separator. /// </summary> /// <docgen category='Payload Options' order='10' /> [DefaultValue(" ")] public string NdcItemSeparator { get; set; } /// <summary> /// Gets the level of stack trace information required by the implementing class. /// </summary> StackTraceUsage IUsesStackTrace.StackTraceUsage { get { #if !NET_CF if (this.IncludeSourceInfo) { return StackTraceUsage.Max; } if (this.IncludeCallSite) { return StackTraceUsage.WithoutSource; } #endif return StackTraceUsage.None; } } internal IList<NLogViewerParameterInfo> Parameters { get; set; } internal void AppendToStringBuilder(StringBuilder sb, LogEventInfo logEvent) { this.Append(sb, logEvent); } /// <summary> /// Renders the XML logging event and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { var settings = new XmlWriterSettings { Indent = this.IndentXml, ConformanceLevel = ConformanceLevel.Fragment, IndentChars = " ", }; var sb = new StringBuilder(); using (XmlWriter xtw = XmlWriter.Create(sb, settings)) { xtw.WriteStartElement("log4j", "event", dummyNamespace); xtw.WriteAttributeString("xmlns", "nlog", null, dummyNLogNamespace); xtw.WriteAttributeString("logger", logEvent.LoggerName); xtw.WriteAttributeString("level", logEvent.Level.Name.ToUpper(CultureInfo.InvariantCulture)); xtw.WriteAttributeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture)); xtw.WriteAttributeString("thread", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture)); xtw.WriteElementString("log4j", "message", dummyNamespace, logEvent.FormattedMessage); if (this.IncludeNdc) { xtw.WriteElementString("log4j", "NDC", dummyNamespace, string.Join(this.NdcItemSeparator, NestedDiagnosticsContext.GetAllMessages())); } if (logEvent.Exception != null) { xtw.WriteStartElement("log4j", "throwable", dummyNamespace); xtw.WriteCData(logEvent.Exception.ToString()); xtw.WriteEndElement(); } #if !NET_CF if (this.IncludeCallSite || this.IncludeSourceInfo) { System.Diagnostics.StackFrame frame = logEvent.UserStackFrame; MethodBase methodBase = frame.GetMethod(); Type type = methodBase.DeclaringType; xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace); if (type != null) { xtw.WriteAttributeString("class", type.FullName); } xtw.WriteAttributeString("method", methodBase.ToString()); #if !SILVERLIGHT if (this.IncludeSourceInfo) { xtw.WriteAttributeString("file", frame.GetFileName()); xtw.WriteAttributeString("line", frame.GetFileLineNumber().ToString(CultureInfo.InvariantCulture)); } #endif xtw.WriteEndElement(); if (this.IncludeNLogData) { xtw.WriteElementString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture)); xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace); if (type != null) { xtw.WriteAttributeString("assembly", type.Assembly.FullName); } xtw.WriteEndElement(); } } #endif xtw.WriteStartElement("log4j", "properties", dummyNamespace); if (this.IncludeMdc) { foreach (KeyValuePair<string, string> entry in MappedDiagnosticsContext.ThreadDictionary) { xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeString("name", entry.Key); xtw.WriteAttributeString("value", entry.Value); xtw.WriteEndElement(); } } foreach (NLogViewerParameterInfo parameter in this.Parameters) { xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeString("name", parameter.Name); xtw.WriteAttributeString("value", parameter.Layout.Render(logEvent)); xtw.WriteEndElement(); } xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeString("name", "log4japp"); xtw.WriteAttributeString("value", this.AppInfo); xtw.WriteEndElement(); xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeString("name", "log4jmachinename"); #if NET_CF xtw.WriteAttributeString("value", "netcf"); #elif SILVERLIGHT xtw.WriteAttributeString("value", "silverlight"); #else xtw.WriteAttributeString("value", Environment.MachineName); #endif xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.Flush(); // get rid of 'nlog' and 'log4j' namespace declarations sb.Replace(" xmlns:log4j=\"" + dummyNamespace + "\"", string.Empty); sb.Replace(" xmlns:nlog=\"" + dummyNLogNamespace + "\"", string.Empty); builder.Append(sb.ToString()); } } } }
// Copyright 2017 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 UnityEngine.EventSystems; using DaydreamElements.Common.IconMenu; using UnityEngine.Events; namespace DaydreamElements.ConstellationMenu { /// This script is attached to the game object responsible for spawning /// the Constellation menu. public class ConstellationMenuRoot : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { /// Controls size of Menu private const float MENU_SCALE = 0.1f; /// The position and orientation of the menu. private Vector3 menuCenter; private Quaternion menuOrientation = Quaternion.identity; /// Reticle distance to return to after closing the menu. private float reticleDistance; private ConstellationMenuIcon dummyParent; private bool selected; private bool graphDirty; [Tooltip("The tree of menu items")] [SerializeField] private ConstellationMenuTree menuTree; public GvrLaserPointer laserPointer; public UnityEvent OnMenuOpened; public UnityEvent OnMenuClosed; public ConstellationMenuItemEvent OnItemSelected; public ConstellationMenuItemEvent OnItemHovered; [System.Serializable] public class ConstellationMenuItemEvent : UnityEvent<ConstellationMenuItem> { } public enum GvrMenuActivationButton { ClickButtonDown, ClickButtonUp, AppButtonDown, AppButtonUp } [Tooltip("Input event to trigger the menu")] public GvrMenuActivationButton menuActivationButton = GvrMenuActivationButton.ClickButtonDown; public enum GvrMenuActivationMode { Clutch, Click, WaitClutch, WaitClick } [Tooltip("Input event to trigger the menu")] public GvrMenuActivationMode menuActivationMode = GvrMenuActivationMode.Clutch; [Tooltip("Prefab used for each item in the menu")] public ConstellationMenuIcon menuIconPrefab; [Tooltip("Controls the length of the line between icons. Increase if using larger icons.")] [Range(0.1f, 50.0f)] public float lineShorteningDistance = .1f; [Tooltip("Maximum number of meters the reticle can move per second.")] [Range(0.1f, 50.0f)] public float reticleDelta = 10.0f; [Tooltip("Distance away from the controller of the menu in meters.")] [Range(0.6f, 5.0f)] public float menuDistance = 0.75f; [Tooltip("Angle away from the menu center to cause a closure.")] [Range(5.0f, 30.0f)] public float closeAngle = 15.0f; [Tooltip("Angle of gaze vs pointer needed to open a menu.")] [Range(30.0f, 50.0f)] public float openFovAngle = 35.0f; [Tooltip("Defines the decoration label to use for icons which are expandable")] public Sprite expandableIconDecoration; [Tooltip("Defines the background to use for icons which are not expandable")] public Sprite iconBackground; [Tooltip("Seconds the laser has to point at an icon make it hover. Only applies to icons not" + " in the highlighted path")] [Range(0.0f, 1.0f)] public float hoverDelay = 0.1f; /// The icon most recently in the hover state. /// If another icon starts to hover this one will stop /// The hover icon is also used to estimate menu depth private ConstellationMenuIcon hoverIcon; /// A cached search result for the icon at the deepest level. /// It may be deleted at any moment, or may be closed and not visible. private ConstellationMenuIcon deepestIcon; /// Scale factor to apply to the menuDistance used to /// determine the max distance of the pointer. Without this scale factor, /// the max distance will fall short of the menu by an increasing amount as the /// pointer moves away from the center of the menu. private const float POINTER_DISTANCE_SCALE = 1.15f; void Awake() { selected = false; } public bool IsMenuOpen() { return (dummyParent != null) && (dummyParent.State != IconState.Closed); } /// Determine if the activation button is held down. private bool IsButtonClicked() { switch (menuActivationButton) { case GvrMenuActivationButton.ClickButtonDown: return GvrControllerInput.ClickButtonDown; case GvrMenuActivationButton.ClickButtonUp: return GvrControllerInput.ClickButtonUp; case GvrMenuActivationButton.AppButtonDown: return GvrControllerInput.AppButtonDown; case GvrMenuActivationButton.AppButtonUp: return GvrControllerInput.AppButtonUp; default: return false; } } private void SetMenuLocation() { Vector3 laserEndPt = laserPointer.GetPointAlongPointer(menuDistance); /* // Get the position and orientation from the arm model. Vector3 pointerPosition = laserPointer.transform.position; Vector3 ray = laserPointer.transform.rotation * Vector3.forward; // Calculate the intersection of the point with the head sphere. laserEndPt = pointerPosition + ray * menuDistance;*/ // Center and orient the menu menuCenter = laserEndPt; Vector3 headRight = Camera.main.transform.right; headRight.y = 0.0f; headRight.Normalize(); Vector3 cameraCenter = Camera.main.transform.position; Vector3 rayFromCamera = (laserEndPt - cameraCenter).normalized; Vector3 up = Vector3.Cross(rayFromCamera, headRight); menuOrientation = Quaternion.LookRotation(rayFromCamera, up); } private bool IsMenuInFOV() { Vector3 cameraCenter = Camera.main.transform.position; Vector3 menuCenterRelativeToCamera = menuCenter - cameraCenter; Vector3 gazeDirection = Camera.main.transform.rotation * Vector3.forward; return Vector3.Angle(menuCenterRelativeToCamera.normalized, gazeDirection.normalized) < openFovAngle; } private bool IsPointingAway() { if (!laserPointer.IsAvailable) { return true; } // Get the position and orientation form the arm model Vector3 laserEnd = laserPointer.MaxPointerEndPoint; Vector3 cameraCenter = Camera.main.transform.position; Vector3 menuCenterRelativeToCamera = menuCenter - cameraCenter; Vector3 laserEndRelativeToCamera = laserEnd - cameraCenter; float angleToMenuCenter = Vector3.Angle(laserEndRelativeToCamera.normalized, menuCenterRelativeToCamera.normalized); if (angleToMenuCenter < closeAngle) { return false; } return IsPointingAwayFromIcon(cameraCenter, laserEndRelativeToCamera.normalized, dummyParent); } private bool IsPointingAwayFromIcon(Vector3 cameraCenter, Vector3 laserEndToCameraNormalized, ConstellationMenuIcon icon) { if (icon == null) { return true; } return icon.GetClosestAngle(cameraCenter, laserEndToCameraNormalized) > closeAngle; } public void CloseAll() { selected = false; if (IsMenuOpen()) { dummyParent.CloseRecursive(); laserPointer.defaultReticleDistance = reticleDistance; if (OnMenuClosed != null) { OnMenuClosed.Invoke(); } } } void Update() { // Update the menu state if it needs to suddenly open or close if (!dummyParent && IsButtonClicked()) { SetMenuLocation(); if (IsMenuInFOV()) { reticleDistance = laserPointer.defaultReticleDistance; laserPointer.defaultReticleDistance = menuDistance * POINTER_DISTANCE_SCALE; dummyParent = ShowRootIcon(); } } else if ((GvrControllerInput.ClickButtonDown && !selected) || IsPointingAway()) { CloseAll(); } else if (dummyParent && GvrControllerInput.AppButtonUp) { CloseAll(); } } /// Helper function to create a top level icon. /// The root icon does not have any interaction or icon /// ShowRootIcon() initializes the root icon and opens the next level of icons. private ConstellationMenuIcon ShowRootIcon() { ConstellationMenuIcon rootIcon = (ConstellationMenuIcon)Instantiate(menuIconPrefab, transform); rootIcon.transform.position = menuCenter; rootIcon.transform.rotation = menuOrientation; rootIcon.Initialize(this, menuTree.tree.Root, MENU_SCALE); ConstellationMenuIcon.ShowMenu(this, menuTree.tree.Root, rootIcon, menuOrientation, MENU_SCALE); rootIcon.SetDummy(); if (OnMenuOpened != null) { OnMenuOpened.Invoke(); } return rootIcon; } public void OnPointerEnter(PointerEventData eventData) { selected = true; } public void OnPointerExit(PointerEventData eventData) { selected = false; } public void MakeSelection(ConstellationMenuItem item) { if (OnItemSelected != null) { OnItemSelected.Invoke(item); } } public void MakeHover(ConstellationMenuItem item) { if (OnItemHovered != null) { OnItemHovered.Invoke(item); } } /// Force cache clean after nodes are added/removed public void MarkGraphDirty() { graphDirty = true; } public float MenuDepth() { if (dummyParent == null) { return 0; } float hoverDepth = 0; if (hoverIcon != null) { // hovering on leaf node moves the menu deeper as if it had children. // This is so hovering has the same results across siblings. hoverDepth = (hoverIcon.MenuLayer + 1); } if (graphDirty) { deepestIcon = dummyParent.GetDeepestIcon(); graphDirty = false; } return Mathf.Max(hoverDepth, deepestIcon.MenuLayer); } public ConstellationMenuIcon GetHoverIcon() { return hoverIcon; } public void StartFadeOnIcon(ConstellationMenuIcon icon, IconState newState) { bool hoverChanged = false; if (newState == IconState.Hovering) { if (hoverIcon != null) { hoverIcon.FadeIfNeeded(IconState.Hovering, IconState.Shown); } hoverIcon = icon; hoverChanged = true; } if (icon == hoverIcon && newState == IconState.Closed) { hoverIcon = null; hoverChanged = true; } if (hoverChanged) { dummyParent.OnHoverChange(GetHoverIcon()); } } } }
// 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UpgradeProject; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Async { public partial class UpgradeProjectTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpUpgradeProjectCodeFixProvider()); private async Task TestLanguageVersionUpgradedAsync( string initialMarkup, LanguageVersion expected, ParseOptions parseOptions, int index = 0) { var parameters = new TestParameters(parseOptions: parseOptions); using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var actions = await GetCodeActionsAsync(workspace, parameters); var operations = await VerifyInputsAndGetOperationsAsync(index, actions, priority: null); var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations); var oldSolution = appliedChanges.Item1; var newSolution = appliedChanges.Item2; Assert.True(newSolution.Projects.Where(p => p.Language == LanguageNames.CSharp) .All(p => ((CSharpParseOptions)p.ParseOptions).SpecifiedLanguageVersion == expected)); } await TestAsync(initialMarkup, initialMarkup, parseOptions); // no change to markup } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeProjectFromCSharp6ToDefault() { await TestLanguageVersionUpgradedAsync( @" class Program { void A() { var x = [|(1, 2)|]; } }", LanguageVersion.Default, new CSharpParseOptions(LanguageVersion.CSharp6)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeProjectFromCSharp6ToCSharp7() { await TestLanguageVersionUpgradedAsync( @" class Program { void A() { var x = [|(1, 2)|]; } }", LanguageVersion.CSharp7, new CSharpParseOptions(LanguageVersion.CSharp6), index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeProjectFromCSharp5ToCSharp6() { await TestLanguageVersionUpgradedAsync( @" class Program { void A() { var x = [|nameof(A)|]; } }", LanguageVersion.CSharp6, new CSharpParseOptions(LanguageVersion.CSharp5), index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeProjectFromCSharp4ToCSharp5() { await TestLanguageVersionUpgradedAsync( @" class Program { void A() { Func<int, Task<int>> f = [|async|] x => x; } }", LanguageVersion.CSharp5, new CSharpParseOptions(LanguageVersion.CSharp4), index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeProjectFromCSharp7ToLatest() { await TestLanguageVersionUpgradedAsync( @" class Program { #error version:[|7.1|] }", LanguageVersion.Latest, new CSharpParseOptions(LanguageVersion.CSharp7)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeProjectFromCSharp7ToLatest_TriggeredByInferredTupleNames() { await TestLanguageVersionUpgradedAsync( @" class Program { void M() { int b = 2; var t = (1, b); System.Console.Write(t.[|b|]); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } } ", LanguageVersion.Latest, new CSharpParseOptions(LanguageVersion.CSharp7)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeProjectFromCSharp7_1ToLatest() { await TestLanguageVersionUpgradedAsync( @" class Program { #error version:[|7.1|] }", LanguageVersion.Latest, new CSharpParseOptions(LanguageVersion.CSharp7_1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeProjectFromCSharp7ToCSharp7_1() { await TestLanguageVersionUpgradedAsync( @" class Program { #error [|version:7.1|] }", LanguageVersion.CSharp7_1, new CSharpParseOptions(LanguageVersion.CSharp7), index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeProjectFromCSharp7ToCSharp7_1_B() { await TestLanguageVersionUpgradedAsync( @"public class Base { } public class Derived : Base { } public class Program { public static void M<T>(T x) where T: Base { System.Console.Write(x is [|Derived|] b0); } } ", LanguageVersion.CSharp7_1, new CSharpParseOptions(LanguageVersion.CSharp7), index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeAllProjectsToDefault() { await TestLanguageVersionUpgradedAsync( @"<Workspace> <Project Language=""C#"" LanguageVersion=""6""> <Document> class C { void A() { var x = [|(1, 2)|]; } } </Document> </Project> <Project Language=""C#"" LanguageVersion=""6""> </Project> <Project Language=""C#"" LanguageVersion=""Default""> </Project> <Project Language=""C#"" LanguageVersion=""7""> </Project> <Project Language=""Visual Basic""> </Project> </Workspace>", LanguageVersion.Default, parseOptions: null, index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeAllProjectsToCSharp7() { await TestLanguageVersionUpgradedAsync( @"<Workspace> <Project Language=""C#"" LanguageVersion=""6""> <Document> class C { void A() { var x = [|(1, 2)|]; } } </Document> </Project> <Project Language=""C#"" LanguageVersion=""6""> </Project> <Project Language=""C#"" LanguageVersion=""Default""> </Project> <Project Language=""C#"" LanguageVersion=""7""> </Project> <Project Language=""Visual Basic""> </Project> </Workspace>", LanguageVersion.Default, parseOptions: null, index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task ListAllSuggestions() { await TestExactActionSetOfferedAsync( @"<Workspace> <Project Language=""C#"" LanguageVersion=""6""> <Document> class C { void A() { var x = [|(1, 2)|]; } } </Document> </Project> <Project Language=""C#"" LanguageVersion=""7""> </Project> <Project Language=""C#"" LanguageVersion=""Default""> </Project> </Workspace>", new[] { string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "default"), string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "7"), string.Format(CSharpFeaturesResources.Upgrade_all_csharp_projects_to_language_version_0, "default"), string.Format(CSharpFeaturesResources.Upgrade_all_csharp_projects_to_language_version_0, "7") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task FixAllProjectsNotOffered() { await TestExactActionSetOfferedAsync( @"<Workspace> <Project Language=""C#"" LanguageVersion=""6""> <Document> class C { void A() { var x = [|(1, 2)|]; } } </Document> </Project> <Project Language=""Visual Basic""> </Project> </Workspace>", new[] { string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "default"), string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "7") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task OnlyOfferFixAllProjectsToCSharp7WhenApplicable() { await TestExactActionSetOfferedAsync( @"<Workspace> <Project Language=""C#"" LanguageVersion=""6""> <Document> class C { void A() { var x = [|(1, 2)|]; } } </Document> </Project> <Project Language=""C#"" LanguageVersion=""7""> </Project> <Project Language=""Visual Basic""> </Project> </Workspace>", new[] { string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "default"), string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "7"), string.Format(CSharpFeaturesResources.Upgrade_all_csharp_projects_to_language_version_0, "default") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task OnlyOfferFixAllProjectsToDefaultWhenApplicable() { await TestExactActionSetOfferedAsync( @"<Workspace> <Project Language=""C#"" LanguageVersion=""6""> <Document> class C { void A() { var x = [|(1, 2)|]; } } </Document> </Project> <Project Language=""C#"" LanguageVersion=""Default""> </Project> <Project Language=""Visual Basic""> </Project> </Workspace>", new[] { string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "default"), string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "7"), string.Format(CSharpFeaturesResources.Upgrade_all_csharp_projects_to_language_version_0, "7") }); } } }
//------------------------------------------------------------------------------ // <copyright file="COM2Properties.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms.ComponentModel.Com2Interop { using System.Runtime.Remoting; using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; using System; using System.Collections; using System.Collections.Generic; using Microsoft.Win32; /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties"]/*' /> /// <devdoc> /// This class is responsible for managing a set or properties for a native object. It determines /// when the properties need to be refreshed, and owns the extended handlers for those properties. /// </devdoc> internal class Com2Properties { private static TraceSwitch DbgCom2PropertiesSwitch = new TraceSwitch("DbgCom2Properties", "Com2Properties: debug Com2 properties manager"); /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.AGE_THRESHHOLD"]/*' /> /// <devdoc> /// This is the interval that we'll hold props for. If someone doesn't touch an object /// for this amount of time, we'll dump the properties from our cache. /// /// 5 minutes -- ticks are 1/10,000,000th of a second /// </devdoc> private static long AGE_THRESHHOLD = (long)(10000000L * 60L * 5L); /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.weakObjRef"]/*' /> /// <devdoc> /// This is the object that gave us the properties. We hold a WeakRef so we don't addref the object. /// </devdoc> internal WeakReference weakObjRef; /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.props"]/*' /> /// <devdoc> /// This is our list of properties. /// </devdoc> private Com2PropertyDescriptor[] props; /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.defaultIndex"]/*' /> /// <devdoc> /// The index of the default property /// </devdoc> private int defaultIndex = -1; /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.touchedTime"]/*' /> /// <devdoc> /// The timestamp of the last operation on this property manager, usually /// when the property list was fetched. /// </devdoc> private long touchedTime; /// <devdoc> /// For non-IProvideMultipleClassInfo ITypeInfos, this is the version number on the last /// ITypeInfo we looked at. If this changes, we know we need to dump the cache. /// </devdoc> private long[] typeInfoVersions; #if DEBUG private string dbgObjName; private string dbgObjClass; #endif private int alwaysValid = 0; /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.extendedInterfaces"]/*' /> /// <devdoc> /// These are the interfaces we recognize for extended browsing. /// </devdoc> private static Type[] extendedInterfaces = new Type[]{ typeof(NativeMethods.ICategorizeProperties), typeof(NativeMethods.IProvidePropertyBuilder), typeof(NativeMethods.IPerPropertyBrowsing), typeof(NativeMethods.IVsPerPropertyBrowsing), typeof(NativeMethods.IManagedPerPropertyBrowsing)}; /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.extendedInterfaceHandlerTypes"]/*' /> /// <devdoc> /// These are the classes of handlers corresponding to the extended /// interfaces above. /// </devdoc> private static Type[] extendedInterfaceHandlerTypes = new Type[]{ typeof(Com2ICategorizePropertiesHandler), typeof(Com2IProvidePropertyBuilderHandler), typeof(Com2IPerPropertyBrowsingHandler), typeof(Com2IVsPerPropertyBrowsingHandler), typeof(Com2IManagedPerPropertyBrowsingHandler)}; public event EventHandler Disposed; /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.Com2Properties"]/*' /> /// <devdoc> /// Default ctor. /// </devdoc> public Com2Properties(object obj, Com2PropertyDescriptor[] props, int defaultIndex) { #if DEBUG ComNativeDescriptor cnd = new ComNativeDescriptor(); this.dbgObjName = cnd.GetName(obj); if (this.dbgObjName == null) { this.dbgObjName = "(null)"; } this.dbgObjClass = cnd.GetClassName(obj); if (this.dbgObjClass == null) { this.dbgObjClass = "(null)"; } if (DbgCom2PropertiesSwitch.TraceVerbose) Debug.WriteLine("Creating Com2Properties for object " + dbgObjName + ", class=" + dbgObjClass); #endif // set up our variables SetProps(props); weakObjRef = new WeakReference(obj); this.defaultIndex = defaultIndex; typeInfoVersions = GetTypeInfoVersions(obj); touchedTime = DateTime.Now.Ticks; } internal bool AlwaysValid { get { return this.alwaysValid > 0; } set { if (value) { if (alwaysValid == 0 && !CheckValid()) { return; } this.alwaysValid++; } else { if (alwaysValid > 0) { this.alwaysValid--; } } } } /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.DefaultProperty"]/*' /> /// <devdoc> /// Retrieve the default property. /// </devdoc> public Com2PropertyDescriptor DefaultProperty{ get{ if (!CheckValid(true)) { return null; } if (defaultIndex == -1) { if (props.Length > 0) { return props[0]; } else { return null; } } Debug.Assert(defaultIndex < props.Length, "Whoops! default index is > props.Length"); return props[defaultIndex]; } } /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.TargetObject"]/*' /> /// <devdoc> /// The object that created the list of properties. This will /// return null if the timeout has passed or the ref has died. /// </devdoc> public object TargetObject{ get{ if (!CheckValid(false) || touchedTime == 0) { #if DEBUG if (DbgCom2PropertiesSwitch.TraceVerbose) Debug.WriteLine("CheckValid called on dead object!"); #endif return null; } return weakObjRef.Target; } } /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.TicksSinceTouched"]/*' /> /// <devdoc> /// How long since these props have been queried. /// </devdoc> public long TicksSinceTouched{ get{ if (touchedTime == 0) { return 0; } return DateTime.Now.Ticks - touchedTime; } } /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.Properties"]/*' /> /// <devdoc> /// Returns the list of properties /// </devdoc> public Com2PropertyDescriptor[] Properties{ get{ CheckValid(true); if (touchedTime == 0 || props == null) { return null; } touchedTime = DateTime.Now.Ticks; // refresh everyone! for (int i = 0; i < props.Length; i++) { props[i].SetNeedsRefresh(Com2PropertyDescriptorRefresh.All, true); } #if DEBUG if (DbgCom2PropertiesSwitch.TraceVerbose) Debug.WriteLine("Returning prop array for object " + dbgObjName + ", class=" + dbgObjClass); #endif return props; } } /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.TooOld"]/*' /> /// <devdoc> /// Should this guy be refreshed because of old age? /// </devdoc> public bool TooOld{ get{ // check if the property is valid but don't dispose it if it's not CheckValid(false, false); if (touchedTime == 0) { return false; } return TicksSinceTouched > AGE_THRESHHOLD; } } /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.AddExtendedBrowsingHandlers"]/*' /> /// <devdoc> /// Checks the source object for eache extended browsing inteface /// listed in extendedInterfaces and creates a handler from extendedInterfaceHandlerTypes /// to handle it. /// </devdoc> public void AddExtendedBrowsingHandlers(Hashtable handlers) { object target = this.TargetObject; if (target == null) { return; } // process all our registered types Type t; for (int i = 0; i < extendedInterfaces.Length; i++) { t = extendedInterfaces[i]; // is this object an implementor of the interface? // if (t.IsInstanceOfType(target)) { // since handlers must be stateless, check to see if we've already // created one of this type // Com2ExtendedBrowsingHandler handler = (Com2ExtendedBrowsingHandler)handlers[t]; if (handler == null) { handler = (Com2ExtendedBrowsingHandler)Activator.CreateInstance(extendedInterfaceHandlerTypes[i]); handlers[t] = handler; } // make sure we got the right one // if (t.IsAssignableFrom(handler.Interface)) { #if DEBUG if (DbgCom2PropertiesSwitch.TraceVerbose) Debug.WriteLine("Adding browsing handler type " + handler.Interface.Name + " to object " + dbgObjName + ", class=" + dbgObjClass); #endif // allow the handler to attach itself to the appropriate properties // handler.SetupPropertyHandlers(props); } else { throw new ArgumentException(SR.GetString(SR.COM2BadHandlerType, t.Name, handler.Interface.Name)); } } } } public void Dispose() { #if DEBUG if (DbgCom2PropertiesSwitch.TraceVerbose) Debug.WriteLine("Disposing property manager for " + dbgObjName + ", class=" + dbgObjClass); #endif if (props != null) { if (Disposed != null) { Disposed(this, EventArgs.Empty); } weakObjRef = null; props = null; touchedTime = 0; } } public bool CheckValid() { return CheckValid(false); } /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.CheckValid"]/*' /> /// <devdoc> /// Make sure this property list is still valid. /// /// 1) WeakRef is still alive /// 2) Our timeout hasn't passed /// </devdoc> public bool CheckValid(bool checkVersions) { return CheckValid(checkVersions, true); } /// <devdoc> /// Gets a list of version longs for each type info in the COM object /// representing hte current version stamp, function and variable count. /// If any of these things change, we'll re-fetch the properties. /// </devdoc> private long[] GetTypeInfoVersions(object comObject) { // get type infos // UnsafeNativeMethods.ITypeInfo[] pTypeInfos = Com2TypeInfoProcessor.FindTypeInfos(comObject, false); // build up the info. // long[] versions = new long[pTypeInfos.Length]; for (int i = 0; i < pTypeInfos.Length; i++) { versions [i] = GetTypeInfoVersion(pTypeInfos[i]); } return versions; } private static int countOffset = -1; private static int versionOffset = -1; // we define a struct here so we can use unsafe code to marshal it // as a blob of memory. This is here as a reference to how big and where the members are. // /*private struct tagTYPEATTR { public Guid guid; //16 public int lcid; // 4 public int dwReserved; // 4 public int memidConstructor; // 4 public int memidDestructor; // 4 public IntPtr lpstrSchema; // platform public int cbSizeInstance; // 4 public int typekind; // 4 public short cFuncs; // 2 public short cVars; // 2 public short cImplTypes; // 2 public short cbSizeVft; // 2 public short cbAlignment; // 2 public short wTypeFlags; // 2 public short wMajorVerNum; // 2 public short wMinorVerNum; // 2 public int tdescAlias_unionMember; public short tdescAlias_vt; public int idldescType_dwReserved; public short idldescType_wIDLFlags; }*/ // the offset of the cFunc member in the TYPEATTR structure. // private static int CountMemberOffset { get { if (countOffset == -1) { countOffset = Marshal.SizeOf(typeof(Guid)) + IntPtr.Size + 24; } return countOffset; } } // the offset of the cMajorVerNum member in the TYPEATTR structure. // private static int VersionOffset { get { if (versionOffset == -1) { versionOffset = CountMemberOffset + 12; } return versionOffset; } } private unsafe long GetTypeInfoVersion(UnsafeNativeMethods.ITypeInfo pTypeInfo) { IntPtr pTypeAttr = IntPtr.Zero; int hr = pTypeInfo.GetTypeAttr(ref pTypeAttr); if (!NativeMethods.Succeeded(hr)) { return 0; } System.Runtime.InteropServices.ComTypes.TYPEATTR pTAStruct; try { try { // just access directly...no marshalling needed! // pTAStruct = *(System.Runtime.InteropServices.ComTypes.TYPEATTR*)pTypeAttr; } catch { return 0; } long result = 0; // we pull two things out of the struct: the // number of functions and variables, and the version. // since they are next to each other, we just pull the memory directly. // // the cFuncs and cVars are both shorts, so we read them as one block of ints. // // int* pResult = (int*)&result; byte* pbStruct = (byte*)&pTAStruct; // in the low byte, pull the number of props. // *pResult = *(int*)(pbStruct + CountMemberOffset); // move up to the high word of the long. // pResult++; // now pull out the version info. // *pResult = *(int*)(pbStruct + VersionOffset); // return that composite long. // return result; } finally { pTypeInfo.ReleaseTypeAttr(pTypeAttr); } } internal bool CheckValid(bool checkVersions, bool callDispose) { if (this.AlwaysValid) { return true; } bool valid = weakObjRef != null && weakObjRef.IsAlive; // check the version information for each ITypeInfo the object exposes. // if (valid && checkVersions) { // long[] newTypeInfoVersions = GetTypeInfoVersions(weakObjRef.Target); if (newTypeInfoVersions.Length != typeInfoVersions.Length) { valid = false; } else { // compare each version number to the old one. // for (int i = 0; i < newTypeInfoVersions.Length; i++) { if (newTypeInfoVersions[i] != typeInfoVersions[i]) { valid = false; break; } } } if (!valid) { // update to the new version list we have. // typeInfoVersions = newTypeInfoVersions; } } if (!valid && callDispose) { // weak ref has died, so remove this from the hash table // #if DEBUG if (DbgCom2PropertiesSwitch.TraceVerbose) Debug.WriteLine("Disposing reference to object " + dbgObjName + ", class=" + dbgObjClass + " (weakRef " + (weakObjRef == null ? "null" : "dead") + ")"); #endif Dispose(); } return valid; } /// <include file='doc\COM2Properties.uex' path='docs/doc[@for="Com2Properties.SetProps"]/*' /> /// <devdoc> /// Set the props for this object, and notify each property /// that we are now it's manager /// </devdoc> internal void SetProps(Com2PropertyDescriptor[] props) { this.props = props; if (props != null) { for (int i = 0; i < props.Length; i++) { props[i].PropertyManager = this; } } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// General Ledger Notes Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KNDataSet : EduHubDataSet<KN> { /// <inheritdoc /> public override string Name { get { return "KN"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KNDataSet(EduHubContext Context) : base(Context) { Index_NOTE_ID = new Lazy<Dictionary<string, KN>>(() => this.ToDictionary(i => i.NOTE_ID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KN" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KN" /> fields for each CSV column header</returns> internal override Action<KN, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KN, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "NOTE_ID": mapper[i] = (e, v) => e.NOTE_ID = v; break; case "CONTENTS": mapper[i] = (e, v) => e.CONTENTS = v; break; case "ACTIVE": mapper[i] = (e, v) => e.ACTIVE = v; break; case "SCOPE": mapper[i] = (e, v) => e.SCOPE = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KN" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KN" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KN" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KN}"/> of entities</returns> internal override IEnumerable<KN> ApplyDeltaEntities(IEnumerable<KN> Entities, List<KN> DeltaEntities) { HashSet<string> Index_NOTE_ID = new HashSet<string>(DeltaEntities.Select(i => i.NOTE_ID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.NOTE_ID; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_NOTE_ID.Remove(entity.NOTE_ID); if (entity.NOTE_ID.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, KN>> Index_NOTE_ID; #endregion #region Index Methods /// <summary> /// Find KN by NOTE_ID field /// </summary> /// <param name="NOTE_ID">NOTE_ID value used to find KN</param> /// <returns>Related KN entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KN FindByNOTE_ID(string NOTE_ID) { return Index_NOTE_ID.Value[NOTE_ID]; } /// <summary> /// Attempt to find KN by NOTE_ID field /// </summary> /// <param name="NOTE_ID">NOTE_ID value used to find KN</param> /// <param name="Value">Related KN entity</param> /// <returns>True if the related KN entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByNOTE_ID(string NOTE_ID, out KN Value) { return Index_NOTE_ID.Value.TryGetValue(NOTE_ID, out Value); } /// <summary> /// Attempt to find KN by NOTE_ID field /// </summary> /// <param name="NOTE_ID">NOTE_ID value used to find KN</param> /// <returns>Related KN entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KN TryFindByNOTE_ID(string NOTE_ID) { KN value; if (Index_NOTE_ID.Value.TryGetValue(NOTE_ID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KN table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KN]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KN]( [NOTE_ID] varchar(4) NOT NULL, [CONTENTS] varchar(MAX) NULL, [ACTIVE] varchar(1) NULL, [SCOPE] varchar(1) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KN_Index_NOTE_ID] PRIMARY KEY CLUSTERED ( [NOTE_ID] ASC ) ); END"); } /// <summary> /// Returns null as <see cref="KNDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns null as <see cref="KNDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KN"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KN"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KN> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_NOTE_ID = new List<string>(); foreach (var entity in Entities) { Index_NOTE_ID.Add(entity.NOTE_ID); } builder.AppendLine("DELETE [dbo].[KN] WHERE"); // Index_NOTE_ID builder.Append("[NOTE_ID] IN ("); for (int index = 0; index < Index_NOTE_ID.Count; index++) { if (index != 0) builder.Append(", "); // NOTE_ID var parameterNOTE_ID = $"@p{parameterIndex++}"; builder.Append(parameterNOTE_ID); command.Parameters.Add(parameterNOTE_ID, SqlDbType.VarChar, 4).Value = Index_NOTE_ID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KN data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KN data set</returns> public override EduHubDataSetDataReader<KN> GetDataSetDataReader() { return new KNDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KN data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KN data set</returns> public override EduHubDataSetDataReader<KN> GetDataSetDataReader(List<KN> Entities) { return new KNDataReader(new EduHubDataSetLoadedReader<KN>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KNDataReader : EduHubDataSetDataReader<KN> { public KNDataReader(IEduHubDataSetReader<KN> Reader) : base (Reader) { } public override int FieldCount { get { return 7; } } public override object GetValue(int i) { switch (i) { case 0: // NOTE_ID return Current.NOTE_ID; case 1: // CONTENTS return Current.CONTENTS; case 2: // ACTIVE return Current.ACTIVE; case 3: // SCOPE return Current.SCOPE; case 4: // LW_DATE return Current.LW_DATE; case 5: // LW_TIME return Current.LW_TIME; case 6: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // CONTENTS return Current.CONTENTS == null; case 2: // ACTIVE return Current.ACTIVE == null; case 3: // SCOPE return Current.SCOPE == null; case 4: // LW_DATE return Current.LW_DATE == null; case 5: // LW_TIME return Current.LW_TIME == null; case 6: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // NOTE_ID return "NOTE_ID"; case 1: // CONTENTS return "CONTENTS"; case 2: // ACTIVE return "ACTIVE"; case 3: // SCOPE return "SCOPE"; case 4: // LW_DATE return "LW_DATE"; case 5: // LW_TIME return "LW_TIME"; case 6: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "NOTE_ID": return 0; case "CONTENTS": return 1; case "ACTIVE": return 2; case "SCOPE": return 3; case "LW_DATE": return 4; case "LW_TIME": return 5; case "LW_USER": return 6; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #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.IO; using System.Collections.Specialized; using System.Net.Mail; using System.Runtime.ExceptionServices; namespace System.Net.Mime { internal abstract class BaseWriter { // This is the maximum default line length that can actually be written. When encoding // headers, the line length is more conservative to account for things like folding. // In MailWriter, all encoding has already been done so this will only fold lines // that are NOT encoded already, which means being less conservative is ok. private const int DefaultLineLength = 76; private static readonly AsyncCallback s_onWrite = OnWrite; protected static readonly byte[] s_crlf = new byte[] { (byte)'\r', (byte)'\n' }; protected readonly BufferBuilder _bufferBuilder; protected readonly Stream _stream; private readonly EventHandler _onCloseHandler; private readonly bool _shouldEncodeLeadingDots; private readonly int _lineLength; protected Stream _contentStream; protected bool _isInContent; protected BaseWriter(Stream stream, bool shouldEncodeLeadingDots) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } _stream = stream; _shouldEncodeLeadingDots = shouldEncodeLeadingDots; _onCloseHandler = new EventHandler(OnClose); _bufferBuilder = new BufferBuilder(); _lineLength = DefaultLineLength; } #region Headers internal abstract void WriteHeaders(NameValueCollection headers, bool allowUnicode); internal void WriteHeader(string name, string value, bool allowUnicode) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (_isInContent) { throw new InvalidOperationException(SR.MailWriterIsInContent); } CheckBoundary(); _bufferBuilder.Append(name); _bufferBuilder.Append(": "); WriteAndFold(value, name.Length + 2, allowUnicode); _bufferBuilder.Append(s_crlf); } private void WriteAndFold(string value, int charsAlreadyOnLine, bool allowUnicode) { int lastSpace = 0, startOfLine = 0; for (int index = 0; index < value.Length; index++) { // When we find a FWS (CRLF) copy it as is. if (MailBnfHelper.IsFWSAt(value, index)) // At the first char of "\r\n " or "\r\n\t" { index += 2; // Skip the FWS _bufferBuilder.Append(value, startOfLine, index - startOfLine, allowUnicode); // Reset for the next line startOfLine = index; lastSpace = index; charsAlreadyOnLine = 0; } // When we pass the line length limit, and know where there was a space to fold at, fold there else if (((index - startOfLine) > (_lineLength - charsAlreadyOnLine)) && lastSpace != startOfLine) { _bufferBuilder.Append(value, startOfLine, lastSpace - startOfLine, allowUnicode); _bufferBuilder.Append(s_crlf); startOfLine = lastSpace; charsAlreadyOnLine = 0; } // Mark a foldable space. If we go over the line length limit, fold here. else if (value[index] == MailBnfHelper.Space || value[index] == MailBnfHelper.Tab) { lastSpace = index; } } // Write any remaining data to the buffer. if (value.Length - startOfLine > 0) { _bufferBuilder.Append(value, startOfLine, value.Length - startOfLine, allowUnicode); } } #endregion Headers #region Content internal Stream GetContentStream() => GetContentStream(null); private Stream GetContentStream(MultiAsyncResult multiResult) { if (_isInContent) { throw new InvalidOperationException(SR.MailWriterIsInContent); } _isInContent = true; CheckBoundary(); _bufferBuilder.Append(s_crlf); Flush(multiResult); ClosableStream cs = new ClosableStream(new EightBitStream(_stream, _shouldEncodeLeadingDots), _onCloseHandler); _contentStream = cs; return cs; } internal IAsyncResult BeginGetContentStream(AsyncCallback callback, object state) { MultiAsyncResult multiResult = new MultiAsyncResult(this, callback, state); Stream s = GetContentStream(multiResult); if (!(multiResult.Result is Exception)) { multiResult.Result = s; } multiResult.CompleteSequence(); return multiResult; } internal Stream EndGetContentStream(IAsyncResult result) { object o = MultiAsyncResult.End(result); if (o is Exception e) { ExceptionDispatchInfo.Throw(e); } return (Stream)o; } #endregion Content #region Cleanup protected void Flush(MultiAsyncResult multiResult) { if (_bufferBuilder.Length > 0) { if (multiResult != null) { multiResult.Enter(); IAsyncResult result = _stream.BeginWrite(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length, s_onWrite, multiResult); if (result.CompletedSynchronously) { _stream.EndWrite(result); multiResult.Leave(); } } else { _stream.Write(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length); } _bufferBuilder.Reset(); } } protected static void OnWrite(IAsyncResult result) { if (!result.CompletedSynchronously) { MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState; BaseWriter thisPtr = (BaseWriter)multiResult.Context; try { thisPtr._stream.EndWrite(result); multiResult.Leave(); } catch (Exception e) { multiResult.Leave(e); } } } internal abstract void Close(); protected abstract void OnClose(object sender, EventArgs args); #endregion Cleanup protected virtual void CheckBoundary() { } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Data; using System.Windows.Forms; using System.Windows.Forms.Design; using System.ComponentModel.Design; using System.Drawing.Design; namespace Oranikle.Studio.Controls.Wizards { [ToolboxItem(false)] [Designer( "Oranikle.Studio.Controls.Designers.WizardPageDesigner, Oranikle.Studio.Controls.Designers, Version=1.0.4.0, Culture=neutral, PublicKeyToken=fe06e967d3cf723d" )] public class WizardPageBase : System.Windows.Forms.UserControl { #region Class Members private System.ComponentModel.Container components = null; // container private WizardForm m_parent = null; // page parent private int m_iIndex = -1; // Order identifier of page private string m_strTitle; // Page Title private string m_strDescription; // Page Desription private Image m_imgHeader; // Page Image private bool m_bFireEvents = true; // Identifier of QUIET mode private bool m_bFinishPage; // Is Wizard Page a Finish Page private bool m_bHelpExists; // Does page has Help or Not private bool m_bIsWelcome; // Is Page Use Full Wizard Panel or not private ImageList m_imgList; private int m_iImageIndex = -1; #endregion #region Class Properties [Browsable(true)] [DefaultValue(-1)] [Description("Order position of wizard page in Wizard Control")] [Category("Wizard Page")] public int Index { get { return m_iIndex; } set { if( value != m_iIndex ) { m_iIndex = value; OnIndexChanged(); OnChanged(); } } } [Browsable(false)] [Description("Gets/Sets Page Parent control")] public WizardForm WizardPageParent { get { return m_parent; } set { if( value != m_parent ) { m_parent = value; OnWizardPageParentChanged(); } } } [Browsable(true)] [Category("Wizard Page")] [Description("Gets/Sets wizard page Title Text")] public string Title { get { return m_strTitle; } set { if( value != m_strTitle ) { m_strTitle = value; OnTitleChanged(); OnChanged(); } } } [Browsable(true)] [Category("Wizard Page")] [Description("Gets/Sets wizard page description Text")] public string Description { get { return m_strDescription; } set { if( value != m_strDescription ) { m_strDescription = value; OnDescriptionChanged(); OnChanged(); } } } [Browsable(true)] [Category("Wizard Page")] [Description("Gets/Sets wizard page special Image")] [DefaultValue(null)] public Image HeaderImage { get { return m_imgHeader; } set { if( value != m_imgHeader ) { m_imgHeader = value; OnHeaderImageChanged(); OnChanged(); } } } [Browsable(true)] [Category("Wizard Page")] [Description("Gets/Sets wizard page special ImageList")] [DefaultValue(null)] public ImageList ImageList { get { return m_imgList; } set { if( value != m_imgList ) { m_imgList = value; OnImageListChanged(); OnChanged(); } } } [Browsable(true)] [Category("Wizard Page")] [Description("Gets/Sets Image from ImageList which will be used as a HeaderImage")] [DefaultValue(-1)] [Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor))] [TypeConverter("System.Windows.Forms.ImageIndexConverter")] public int ImageIndex { get { return m_iImageIndex; } set { if( value != m_iImageIndex ) { m_iImageIndex = value; OnImageIndexChanged(); OnChanged(); } } } [Browsable(false)] [DefaultValue(false)] public bool QuietMode { get { return !m_bFireEvents; } set { if( value != m_bFireEvents ) { m_bFireEvents = !value; OnQuietModeChanged(); } } } [Browsable(true)] [Category("Wizard Page")] [Description("Gets/Sets Is wizard page last in Wizard Control")] [DefaultValue(false)] public bool FinishPage { get { return m_bFinishPage; } set { if( value != m_bFinishPage ) { m_bFinishPage = value; OnFinishPageChanged(); OnChanged(); } } } [Browsable(true)] [Category("Wizard Page")] [Description("Gets/Sets Is wizard page Has help Page")] [DefaultValue(false)] public bool HelpAvailable { get { return m_bHelpExists; } set { if( value != m_bHelpExists ) { m_bHelpExists = value; OnHelpAvailableChangd(); OnChanged(); } } } [Browsable(true)] [Category("Wizard Page")] [Description("Gets/Sets Is wizard page is a Welcome Page")] [DefaultValue(false)] public bool WelcomePage { get { return m_bIsWelcome; } set { if( value != m_bIsWelcome ) { m_bIsWelcome = value; OnWelcomePageChanged(); OnChanged(); } } } protected override System.Drawing.Size DefaultSize { get { return new Size( 498, 328 ); } } #endregion #region Class Events [Category("Wizard Page")] public event EventHandler Changed; #endregion #region Class Initialze/Finilize methods /// <summary> /// Default constractor /// </summary> public WizardPageBase() { InitializeComponent(); base.Dock = DockStyle.Fill; } /// <summary> /// Free custom resources /// </summary> /// <param name="disposing">if TRUE then free resources</param> protected override void Dispose( bool disposing ) { if( disposing && components != null ) { components.Dispose(); } base.Dispose( disposing ); } #endregion #region Component Designer generated code /// <summary> /// Initialize Control /// </summary> private void InitializeComponent() { // // WizardPageBase // this.Name = "WizardPage"; this.Size = new System.Drawing.Size(424, 248); } #endregion #region Class overrides for inheritors protected virtual void OnIndexChanged(){} protected virtual void OnWizardPageParentChanged(){} protected virtual void OnTitleChanged(){} protected virtual void OnDescriptionChanged(){} protected virtual void OnHeaderImageChanged(){} protected virtual void OnImageListChanged(){} protected virtual void OnImageIndexChanged(){} protected virtual void OnQuietModeChanged(){} protected virtual void OnFinishPageChanged(){} protected virtual void OnHelpAvailableChangd(){} protected virtual void OnWelcomePageChanged(){} #endregion #region Class Overrides /// <summary> /// Function Raise "Changed" event when property of class changed /// </summary> protected virtual void OnChanged() { if( Changed != null && m_bFireEvents == true ) { Changed( this, EventArgs.Empty ); } } #endregion } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// RecipientEmailNotification /// </summary> [DataContract] public partial class RecipientEmailNotification : IEquatable<RecipientEmailNotification>, IValidatableObject { public RecipientEmailNotification() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="RecipientEmailNotification" /> class. /// </summary> /// <param name="EmailBody">Specifies the email body of the message sent to the recipient. Maximum length: 10000 characters. .</param> /// <param name="EmailBodyMetadata">EmailBodyMetadata.</param> /// <param name="EmailSubject">Specifies the subject of the email that is sent to all recipients. See [ML:Template Email Subject Merge Fields] for information about adding merge field information to the email subject..</param> /// <param name="EmailSubjectMetadata">EmailSubjectMetadata.</param> /// <param name="SupportedLanguage">A simple type enumeration of the language used. The supported languages, with the language value shown in parenthesis, are: Arabic (ar), Armenian (hy), Bahasa Indonesia (id), Bahasa Melayu (ms) Bulgarian (bg), Czech (cs), Chinese Simplified (zh_CN), Chinese Traditional (zh_TW), Croatian (hr), Danish (da), Dutch (nl), English US (en), English UK (en_GB), Estonian (et), Farsi (fa), Finnish (fi), French (fr), French Canada (fr_CA), German (de), Greek (el), Hebrew (he), Hindi (hi), Hungarian (hu), Italian (it), Japanese (ja), Korean (ko), Latvian (lv), Lithuanian (lt), Norwegian (no), Polish (pl), Portuguese (pt), Portuguese Brazil (pt_BR), Romanian (ro),Russian (ru), Serbian (sr), Slovak (sk), Slovenian (sl), Spanish (es),Spanish Latin America (es_MX), Swedish (sv), Thai (th), Turkish (tr), Ukrainian (uk), and Vietnamese (vi)..</param> /// <param name="SupportedLanguageMetadata">SupportedLanguageMetadata.</param> public RecipientEmailNotification(string EmailBody = default(string), PropertyMetadata EmailBodyMetadata = default(PropertyMetadata), string EmailSubject = default(string), PropertyMetadata EmailSubjectMetadata = default(PropertyMetadata), string SupportedLanguage = default(string), PropertyMetadata SupportedLanguageMetadata = default(PropertyMetadata)) { this.EmailBody = EmailBody; this.EmailBodyMetadata = EmailBodyMetadata; this.EmailSubject = EmailSubject; this.EmailSubjectMetadata = EmailSubjectMetadata; this.SupportedLanguage = SupportedLanguage; this.SupportedLanguageMetadata = SupportedLanguageMetadata; } /// <summary> /// Specifies the email body of the message sent to the recipient. Maximum length: 10000 characters. /// </summary> /// <value>Specifies the email body of the message sent to the recipient. Maximum length: 10000 characters. </value> [DataMember(Name="emailBody", EmitDefaultValue=false)] public string EmailBody { get; set; } /// <summary> /// Gets or Sets EmailBodyMetadata /// </summary> [DataMember(Name="emailBodyMetadata", EmitDefaultValue=false)] public PropertyMetadata EmailBodyMetadata { get; set; } /// <summary> /// Specifies the subject of the email that is sent to all recipients. See [ML:Template Email Subject Merge Fields] for information about adding merge field information to the email subject. /// </summary> /// <value>Specifies the subject of the email that is sent to all recipients. See [ML:Template Email Subject Merge Fields] for information about adding merge field information to the email subject.</value> [DataMember(Name="emailSubject", EmitDefaultValue=false)] public string EmailSubject { get; set; } /// <summary> /// Gets or Sets EmailSubjectMetadata /// </summary> [DataMember(Name="emailSubjectMetadata", EmitDefaultValue=false)] public PropertyMetadata EmailSubjectMetadata { get; set; } /// <summary> /// A simple type enumeration of the language used. The supported languages, with the language value shown in parenthesis, are: Arabic (ar), Armenian (hy), Bahasa Indonesia (id), Bahasa Melayu (ms) Bulgarian (bg), Czech (cs), Chinese Simplified (zh_CN), Chinese Traditional (zh_TW), Croatian (hr), Danish (da), Dutch (nl), English US (en), English UK (en_GB), Estonian (et), Farsi (fa), Finnish (fi), French (fr), French Canada (fr_CA), German (de), Greek (el), Hebrew (he), Hindi (hi), Hungarian (hu), Italian (it), Japanese (ja), Korean (ko), Latvian (lv), Lithuanian (lt), Norwegian (no), Polish (pl), Portuguese (pt), Portuguese Brazil (pt_BR), Romanian (ro),Russian (ru), Serbian (sr), Slovak (sk), Slovenian (sl), Spanish (es),Spanish Latin America (es_MX), Swedish (sv), Thai (th), Turkish (tr), Ukrainian (uk), and Vietnamese (vi). /// </summary> /// <value>A simple type enumeration of the language used. The supported languages, with the language value shown in parenthesis, are: Arabic (ar), Armenian (hy), Bahasa Indonesia (id), Bahasa Melayu (ms) Bulgarian (bg), Czech (cs), Chinese Simplified (zh_CN), Chinese Traditional (zh_TW), Croatian (hr), Danish (da), Dutch (nl), English US (en), English UK (en_GB), Estonian (et), Farsi (fa), Finnish (fi), French (fr), French Canada (fr_CA), German (de), Greek (el), Hebrew (he), Hindi (hi), Hungarian (hu), Italian (it), Japanese (ja), Korean (ko), Latvian (lv), Lithuanian (lt), Norwegian (no), Polish (pl), Portuguese (pt), Portuguese Brazil (pt_BR), Romanian (ro),Russian (ru), Serbian (sr), Slovak (sk), Slovenian (sl), Spanish (es),Spanish Latin America (es_MX), Swedish (sv), Thai (th), Turkish (tr), Ukrainian (uk), and Vietnamese (vi).</value> [DataMember(Name="supportedLanguage", EmitDefaultValue=false)] public string SupportedLanguage { get; set; } /// <summary> /// Gets or Sets SupportedLanguageMetadata /// </summary> [DataMember(Name="supportedLanguageMetadata", EmitDefaultValue=false)] public PropertyMetadata SupportedLanguageMetadata { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class RecipientEmailNotification {\n"); sb.Append(" EmailBody: ").Append(EmailBody).Append("\n"); sb.Append(" EmailBodyMetadata: ").Append(EmailBodyMetadata).Append("\n"); sb.Append(" EmailSubject: ").Append(EmailSubject).Append("\n"); sb.Append(" EmailSubjectMetadata: ").Append(EmailSubjectMetadata).Append("\n"); sb.Append(" SupportedLanguage: ").Append(SupportedLanguage).Append("\n"); sb.Append(" SupportedLanguageMetadata: ").Append(SupportedLanguageMetadata).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as RecipientEmailNotification); } /// <summary> /// Returns true if RecipientEmailNotification instances are equal /// </summary> /// <param name="other">Instance of RecipientEmailNotification to be compared</param> /// <returns>Boolean</returns> public bool Equals(RecipientEmailNotification other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.EmailBody == other.EmailBody || this.EmailBody != null && this.EmailBody.Equals(other.EmailBody) ) && ( this.EmailBodyMetadata == other.EmailBodyMetadata || this.EmailBodyMetadata != null && this.EmailBodyMetadata.Equals(other.EmailBodyMetadata) ) && ( this.EmailSubject == other.EmailSubject || this.EmailSubject != null && this.EmailSubject.Equals(other.EmailSubject) ) && ( this.EmailSubjectMetadata == other.EmailSubjectMetadata || this.EmailSubjectMetadata != null && this.EmailSubjectMetadata.Equals(other.EmailSubjectMetadata) ) && ( this.SupportedLanguage == other.SupportedLanguage || this.SupportedLanguage != null && this.SupportedLanguage.Equals(other.SupportedLanguage) ) && ( this.SupportedLanguageMetadata == other.SupportedLanguageMetadata || this.SupportedLanguageMetadata != null && this.SupportedLanguageMetadata.Equals(other.SupportedLanguageMetadata) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.EmailBody != null) hash = hash * 59 + this.EmailBody.GetHashCode(); if (this.EmailBodyMetadata != null) hash = hash * 59 + this.EmailBodyMetadata.GetHashCode(); if (this.EmailSubject != null) hash = hash * 59 + this.EmailSubject.GetHashCode(); if (this.EmailSubjectMetadata != null) hash = hash * 59 + this.EmailSubjectMetadata.GetHashCode(); if (this.SupportedLanguage != null) hash = hash * 59 + this.SupportedLanguage.GetHashCode(); if (this.SupportedLanguageMetadata != null) hash = hash * 59 + this.SupportedLanguageMetadata.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
#region MigraDoc - Creating Documents on the Fly // // Authors: // Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com) // // Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://www.migradoc.com // http://sourceforge.net/projects/pdfsharp // // 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.IO; using System.Diagnostics; using MigraDoc.DocumentObjectModel; using PdfSharp.Drawing; using MigraDoc.DocumentObjectModel.Shapes; using MigraDoc.Rendering.Resources; namespace MigraDoc.Rendering { /// <summary> /// Renders images. /// </summary> internal class ImageRenderer : ShapeRenderer { internal ImageRenderer(XGraphics gfx, Image image, FieldInfos fieldInfos) : base(gfx, image, fieldInfos) { this.image = image; ImageRenderInfo renderInfo = new ImageRenderInfo(); renderInfo.shape = this.shape; this.renderInfo = renderInfo; } internal ImageRenderer(XGraphics gfx, RenderInfo renderInfo, FieldInfos fieldInfos) : base(gfx, renderInfo, fieldInfos) { this.image = (Image)renderInfo.DocumentObject; } internal override void Format(Area area, FormatInfo previousFormatInfo) { if (!image.StreamBased) { this.imageFilePath = image.GetFilePath(this.documentRenderer.WorkingDirectory); //if (!File.Exists(this.imageFilePath)) if (!XImage.ExistsFile(this.imageFilePath)) { this.failure = ImageFailure.FileNotFound; Trace.WriteLine(Messages.ImageNotFound(this.image.Name), "warning"); } } ImageFormatInfo formatInfo = (ImageFormatInfo)this.renderInfo.FormatInfo; formatInfo.failure = this.failure; formatInfo.ImagePath = this.imageFilePath; CalculateImageDimensions(); base.Format(area, previousFormatInfo); } protected override XUnit ShapeHeight { get { ImageFormatInfo formatInfo = (ImageFormatInfo)this.renderInfo.FormatInfo; return formatInfo.Height + this.lineFormatRenderer.GetWidth(); } } protected override XUnit ShapeWidth { get { ImageFormatInfo formatInfo = (ImageFormatInfo)this.renderInfo.FormatInfo; return formatInfo.Width + this.lineFormatRenderer.GetWidth(); } } internal override void Render() { RenderFilling(); ImageFormatInfo formatInfo = (ImageFormatInfo)this.renderInfo.FormatInfo; Area contentArea = this.renderInfo.LayoutInfo.ContentArea; XRect destRect = new XRect(contentArea.X, contentArea.Y, formatInfo.Width, formatInfo.Height); if (formatInfo.failure == ImageFailure.None) { XImage xImage = null; try { XRect srcRect = new XRect(formatInfo.CropX, formatInfo.CropY, formatInfo.CropWidth, formatInfo.CropHeight); if (image.StreamBased) { xImage = new XImage(image.ImageStream); } else { xImage = XImage.FromFile(formatInfo.ImagePath); } this.gfx.DrawImage(xImage, destRect, srcRect, XGraphicsUnit.Point); //Pixel. } catch (Exception) { RenderFailureImage(destRect); } finally { if (xImage != null) xImage.Dispose(); } } else RenderFailureImage(destRect); RenderLine(); } void RenderFailureImage(XRect destRect) { this.gfx.DrawRectangle(XBrushes.LightGray, destRect); string failureString; ImageFormatInfo formatInfo = (ImageFormatInfo)this.RenderInfo.FormatInfo; switch (formatInfo.failure) { case ImageFailure.EmptySize: failureString = Messages.DisplayEmptyImageSize; break; case ImageFailure.FileNotFound: failureString = Messages.DisplayImageFileNotFound; break; case ImageFailure.InvalidType: failureString = Messages.DisplayInvalidImageType; break; case ImageFailure.NotRead: default: failureString = Messages.DisplayImageNotRead; break; } // Create stub font XFont font = new XFont("Courier New", 8); this.gfx.DrawString(failureString, font, XBrushes.Red, destRect, XStringFormats.Center); } private void CalculateImageDimensions() { ImageFormatInfo formatInfo = (ImageFormatInfo)this.renderInfo.FormatInfo; if (formatInfo.failure == ImageFailure.None) { XImage xImage = null; try { if (image.StreamBased) { xImage = new XImage(image.ImageStream); } else { xImage = XImage.FromFile(formatInfo.ImagePath); } } catch (InvalidOperationException ex) { Trace.WriteLine(Messages.InvalidImageType(ex.Message)); formatInfo.failure = ImageFailure.InvalidType; } try { XUnit usrWidth = image.Width.Point; XUnit usrHeight = image.Height.Point; bool usrWidthSet = !this.image.IsNull("Width"); bool usrHeightSet = !this.image.IsNull("Height"); XUnit resultWidth = usrWidth; XUnit resultHeight = usrHeight; double xPixels = xImage.PixelWidth; bool usrResolutionSet = !image.IsNull("Resolution"); double horzRes = usrResolutionSet ? (double)image.Resolution : xImage.HorizontalResolution; XUnit inherentWidth = XUnit.FromInch(xPixels / horzRes); double yPixels = xImage.PixelHeight; double vertRes = usrResolutionSet ? (double)image.Resolution : xImage.VerticalResolution; XUnit inherentHeight = XUnit.FromInch(yPixels / vertRes); bool lockRatio = this.image.IsNull("LockAspectRatio") ? true : image.LockAspectRatio; double scaleHeight = this.image.ScaleHeight; double scaleWidth = this.image.ScaleWidth; bool scaleHeightSet = !this.image.IsNull("ScaleHeight"); bool scaleWidthSet = !this.image.IsNull("ScaleWidth"); if (lockRatio && !(scaleHeightSet && scaleWidthSet)) { if (usrWidthSet && !usrHeightSet) { resultHeight = inherentHeight / inherentWidth * usrWidth; } else if (usrHeightSet && !usrWidthSet) { resultWidth = inherentWidth / inherentHeight * usrHeight; } else if (!usrHeightSet && !usrWidthSet) { resultHeight = inherentHeight; resultWidth = inherentWidth; } if (scaleHeightSet) { resultHeight = resultHeight * scaleHeight; resultWidth = resultWidth * scaleHeight; } if (scaleWidthSet) { resultHeight = resultHeight * scaleWidth; resultWidth = resultWidth * scaleWidth; } } else { if (!usrHeightSet) resultHeight = inherentHeight; if (!usrWidthSet) resultWidth = inherentWidth; if (scaleHeightSet) resultHeight = resultHeight * scaleHeight; if (scaleWidthSet) resultWidth = resultWidth * scaleWidth; } formatInfo.CropWidth = (int)xPixels; formatInfo.CropHeight = (int)yPixels; if (!this.image.IsNull("PictureFormat")) { PictureFormat picFormat = this.image.PictureFormat; //Cropping in pixels. XUnit cropLeft = picFormat.CropLeft.Point; XUnit cropRight = picFormat.CropRight.Point; XUnit cropTop = picFormat.CropTop.Point; XUnit cropBottom = picFormat.CropBottom.Point; formatInfo.CropX = (int)(horzRes * cropLeft.Inch); formatInfo.CropY = (int)(vertRes * cropTop.Inch); formatInfo.CropWidth -= (int)(horzRes * ((XUnit)(cropLeft + cropRight)).Inch); formatInfo.CropHeight -= (int)(vertRes * ((XUnit)(cropTop + cropBottom)).Inch); //Scaled cropping of the height and width. double xScale = resultWidth / inherentWidth; double yScale = resultHeight / inherentHeight; cropLeft = xScale * cropLeft; cropRight = xScale * cropRight; cropTop = yScale * cropTop; cropBottom = yScale * cropBottom; resultHeight = resultHeight - cropTop - cropBottom; resultWidth = resultWidth - cropLeft - cropRight; } if (resultHeight <= 0 || resultWidth <= 0) { formatInfo.Width = XUnit.FromCentimeter(2.5); formatInfo.Height = XUnit.FromCentimeter(2.5); Trace.WriteLine(Messages.EmptyImageSize); this.failure = ImageFailure.EmptySize; } else { formatInfo.Width = resultWidth; formatInfo.Height = resultHeight; } } catch (Exception ex) { Trace.WriteLine(Messages.ImageNotReadable(this.image.Name, ex.Message)); formatInfo.failure = ImageFailure.NotRead; } finally { if (xImage != null) xImage.Dispose(); } } if (formatInfo.failure != ImageFailure.None) { if (!this.image.IsNull("Width")) formatInfo.Width = this.image.Width.Point; else formatInfo.Width = XUnit.FromCentimeter(2.5); if (!this.image.IsNull("Height")) formatInfo.Height = this.image.Height.Point; else formatInfo.Height = XUnit.FromCentimeter(2.5); return; } } Image image; string imageFilePath; ImageFailure failure; } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { static class CSharpCompilationOptionsExtensions { [Fact] public void WithModuleName() { // ModuleName Assert.Equal(null, TestOptions.ReleaseDll.WithModuleName(null).ModuleName); TestOptions.ReleaseDll.WithModuleName("").VerifyErrors( // error CS7087: Name cannot be empty. // Parameter name: ModuleName Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments( @"Name cannot be empty. Parameter name: ModuleName" )); TestOptions.ReleaseDll.WithModuleName("a\0a").VerifyErrors( // error CS7087: Name contains invalid characters. // Parameter name: ModuleName Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(@"Name contains invalid characters. Parameter name: ModuleName") ); TestOptions.ReleaseDll.WithModuleName("a\uD800b").VerifyErrors( // error CS7087: Name contains invalid characters. // Parameter name: ModuleName Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(@"Name contains invalid characters. Parameter name: ModuleName") ); TestOptions.ReleaseDll.WithModuleName("a\\b").VerifyErrors( // error CS7087: Name contains invalid characters. // Parameter name: ModuleName Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(@"Name contains invalid characters. Parameter name: ModuleName") ); TestOptions.ReleaseDll.WithModuleName("a/b").VerifyErrors( // error CS7087: Name contains invalid characters. // Parameter name: ModuleName Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(@"Name contains invalid characters. Parameter name: ModuleName") ); TestOptions.ReleaseDll.WithModuleName("a:b").VerifyErrors( // error CS7087: Name contains invalid characters. // Parameter name: ModuleName Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(@"Name contains invalid characters. Parameter name: ModuleName") ); } public static void VerifyErrors(this CSharpCompilationOptions options, params DiagnosticDescription[] expected) { options.Errors.Verify(expected); } } public class CSharpCompilationOptionsTests : CSharpTestBase { private void TestProperty<T>( Func<CSharpCompilationOptions, T, CSharpCompilationOptions> factory, Func<CSharpCompilationOptions, T> getter, T validNonDefaultValue) { var oldOpt1 = new CSharpCompilationOptions(OutputKind.ConsoleApplication); var validDefaultValue = getter(oldOpt1); // we need non-default value to test Equals and GetHashCode Assert.NotEqual(validNonDefaultValue, validDefaultValue); // check that the assigned value can be read: var newOpt1 = factory(oldOpt1, validNonDefaultValue); Assert.Equal(validNonDefaultValue, getter(newOpt1)); Assert.Equal(0, newOpt1.Errors.Length); // check that creating new options with the same value yields the same options instance: var newOpt1_alias = factory(newOpt1, validNonDefaultValue); Assert.Same(newOpt1_alias, newOpt1); // check that Equals and GetHashCode work var newOpt2 = factory(oldOpt1, validNonDefaultValue); Assert.False(newOpt1.Equals(oldOpt1)); Assert.True(newOpt1.Equals(newOpt2)); Assert.Equal(newOpt1.GetHashCode(), newOpt2.GetHashCode()); // test default(T): Assert.NotNull(factory(oldOpt1, default(T))); } [Fact] public void Invariants() { TestProperty((old, value) => old.WithOutputKind(value), opt => opt.OutputKind, OutputKind.DynamicallyLinkedLibrary); TestProperty((old, value) => old.WithModuleName(value), opt => opt.ModuleName, "foo.dll"); TestProperty((old, value) => old.WithMainTypeName(value), opt => opt.MainTypeName, "Foo.Bar"); TestProperty((old, value) => old.WithScriptClassName(value), opt => opt.ScriptClassName, "<Script>"); TestProperty((old, value) => old.WithUsings(value), opt => opt.Usings, ImmutableArray.Create("A", "B")); TestProperty((old, value) => old.WithOptimizationLevel(value), opt => opt.OptimizationLevel, OptimizationLevel.Release); TestProperty((old, value) => old.WithOverflowChecks(value), opt => opt.CheckOverflow, true); TestProperty((old, value) => old.WithAllowUnsafe(value), opt => opt.AllowUnsafe, true); TestProperty((old, value) => old.WithCryptoKeyContainer(value), opt => opt.CryptoKeyContainer, "foo"); TestProperty((old, value) => old.WithCryptoKeyFile(value), opt => opt.CryptoKeyFile, "foo"); TestProperty((old, value) => old.WithDelaySign(value), opt => opt.DelaySign, true); TestProperty((old, value) => old.WithPlatform(value), opt => opt.Platform, Platform.Itanium); TestProperty((old, value) => old.WithGeneralDiagnosticOption(value), opt => opt.GeneralDiagnosticOption, ReportDiagnostic.Suppress); TestProperty((old, value) => old.WithWarningLevel(value), opt => opt.WarningLevel, 3); TestProperty((old, value) => old.WithSpecificDiagnosticOptions(value), opt => opt.SpecificDiagnosticOptions, new Dictionary<string, ReportDiagnostic> { { "CS0001", ReportDiagnostic.Error } }.ToImmutableDictionary()); TestProperty((old, value) => old.WithConcurrentBuild(value), opt => opt.ConcurrentBuild, false); TestProperty((old, value) => old.WithExtendedCustomDebugInformation(value), opt => opt.ExtendedCustomDebugInformation, false); TestProperty((old, value) => old.WithXmlReferenceResolver(value), opt => opt.XmlReferenceResolver, new XmlFileResolver(null)); TestProperty((old, value) => old.WithMetadataReferenceResolver(value), opt => opt.MetadataReferenceResolver, new AssemblyReferenceResolver(new MetadataFileReferenceResolver(new string[0], null), new MetadataFileReferenceProvider())); TestProperty((old, value) => old.WithAssemblyIdentityComparer(value), opt => opt.AssemblyIdentityComparer, new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy())); TestProperty((old, value) => old.WithStrongNameProvider(value), opt => opt.StrongNameProvider, new DesktopStrongNameProvider()); } [Fact] public void WithXxx() { new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName(null).VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: 'null'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "null")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName("blah\0foo").VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: 'blah\0foo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "blah\0foo")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName("").VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "")); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName(null).Errors.Length); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName("blah\0foo").VerifyErrors( // error CS7088: Invalid 'MainTypeName' value: 'blah\0foo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "blah\0foo")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName("").VerifyErrors( // error CS7088: Invalid 'MainTypeName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOutputKind((OutputKind)Int32.MaxValue).VerifyErrors( // error CS7088: Invalid 'OutputKind' value: 'Int32.MaxValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MaxValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOutputKind((OutputKind)Int32.MinValue).VerifyErrors( // error CS7088: Invalid 'OutputKind' value: 'Int32.MinValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel((OptimizationLevel)Int32.MaxValue).VerifyErrors( // error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MaxValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MaxValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel((OptimizationLevel)Int32.MinValue).VerifyErrors( // error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MinValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithPlatform((Platform)Int32.MaxValue).VerifyErrors( // error CS1672: Invalid option 'Int32.MaxValue' for /platform; must be anycpu, x86, Itanium or x64 Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MaxValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithPlatform((Platform)Int32.MinValue).VerifyErrors( // error CS1672: Invalid option 'Int32.MinValue' for /platform; must be anycpu, x86, Itanium or x64 Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MinValue.ToString())); var defaultWarnings = new CSharpCompilationOptions(OutputKind.ConsoleApplication); Assert.Equal(ReportDiagnostic.Default, defaultWarnings.GeneralDiagnosticOption); Assert.Equal(4, defaultWarnings.WarningLevel); Assert.Equal(ReportDiagnostic.Error, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithGeneralDiagnosticOption(ReportDiagnostic.Error).GeneralDiagnosticOption); Assert.Equal(ReportDiagnostic.Default, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithGeneralDiagnosticOption(ReportDiagnostic.Default).GeneralDiagnosticOption); } [Fact] public void WithUsings() { var actual1 = new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new[] { "A", "B" }).Usings; Assert.True(actual1.SequenceEqual(new[] { "A", "B" })); var actual2 = new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(Enumerable.Repeat("A", 1)).Usings; Assert.True(actual2.SequenceEqual(Enumerable.Repeat("A", 1))); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings("A", "B").WithUsings(null).Usings.Count()); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings("A", "B").WithUsings((string[])null).Usings.Count()); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { null }).VerifyErrors( // error CS7088: Invalid 'Usings' value: 'null'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "null")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { "" }).VerifyErrors( // error CS7088: Invalid 'Usings' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { "blah\0foo" }).VerifyErrors( // error CS7088: Invalid 'Usings' value: 'blah\0foo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "blah\0foo")); } [Fact] public void WithWarnings() { var warnings = new Dictionary<string, ReportDiagnostic> { { MessageProvider.Instance.GetIdForErrorCode(1), ReportDiagnostic.Error }, { MessageProvider.Instance.GetIdForErrorCode(2), ReportDiagnostic.Suppress }, { MessageProvider.Instance.GetIdForErrorCode(3), ReportDiagnostic.Warn } }; Assert.Equal(3, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithSpecificDiagnosticOptions(warnings).SpecificDiagnosticOptions.Count); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithSpecificDiagnosticOptions(null).SpecificDiagnosticOptions.Count); Assert.Equal(1, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(1).WarningLevel); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(-1).VerifyErrors( // error CS7088: Invalid 'WarningLevel' value: '-1'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "-1")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(5).VerifyErrors( // error CS7088: Invalid 'WarningLevel' value: '5'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "5")); } [Fact] public void ConstructorValidation() { new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { null }).VerifyErrors( // error CS7088: Invalid 'Usings' value: 'null'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "null")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { "" }).VerifyErrors( // error CS7088: Invalid 'Usings' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { "blah\0foo" }).VerifyErrors( // error CS7088: Invalid 'Usings' value: 'blah\0foo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "blah\0foo")); Assert.Equal("Script", new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: null).ScriptClassName); new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: "blah\0foo").VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: 'blah\0foo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "blah\0foo")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: "").VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "")); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: null).Errors.Length); new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: "blah\0foo").VerifyErrors( // error CS7088: Invalid 'MainTypeName' value: 'blah\0foo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "blah\0foo")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: "").VerifyErrors( // error CS7088: Invalid 'MainTypeName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "")); new CSharpCompilationOptions(outputKind: (OutputKind)Int32.MaxValue).VerifyErrors( // error CS7088: Invalid 'OutputKind' value: 'Int32.MaxValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MaxValue.ToString())); new CSharpCompilationOptions(outputKind: (OutputKind)Int32.MinValue).VerifyErrors( // error CS7088: Invalid 'OutputKind' value: 'Int32.MinValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel: (OptimizationLevel)Int32.MaxValue).VerifyErrors( // error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MaxValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MaxValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel: (OptimizationLevel)Int32.MinValue).VerifyErrors( // error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MinValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication, platform: (Platform)Int32.MinValue).VerifyErrors( // error CS1672: Invalid option 'Int32.MinValue' for /platform; must be anycpu, x86, Itanium or x64 Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication, warningLevel: -1).VerifyErrors( // error CS7088: Invalid 'WarningLevel' value: '-1'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "-1")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, warningLevel: 5).VerifyErrors( // error CS7088: Invalid 'WarningLevel' value: '5'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "5")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, platform: Platform.AnyCpu32BitPreferred).VerifyErrors(); new CSharpCompilationOptions(OutputKind.WindowsRuntimeApplication, platform: Platform.AnyCpu32BitPreferred).VerifyErrors(); new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata, platform: Platform.AnyCpu32BitPreferred).VerifyErrors( Diagnostic(ErrorCode.ERR_BadPrefer32OnLib)); new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, platform: Platform.AnyCpu32BitPreferred).VerifyErrors( Diagnostic(ErrorCode.ERR_BadPrefer32OnLib)); } /// <summary> /// If this test fails, please update the <see cref="CSharpCompilationOptions.GetHashCode"/> /// and <see cref="CSharpCompilationOptions.Equals(CSharpCompilationOptions)"/> methods to /// make sure they are doing the right thing with your new field and then update the baseline /// here. /// </summary> [Fact] public void TestFieldsForEqualsAndGetHashCode() { ReflectionAssert.AssertPublicAndInternalFieldsAndProperties( typeof(CSharpCompilationOptions), "AllowUnsafe", "Usings"); } [Fact] public void TestEqualitySemantics() { Assert.Equal(CreateCSharpCompilationOptions(), CreateCSharpCompilationOptions()); } private static CSharpCompilationOptions CreateCSharpCompilationOptions() { string moduleName = null; string mainTypeName = null; string scriptClassName = null; IEnumerable<string> usings = null; OptimizationLevel optimizationLevel = OptimizationLevel.Debug; bool checkOverflow = false; bool allowUnsafe = false; string cryptoKeyContainer = null; string cryptoKeyFile = null; bool? delaySign = null; Platform platform = 0; ReportDiagnostic generalDiagnosticOption = 0; int warningLevel = 0; IEnumerable<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptions = null; bool concurrentBuild = false; bool extendedCustomDebugInformation = true; XmlReferenceResolver xmlReferenceResolver = new XmlFileResolver(null); SourceReferenceResolver sourceReferenceResolver = new SourceFileResolver(ImmutableArray<string>.Empty, null); MetadataReferenceResolver metadataReferenceResolver = new AssemblyReferenceResolver(new MetadataFileReferenceResolver(ImmutableArray<string>.Empty, null), MetadataFileReferenceProvider.Default); AssemblyIdentityComparer assemblyIdentityComparer = AssemblyIdentityComparer.Default; // Currently uses reference equality StrongNameProvider strongNameProvider = new DesktopStrongNameProvider(); MetadataImportOptions metadataImportOptions = 0; ImmutableArray<string> features = ImmutableArray<string>.Empty; return new CSharpCompilationOptions(OutputKind.ConsoleApplication, moduleName, mainTypeName, scriptClassName, usings, optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, delaySign, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, concurrentBuild, extendedCustomDebugInformation, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver, assemblyIdentityComparer, strongNameProvider, metadataImportOptions, features); } [Fact] public void Serializability1() { VerifySerializability(new CSharpSerializableCompilationOptions(new CSharpCompilationOptions( outputKind: OutputKind.WindowsApplication, usings: new[] { "F", "G" }, generalDiagnosticOption: ReportDiagnostic.Hidden, specificDiagnosticOptions: new[] { KeyValuePair.Create("CS0001", ReportDiagnostic.Suppress) }))); } [Fact] public void Serializability2() { var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp3, DocumentationMode.Diagnose, SourceCodeKind.Interactive); var compilationOptions = new CSharpCompilationOptions( OutputKind.DynamicallyLinkedLibrary, moduleName: "M", optimizationLevel: OptimizationLevel.Release); compilationOptions = compilationOptions. WithConcurrentBuild(!compilationOptions.ConcurrentBuild). WithExtendedCustomDebugInformation(!compilationOptions.ExtendedCustomDebugInformation); var deserializedCompilationOptions = VerifySerializability(new CSharpSerializableCompilationOptions(compilationOptions)).Options; Assert.Equal(compilationOptions.OutputKind, deserializedCompilationOptions.OutputKind); Assert.Equal(compilationOptions.ModuleName, deserializedCompilationOptions.ModuleName); Assert.Equal(compilationOptions.OptimizationLevel, deserializedCompilationOptions.OptimizationLevel); Assert.Equal(compilationOptions.ConcurrentBuild, deserializedCompilationOptions.ConcurrentBuild); Assert.Equal(compilationOptions.ExtendedCustomDebugInformation, deserializedCompilationOptions.ExtendedCustomDebugInformation); } } }
/* * MethodCall.cs - Implementation of the * "System.Runtime.Remoting.Messaging.MethodCall" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Runtime.Remoting.Messaging { #if CONFIG_REMOTING using System.Collections; using System.Reflection; using System.Runtime.Serialization; [Serializable] [CLSCompliant(false)] public class MethodCall : IMethodCallMessage, ISerializable, IMethodMessage, IMessage, ISerializationRootObject, IMessageDictionary { // Internal state. protected IDictionary ExternalProperties; protected IDictionary InternalProperties; private Object[] args; private String methodName; private String typeName; private String uri; private bool hasVarArgs; private bool isSoap; private LogicalCallContext context; private MethodBase method; private ParameterInfo[] parameters; private Object srvID; private Type[] signature; // Constructors. public MethodCall(Header[] h1) { isSoap = true; // This form is used for SOAP requests. Init(); if(h1 != null) { foreach(Header h in h1) { ProcessHeader(h.Name, h.Value); } } ResolveMethod(); AccessCheck(); } public MethodCall(IMessage msg) { if(msg == null) { throw new ArgumentNullException("msg"); } Init(); IDictionaryEnumerator e = msg.Properties.GetEnumerator(); while(e.MoveNext()) { ProcessHeader(e.Key.ToString(), e.Value); } ResolveMethod(); AccessCheck(); } internal MethodCall(SerializationInfo info, StreamingContext context) { if(info == null) { throw new ArgumentNullException("info"); } Init(); RootSetObjectData(info, context); } // Implement the IMethodCallMessage interface. public virtual IDictionary Properties { get { if(InternalProperties == null) { InternalProperties = new Hashtable(); } if(ExternalProperties == null) { ExternalProperties = new MessageProperties (this, InternalProperties); } return ExternalProperties; } } public int ArgCount { get { if(args != null) { return args.Length; } else { return 0; } } } public Object[] Args { get { return args; } } public bool HasVarArgs { get { return hasVarArgs; } } public LogicalCallContext LogicalCallContext { get { if(context == null) { context = new LogicalCallContext(); } return context; } } public MethodBase MethodBase { get { return method; } } public String MethodName { get { return methodName; } } public Object MethodSignature { get { if(signature == null) { FetchParameters(); if(parameters != null) { signature = new Type [parameters.Length]; int posn; for(posn = 0; posn < signature.Length; ++posn) { signature[posn] = parameters[posn].ParameterType; } } } return signature; } } public String TypeName { get { return typeName; } } public String Uri { get { return uri; } set { uri = value; } } public int InArgCount { get { FetchParameters(); int count = 0; if(parameters != null) { foreach(ParameterInfo p in parameters) { if(!(p.ParameterType.IsByRef)) { ++count; } } } return count; } } public Object[] InArgs { get { int count = InArgCount; Object[] inArgs = new Object [count]; if(parameters != null && args != null) { int posn; count = 0; for(posn = 0; posn < args.Length; ++posn) { if(!(parameters[posn].ParameterType.IsByRef)) { inArgs[count++] = args[posn]; } } } return inArgs; } } public Object GetArg(int argNum) { return args[argNum]; } public String GetArgName(int index) { FetchParameters(); return parameters[index].Name; } public Object GetInArg(int argNum) { FetchParameters(); if(parameters != null && args != null) { int posn; for(posn = 0; posn < args.Length; ++posn) { if(!(parameters[posn].ParameterType.IsByRef)) { if(argNum == 0) { return args[posn]; } --argNum; } } } throw new IndexOutOfRangeException(_("Arg_InvalidArrayIndex")); } public String GetInArgName(int index) { FetchParameters(); if(parameters != null) { int posn; for(posn = 0; posn < args.Length; ++posn) { if(!(parameters[posn].ParameterType.IsByRef)) { if(index == 0) { return parameters[posn].Name; } --index; } } } throw new IndexOutOfRangeException(_("Arg_InvalidArrayIndex")); } // Implement the ISerializable interface. public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(); } // Handle incoming headers. public virtual Object HeaderHandler(Header[] h) { // Extract the method name from the headers, if present. if(h != null && h.Length != 0 && h[0].Name == "__methodName") { methodName = (String)(h[0].Value); if(h.Length != 1) { Header[] nh = new Header [h.Length - 1]; Array.Copy(h, 1, nh, 0, h.Length - 1); nh = h; } else { h = null; } } // Process the headers to set the message properties. if(h != null) { foreach(Header header in h) { ProcessHeader(header.Name, header.Value); } } // Resolve the method. ResolveMethod(false); return null; } // Initialization helper. public virtual void Init() { // Nothing to do here. } // Resolve the method. public void ResolveMethod() { ResolveMethod(true); } [TODO] private void ResolveMethod(bool throwOnError) { // TODO } // Set the root object data for a SOAP method call. [TODO] private void RootSetSoapObjectData(SerializationInfo info) { // TODO } // Set the root object data for this method call. public void RootSetObjectData(SerializationInfo info, StreamingContext context) { if(info == null) { throw new ArgumentNullException("info"); } // Use a different algorithm for SOAP messages. if(isSoap) { RootSetSoapObjectData(info); return; } // De-serialize the main values. SerializationInfoEnumerator se = info.GetEnumerator(); while(se.MoveNext()) { ProcessHeader(se.Name, se.Value); } // Process the headers in the streaming context. if(context.State == StreamingContextStates.Remoting) { Header[] headers = (context.Context as Header[]); if(headers != null) { foreach(Header header in headers) { ProcessHeader(header.Name, header.Value); } } } } // Set the server identity within this object. internal void SetServerIdentity(Object srvID) { this.srvID = srvID; } // Process a header. private void ProcessHeader(String name, Object value) { Properties[name] = value; } // Perform an access check on the resolved method. [TODO] private void AccessCheck() { // TODO } // Fetch the parameter information from the method block. private void FetchParameters() { if(parameters == null && method != null) { parameters = method.GetParameters(); } } // Implement the IMessageDictionary interface. String[] IMessageDictionary.SpecialProperties { get { return SpecialProperties; } } Object IMessageDictionary.GetSpecialProperty(String name) { return GetSpecialProperty(name); } void IMessageDictionary.SetSpecialProperty(String name, Object value) { SetSpecialProperty(name, value); } internal virtual String[] SpecialProperties { get { return new String[] { "__Uri", "__MethodName", "__MethodSignature", "__TypeName", "__Args", "__CallContext" }; } } internal virtual Object GetSpecialProperty(String name) { switch(name) { case "__Uri": return Uri; case "__MethodName": return MethodName; case "__MethodSignature": return MethodSignature; case "__TypeName": return TypeName; case "__Args": return Args; case "__CallContext": return LogicalCallContext; } return null; } internal virtual void SetSpecialProperty(String name, Object value) { switch(name) { case "__Uri": Uri = (String)value; break; case "__CallContext": context = (LogicalCallContext)value; break; } } }; // class MethodCall #endif // CONFIG_REMOTING }; // namespace System.Runtime.Remoting.Messaging
/* ==================================================================== 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.XSSF.Model; using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.XSSF.UserModel.Extensions; using NUnit.Framework; using NPOI.SS.UserModel; using NPOI.HSSF.UserModel; using System.Drawing; using NPOI.HSSF.Util; namespace NPOI.XSSF.UserModel { [TestFixture] public class TestXSSFCellStyle { private StylesTable stylesTable; private CT_Border ctBorderA; private CT_Fill ctFill; private CT_Font ctFont; private CT_Xf cellStyleXf; private CT_Xf cellXf; private CT_CellXfs cellXfs; private XSSFCellStyle cellStyle; private CT_Stylesheet ctStylesheet; [SetUp] public void SetUp() { stylesTable = new StylesTable(); ctStylesheet = stylesTable.GetCTStylesheet(); ctBorderA = new CT_Border(); XSSFCellBorder borderA = new XSSFCellBorder(ctBorderA); long borderId = stylesTable.PutBorder(borderA); Assert.AreEqual(1, borderId); XSSFCellBorder borderB = new XSSFCellBorder(); Assert.AreEqual(1, stylesTable.PutBorder(borderB)); ctFill = new CT_Fill(); XSSFCellFill fill = new XSSFCellFill(ctFill); long fillId = stylesTable.PutFill(fill); Assert.AreEqual(2, fillId); ctFont = new CT_Font(); XSSFFont font = new XSSFFont(ctFont); long fontId = stylesTable.PutFont(font); Assert.AreEqual(1, fontId); cellStyleXf = ctStylesheet.AddNewCellStyleXfs().AddNewXf(); cellStyleXf.borderId = 1; cellStyleXf.fillId = 1; cellStyleXf.fontId = 1; cellXfs = ctStylesheet.AddNewCellXfs(); cellXf = cellXfs.AddNewXf(); cellXf.xfId = (1); cellXf.borderId = (1); cellXf.fillId = (1); cellXf.fontId = (1); stylesTable.PutCellStyleXf(cellStyleXf); stylesTable.PutCellXf(cellXf); cellStyle = new XSSFCellStyle(1, 1, stylesTable, null); } [Test] public void TestGetSetBorderBottom() { //default values Assert.AreEqual(BorderStyle.None, cellStyle.BorderBottom); int num = stylesTable.GetBorders().Count; cellStyle.BorderBottom = (BorderStyle.Medium); Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderBottom); //a new border has been Added Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.medium, ctBorder.bottom.style); num = stylesTable.GetBorders().Count; //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.BorderBottom = (BorderStyle.Medium); Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderBottom); } Assert.AreEqual((uint)borderId, cellStyle.GetCoreXf().borderId); Assert.AreEqual(num, stylesTable.GetBorders().Count); Assert.AreSame(ctBorder, stylesTable.GetBorderAt(borderId).GetCTBorder()); //setting border to none Removes the <bottom> element cellStyle.BorderBottom = (BorderStyle.None); Assert.AreEqual(num, stylesTable.GetBorders().Count); borderId = (int)cellStyle.GetCoreXf().borderId; ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.IsFalse(ctBorder.IsSetBottom()); } [Test] public void TestSetServeralBordersOnSameCell() { Assert.AreEqual(BorderStyle.None, cellStyle.BorderRight); Assert.AreEqual(BorderStyle.None, cellStyle.BorderLeft); Assert.AreEqual(BorderStyle.None, cellStyle.BorderTop); Assert.AreEqual(BorderStyle.None, cellStyle.BorderBottom); Assert.AreEqual(2, stylesTable.GetBorders().Count); cellStyle.BorderBottom = BorderStyle.Thin; cellStyle.BottomBorderColor = HSSFColor.Black.Index; cellStyle.BorderLeft = BorderStyle.DashDotDot; cellStyle.LeftBorderColor = HSSFColor.Green.Index; cellStyle.BorderRight = BorderStyle.Hair; cellStyle.RightBorderColor = HSSFColor.Blue.Index; cellStyle.BorderTop = BorderStyle.MediumDashed; cellStyle.TopBorderColor = HSSFColor.Orange.Index; //only one border style should be generated Assert.AreEqual(3, stylesTable.GetBorders().Count); } [Test] public void TestGetSetBorderDiagonal() { Assert.AreEqual(BorderDiagonal.None, cellStyle.BorderDiagonal); int num = stylesTable.GetBorders().Count; cellStyle.BorderDiagonalLineStyle = BorderStyle.Medium; cellStyle.BorderDiagonalColor = HSSFColor.Red.Index; cellStyle.BorderDiagonal = BorderDiagonal.Backward; Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderDiagonalLineStyle); //a new border has been added Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the created border uint borderId = cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.medium, ctBorder.diagonal.style); num = stylesTable.GetBorders().Count; //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.BorderDiagonal = BorderDiagonal.Backward; Assert.AreEqual(BorderDiagonal.Backward, cellStyle.BorderDiagonal); } Assert.AreEqual(borderId, cellStyle.GetCoreXf().borderId); Assert.AreEqual(num, stylesTable.GetBorders().Count); Assert.AreSame(ctBorder, stylesTable.GetBorderAt((int)borderId).GetCTBorder()); cellStyle.BorderDiagonal = (BorderDiagonal.None); Assert.AreEqual(num, stylesTable.GetBorders().Count); borderId = cellStyle.GetCoreXf().borderId; ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.IsFalse(ctBorder.IsSetDiagonal()); } [Test] public void TestGetSetBorderRight() { //default values Assert.AreEqual(BorderStyle.None, cellStyle.BorderRight); int num = stylesTable.GetBorders().Count; cellStyle.BorderRight = (BorderStyle.Medium); Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderRight); //a new border has been Added Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border uint borderId = cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.medium, ctBorder.right.style); num = stylesTable.GetBorders().Count; //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.BorderRight = (BorderStyle.Medium); Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderRight); } Assert.AreEqual(borderId, cellStyle.GetCoreXf().borderId); Assert.AreEqual(num, stylesTable.GetBorders().Count); Assert.AreSame(ctBorder, stylesTable.GetBorderAt((int)borderId).GetCTBorder()); //setting border to none Removes the <right> element cellStyle.BorderRight = (BorderStyle.None); Assert.AreEqual(num, stylesTable.GetBorders().Count); borderId = cellStyle.GetCoreXf().borderId; ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.IsFalse(ctBorder.IsSetRight()); } [Test] public void TestGetSetBorderLeft() { //default values Assert.AreEqual(BorderStyle.None, cellStyle.BorderLeft); int num = stylesTable.GetBorders().Count; cellStyle.BorderLeft = (BorderStyle.Medium); Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderLeft); //a new border has been Added Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border uint borderId = cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.medium, ctBorder.left.style); num = stylesTable.GetBorders().Count; //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.BorderLeft = (BorderStyle.Medium); Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderLeft); } Assert.AreEqual(borderId, cellStyle.GetCoreXf().borderId); Assert.AreEqual(num, stylesTable.GetBorders().Count); Assert.AreSame(ctBorder, stylesTable.GetBorderAt((int)borderId).GetCTBorder()); //setting border to none Removes the <left> element cellStyle.BorderLeft = (BorderStyle.None); Assert.AreEqual(num, stylesTable.GetBorders().Count); borderId = cellStyle.GetCoreXf().borderId; ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.IsFalse(ctBorder.IsSetLeft()); } [Test] public void TestGetSetBorderTop() { //default values Assert.AreEqual(BorderStyle.None, cellStyle.BorderTop); int num = stylesTable.GetBorders().Count; cellStyle.BorderTop = BorderStyle.Medium; Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderTop); //a new border has been Added Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border uint borderId = cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.medium, ctBorder.top.style); num = stylesTable.GetBorders().Count; //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.BorderTop = BorderStyle.Medium; Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderTop); } Assert.AreEqual((uint)borderId, cellStyle.GetCoreXf().borderId); Assert.AreEqual(num, stylesTable.GetBorders().Count); Assert.AreSame(ctBorder, stylesTable.GetBorderAt((int)borderId).GetCTBorder()); //setting border to none Removes the <top> element cellStyle.BorderTop = BorderStyle.None; Assert.AreEqual(num, stylesTable.GetBorders().Count); borderId = cellStyle.GetCoreXf().borderId; ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.IsFalse(ctBorder.IsSetTop()); } [Test] public void TestGetSetBottomBorderColor() { //defaults Assert.AreEqual(IndexedColors.Black.Index, cellStyle.BottomBorderColor); Assert.IsNull(cellStyle.BottomBorderXSSFColor); int num = stylesTable.GetBorders().Count; XSSFColor clr; //setting indexed color cellStyle.BottomBorderColor = (IndexedColors.BlueGrey.Index); Assert.AreEqual(IndexedColors.BlueGrey.Index, cellStyle.BottomBorderColor); clr = cellStyle.BottomBorderXSSFColor; Assert.IsTrue(clr.GetCTColor().IsSetIndexed()); Assert.AreEqual(IndexedColors.BlueGrey.Index, clr.Indexed); //a new border was Added to the styles table Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border uint borderId = cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.AreEqual((uint)IndexedColors.BlueGrey.Index, ctBorder.bottom.color.indexed); //setting XSSFColor num = stylesTable.GetBorders().Count; clr = new XSSFColor(Color.Cyan); cellStyle.SetBottomBorderColor(clr); Assert.AreEqual(clr.GetCTColor().ToString(), cellStyle.BottomBorderXSSFColor.GetCTColor().ToString()); byte[] rgb = cellStyle.BottomBorderXSSFColor.GetRgb(); Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF).ToArgb()); //another border was Added to the styles table Assert.AreEqual(num, stylesTable.GetBorders().Count); //passing null unsets the color cellStyle.SetBottomBorderColor(null); Assert.IsNull(cellStyle.BottomBorderXSSFColor); } [Test] public void TestGetSetTopBorderColor() { //defaults Assert.AreEqual(IndexedColors.Black.Index, cellStyle.TopBorderColor); Assert.IsNull(cellStyle.TopBorderXSSFColor); int num = stylesTable.GetBorders().Count; XSSFColor clr; //setting indexed color cellStyle.TopBorderColor = (IndexedColors.BlueGrey.Index); Assert.AreEqual(IndexedColors.BlueGrey.Index, cellStyle.TopBorderColor); clr = cellStyle.TopBorderXSSFColor; Assert.IsTrue(clr.GetCTColor().IsSetIndexed()); Assert.AreEqual(IndexedColors.BlueGrey.Index, clr.Indexed); //a new border was added to the styles table Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual((uint)IndexedColors.BlueGrey.Index, ctBorder.top.color.indexed); //setting XSSFColor num = stylesTable.GetBorders().Count; clr = new XSSFColor(Color.Cyan); cellStyle.SetTopBorderColor(clr); Assert.AreEqual(clr.GetCTColor().ToString(), cellStyle.TopBorderXSSFColor.GetCTColor().ToString()); byte[] rgb = cellStyle.TopBorderXSSFColor.GetRgb(); Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0], rgb[1], rgb[2]).ToArgb()); //another border was added to the styles table Assert.AreEqual(num, stylesTable.GetBorders().Count); //passing null unsets the color cellStyle.SetTopBorderColor(null); Assert.IsNull(cellStyle.TopBorderXSSFColor); } [Test] public void TestGetSetLeftBorderColor() { //defaults Assert.AreEqual(IndexedColors.Black.Index, cellStyle.LeftBorderColor); Assert.IsNull(cellStyle.LeftBorderXSSFColor); int num = stylesTable.GetBorders().Count; XSSFColor clr; //setting indexed color cellStyle.LeftBorderColor = (IndexedColors.BlueGrey.Index); Assert.AreEqual(IndexedColors.BlueGrey.Index, cellStyle.LeftBorderColor); clr = cellStyle.LeftBorderXSSFColor; Assert.IsTrue(clr.GetCTColor().IsSetIndexed()); Assert.AreEqual(IndexedColors.BlueGrey.Index, clr.Indexed); //a new border was Added to the styles table Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual((uint)IndexedColors.BlueGrey.Index, ctBorder.left.color.indexed); //setting XSSFColor num = stylesTable.GetBorders().Count; clr = new XSSFColor(Color.Cyan); cellStyle.SetLeftBorderColor(clr); Assert.AreEqual(clr.GetCTColor().ToString(), cellStyle.LeftBorderXSSFColor.GetCTColor().ToString()); byte[] rgb = cellStyle.LeftBorderXSSFColor.GetRgb(); Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF).ToArgb()); //another border was Added to the styles table Assert.AreEqual(num, stylesTable.GetBorders().Count); //passing null unsets the color cellStyle.SetLeftBorderColor(null); Assert.IsNull(cellStyle.LeftBorderXSSFColor); } [Test] public void TestGetSetRightBorderColor() { //defaults Assert.AreEqual(IndexedColors.Black.Index, cellStyle.RightBorderColor); Assert.IsNull(cellStyle.RightBorderXSSFColor); int num = stylesTable.GetBorders().Count; XSSFColor clr; //setting indexed color cellStyle.RightBorderColor = (IndexedColors.BlueGrey.Index); Assert.AreEqual(IndexedColors.BlueGrey.Index, cellStyle.RightBorderColor); clr = cellStyle.RightBorderXSSFColor; Assert.IsTrue(clr.GetCTColor().IsSetIndexed()); Assert.AreEqual(IndexedColors.BlueGrey.Index, clr.Indexed); //a new border was Added to the styles table Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual((uint)IndexedColors.BlueGrey.Index, ctBorder.right.color.indexed); //setting XSSFColor num = stylesTable.GetBorders().Count; clr = new XSSFColor(Color.Cyan); cellStyle.SetRightBorderColor(clr); Assert.AreEqual(clr.GetCTColor().ToString(), cellStyle.RightBorderXSSFColor.GetCTColor().ToString()); byte[] rgb = cellStyle.RightBorderXSSFColor.GetRgb(); Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF).ToArgb()); //another border was Added to the styles table Assert.AreEqual(num, stylesTable.GetBorders().Count); //passing null unsets the color cellStyle.SetRightBorderColor(null); Assert.IsNull(cellStyle.RightBorderXSSFColor); } [Test] public void TestGetSetFillBackgroundColor() { Assert.AreEqual(IndexedColors.Automatic.Index, cellStyle.FillBackgroundColor); Assert.IsNull(cellStyle.FillBackgroundColorColor); XSSFColor clr; int num = stylesTable.GetFills().Count; //setting indexed color cellStyle.FillBackgroundColor = (IndexedColors.Red.Index); Assert.AreEqual(IndexedColors.Red.Index, cellStyle.FillBackgroundColor); clr = (XSSFColor)cellStyle.FillBackgroundColorColor; Assert.IsTrue(clr.GetCTColor().IsSetIndexed()); Assert.AreEqual(IndexedColors.Red.Index, clr.Indexed); //a new fill was Added to the styles table Assert.AreEqual(num + 1, stylesTable.GetFills().Count); //id of the Created border int FillId = (int)cellStyle.GetCoreXf().fillId; Assert.IsTrue(FillId > 0); //check changes in the underlying xml bean CT_Fill ctFill = stylesTable.GetFillAt(FillId).GetCTFill(); Assert.AreEqual((uint)IndexedColors.Red.Index, ctFill.GetPatternFill().bgColor.indexed); //setting XSSFColor num = stylesTable.GetFills().Count; clr = new XSSFColor(Color.Cyan); cellStyle.SetFillBackgroundColor(clr); // TODO this testcase assumes that cellStyle creates a new CT_Fill, but the implementation changes the existing style. - do not know whats right 8-( Assert.AreEqual(clr.GetCTColor().ToString(), ((XSSFColor)cellStyle.FillBackgroundColorColor).GetCTColor().ToString()); byte[] rgb = ((XSSFColor)cellStyle.FillBackgroundColorColor).GetRgb(); Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF).ToArgb()); //another border was added to the styles table Assert.AreEqual(num, stylesTable.GetFills().Count); //passing null unsets the color cellStyle.SetFillBackgroundColor(null); Assert.IsNull(cellStyle.FillBackgroundColorColor); Assert.AreEqual(IndexedColors.Automatic.Index, cellStyle.FillBackgroundColor); } [Test] public void TestDefaultStyles() { XSSFWorkbook wb1 = new XSSFWorkbook(); XSSFCellStyle style1 = (XSSFCellStyle)wb1.CreateCellStyle(); Assert.AreEqual(IndexedColors.Automatic.Index, style1.FillBackgroundColor); Assert.IsNull(style1.FillBackgroundColorColor); //compatibility with HSSF HSSFWorkbook wb2 = new HSSFWorkbook(); HSSFCellStyle style2 = (HSSFCellStyle)wb2.CreateCellStyle(); Assert.AreEqual(style2.FillBackgroundColor, style1.FillBackgroundColor); Assert.AreEqual(style2.FillForegroundColor, style1.FillForegroundColor); Assert.AreEqual(style2.FillPattern, style1.FillPattern); Assert.AreEqual(style2.LeftBorderColor, style1.LeftBorderColor); Assert.AreEqual(style2.TopBorderColor, style1.TopBorderColor); Assert.AreEqual(style2.RightBorderColor, style1.RightBorderColor); Assert.AreEqual(style2.BottomBorderColor, style1.BottomBorderColor); Assert.AreEqual(style2.BorderBottom, style1.BorderBottom); Assert.AreEqual(style2.BorderLeft, style1.BorderLeft); Assert.AreEqual(style2.BorderRight, style1.BorderRight); Assert.AreEqual(style2.BorderTop, style1.BorderTop); } [Ignore] public void TestGetFillForegroundColor() { XSSFWorkbook wb = new XSSFWorkbook(); StylesTable styles = wb.GetStylesSource(); Assert.AreEqual(1, wb.NumCellStyles); Assert.AreEqual(2, styles.GetFills().Count); XSSFCellStyle defaultStyle = (XSSFCellStyle)wb.GetCellStyleAt((short)0); Assert.AreEqual(IndexedColors.Automatic.Index, defaultStyle.FillForegroundColor); Assert.AreEqual(null, defaultStyle.FillForegroundColorColor); Assert.AreEqual(FillPattern.NoFill, defaultStyle.FillPattern); XSSFCellStyle customStyle = (XSSFCellStyle)wb.CreateCellStyle(); customStyle.FillPattern = (FillPattern.SolidForeground); Assert.AreEqual(FillPattern.SolidForeground, customStyle.FillPattern); Assert.AreEqual(3, styles.GetFills().Count); customStyle.FillForegroundColor = (IndexedColors.BrightGreen.Index); Assert.AreEqual(IndexedColors.BrightGreen.Index, customStyle.FillForegroundColor); Assert.AreEqual(4, styles.GetFills().Count); for (int i = 0; i < 3; i++) { XSSFCellStyle style = (XSSFCellStyle)wb.CreateCellStyle(); style.FillPattern = (FillPattern.SolidForeground); Assert.AreEqual(FillPattern.SolidForeground, style.FillPattern); Assert.AreEqual(4, styles.GetFills().Count); style.FillForegroundColor = (IndexedColors.BrightGreen.Index); Assert.AreEqual(IndexedColors.BrightGreen.Index, style.FillForegroundColor); Assert.AreEqual(4, styles.GetFills().Count); } } [Test] public void TestGetFillPattern() { Assert.AreEqual(FillPattern.NoFill, cellStyle.FillPattern); int num = stylesTable.GetFills().Count; cellStyle.FillPattern = (FillPattern.SolidForeground); Assert.AreEqual(FillPattern.SolidForeground, cellStyle.FillPattern); Assert.AreEqual(num + 1, stylesTable.GetFills().Count); int FillId = (int)cellStyle.GetCoreXf().fillId; Assert.IsTrue(FillId > 0); //check Changes in the underlying xml bean CT_Fill ctFill = stylesTable.GetFillAt(FillId).GetCTFill(); Assert.AreEqual(ST_PatternType.solid, ctFill.GetPatternFill().patternType); //setting the same fill multiple time does not update the styles table for (int i = 0; i < 3; i++) { cellStyle.FillPattern = (FillPattern.SolidForeground); } Assert.AreEqual(num + 1, stylesTable.GetFills().Count); cellStyle.FillPattern = (FillPattern.NoFill); Assert.AreEqual(FillPattern.NoFill, cellStyle.FillPattern); FillId = (int)cellStyle.GetCoreXf().fillId; ctFill = stylesTable.GetFillAt(FillId).GetCTFill(); Assert.IsFalse(ctFill.GetPatternFill().IsSetPatternType()); } [Test] public void TestGetFont() { Assert.IsNotNull(cellStyle.GetFont()); } [Test] public void TestGetSetHidden() { Assert.IsFalse(cellStyle.IsHidden); cellStyle.IsHidden = (true); Assert.IsTrue(cellStyle.IsHidden); cellStyle.IsHidden = (false); Assert.IsFalse(cellStyle.IsHidden); } [Test] public void TestGetSetLocked() { Assert.IsTrue(cellStyle.IsLocked); cellStyle.IsLocked = (true); Assert.IsTrue(cellStyle.IsLocked); cellStyle.IsLocked = (false); Assert.IsFalse(cellStyle.IsLocked); } [Test] public void TestGetSetIndent() { Assert.AreEqual((short)0, cellStyle.Indention); cellStyle.Indention = ((short)3); Assert.AreEqual((short)3, cellStyle.Indention); cellStyle.Indention = ((short)13); Assert.AreEqual((short)13, cellStyle.Indention); } [Test] public void TestGetSetAlignement() { Assert.IsTrue(!cellStyle.GetCellAlignment().GetCTCellAlignment().horizontalSpecified); Assert.AreEqual(HorizontalAlignment.General, cellStyle.Alignment); cellStyle.Alignment = HorizontalAlignment.Left; Assert.AreEqual(HorizontalAlignment.Left, cellStyle.Alignment); Assert.AreEqual(ST_HorizontalAlignment.left, cellStyle.GetCellAlignment().GetCTCellAlignment().horizontal); cellStyle.Alignment = (HorizontalAlignment.Justify); Assert.AreEqual(HorizontalAlignment.Justify, cellStyle.Alignment); Assert.AreEqual(ST_HorizontalAlignment.justify, cellStyle.GetCellAlignment().GetCTCellAlignment().horizontal); cellStyle.Alignment = (HorizontalAlignment.Center); Assert.AreEqual(HorizontalAlignment.Center, cellStyle.Alignment); Assert.AreEqual(ST_HorizontalAlignment.center, cellStyle.GetCellAlignment().GetCTCellAlignment().horizontal); } [Test] public void TestGetSetVerticalAlignment() { Assert.AreEqual(VerticalAlignment.Bottom, cellStyle.VerticalAlignment); Assert.IsTrue(!cellStyle.GetCellAlignment().GetCTCellAlignment().verticalSpecified); cellStyle.VerticalAlignment = (VerticalAlignment.Top); Assert.AreEqual(VerticalAlignment.Top, cellStyle.VerticalAlignment); Assert.AreEqual(ST_VerticalAlignment.top, cellStyle.GetCellAlignment().GetCTCellAlignment().vertical); cellStyle.VerticalAlignment = (VerticalAlignment.Center); Assert.AreEqual(VerticalAlignment.Center, cellStyle.VerticalAlignment); Assert.AreEqual(ST_VerticalAlignment.center, cellStyle.GetCellAlignment().GetCTCellAlignment().vertical); cellStyle.VerticalAlignment = VerticalAlignment.Justify; Assert.AreEqual(VerticalAlignment.Justify, cellStyle.VerticalAlignment); Assert.AreEqual(ST_VerticalAlignment.justify, cellStyle.GetCellAlignment().GetCTCellAlignment().vertical); cellStyle.VerticalAlignment = (VerticalAlignment.Bottom); Assert.AreEqual(VerticalAlignment.Bottom, cellStyle.VerticalAlignment); Assert.AreEqual(ST_VerticalAlignment.bottom, cellStyle.GetCellAlignment().GetCTCellAlignment().vertical); } [Test] public void TestGetSetWrapText() { Assert.IsFalse(cellStyle.WrapText); cellStyle.WrapText = (true); Assert.IsTrue(cellStyle.WrapText); cellStyle.WrapText = (false); Assert.IsFalse(cellStyle.WrapText); } /** * Cloning one XSSFCellStyle onto Another, same XSSFWorkbook */ [Test] public void TestCloneStyleSameWB() { XSSFWorkbook wb = new XSSFWorkbook(); Assert.AreEqual(1, wb.NumberOfFonts); XSSFFont fnt = (XSSFFont)wb.CreateFont(); fnt.FontName = ("TestingFont"); Assert.AreEqual(2, wb.NumberOfFonts); XSSFCellStyle orig = (XSSFCellStyle)wb.CreateCellStyle(); orig.Alignment = (HorizontalAlignment.Right); orig.SetFont(fnt); orig.DataFormat = (short)18; Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment); Assert.AreEqual(fnt, orig.GetFont()); Assert.AreEqual(18, orig.DataFormat); XSSFCellStyle clone = (XSSFCellStyle)wb.CreateCellStyle(); Assert.AreNotEqual(HorizontalAlignment.Right, clone.Alignment); Assert.AreNotEqual(fnt, clone.GetFont()); Assert.AreNotEqual(18, clone.DataFormat); clone.CloneStyleFrom(orig); Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment); Assert.AreEqual(fnt, clone.GetFont()); Assert.AreEqual(18, clone.DataFormat); Assert.AreEqual(2, wb.NumberOfFonts); clone.Alignment = HorizontalAlignment.Left; clone.DataFormat = 17; Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment); Assert.AreEqual(18, orig.DataFormat); } /** * Cloning one XSSFCellStyle onto Another, different XSSFWorkbooks */ [Test] public void TestCloneStyleDiffWB() { XSSFWorkbook wbOrig = new XSSFWorkbook(); Assert.AreEqual(1, wbOrig.NumberOfFonts); Assert.AreEqual(0, wbOrig.GetStylesSource().GetNumberFormats().Count); XSSFFont fnt = (XSSFFont)wbOrig.CreateFont(); fnt.FontName = ("TestingFont"); Assert.AreEqual(2, wbOrig.NumberOfFonts); Assert.AreEqual(0, wbOrig.GetStylesSource().GetNumberFormats().Count); XSSFDataFormat fmt = (XSSFDataFormat)wbOrig.CreateDataFormat(); fmt.GetFormat("MadeUpOne"); fmt.GetFormat("MadeUpTwo"); XSSFCellStyle orig = (XSSFCellStyle)wbOrig.CreateCellStyle(); orig.Alignment = (HorizontalAlignment.Right); orig.SetFont(fnt); orig.DataFormat = (fmt.GetFormat("Test##")); Assert.IsTrue(HorizontalAlignment.Right == orig.Alignment); Assert.IsTrue(fnt == orig.GetFont()); Assert.IsTrue(fmt.GetFormat("Test##") == orig.DataFormat); Assert.AreEqual(2, wbOrig.NumberOfFonts); Assert.AreEqual(3, wbOrig.GetStylesSource().GetNumberFormats().Count); // Now a style on another workbook XSSFWorkbook wbClone = new XSSFWorkbook(); Assert.AreEqual(1, wbClone.NumberOfFonts); Assert.AreEqual(0, wbClone.GetStylesSource().GetNumberFormats().Count); Assert.AreEqual(1, wbClone.NumCellStyles); XSSFDataFormat fmtClone = (XSSFDataFormat)wbClone.CreateDataFormat(); XSSFCellStyle clone = (XSSFCellStyle)wbClone.CreateCellStyle(); Assert.AreEqual(1, wbClone.NumberOfFonts); Assert.AreEqual(0, wbClone.GetStylesSource().GetNumberFormats().Count); Assert.IsFalse(HorizontalAlignment.Right == clone.Alignment); Assert.IsFalse("TestingFont" == clone.GetFont().FontName); clone.CloneStyleFrom(orig); Assert.AreEqual(2, wbClone.NumberOfFonts); Assert.AreEqual(2, wbClone.NumCellStyles); Assert.AreEqual(1, wbClone.GetStylesSource().GetNumberFormats().Count); Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment); Assert.AreEqual("TestingFont", clone.GetFont().FontName); Assert.AreEqual(fmtClone.GetFormat("Test##"), clone.DataFormat); Assert.IsFalse(fmtClone.GetFormat("Test##") == fmt.GetFormat("Test##")); // Save it and re-check XSSFWorkbook wbReload = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wbClone); Assert.AreEqual(2, wbReload.NumberOfFonts); Assert.AreEqual(2, wbReload.NumCellStyles); Assert.AreEqual(1, wbReload.GetStylesSource().GetNumberFormats().Count); XSSFCellStyle reload = (XSSFCellStyle)wbReload.GetCellStyleAt((short)1); Assert.AreEqual(HorizontalAlignment.Right, reload.Alignment); Assert.AreEqual("TestingFont", reload.GetFont().FontName); Assert.AreEqual(fmtClone.GetFormat("Test##"), reload.DataFormat); Assert.IsFalse(fmtClone.GetFormat("Test##") == fmt.GetFormat("Test##")); } /** * Avoid ArrayIndexOutOfBoundsException when creating cell style * in a workbook that has an empty xf table. */ [Test] public void TestBug52348() { XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("52348.xlsx"); StylesTable st = workbook.GetStylesSource(); Assert.AreEqual(0, st.StyleXfsSize); XSSFCellStyle style = workbook.CreateCellStyle() as XSSFCellStyle; // no exception at this point Assert.IsNull(style.GetStyleXf()); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Threading; using System; using System.IO; namespace Quixel { public static class NodeEditor { #region Fields /// <summary> The type of brush to edit with. </summary> public enum BrushType { BOX, SPHERE } public static float DENSITY_SOLIDHARD = MeshFactory.isolevel - 0.1f; public static float DENSITY_SOLIDSOFT = MeshFactory.isolevel - 5f; public static float DENSITY_EMPTY = MeshFactory.isolevel + 1f; private static byte materialID = 0; #endregion /// <summary> /// Sets the material id to paint/brush with. /// The material ID is the material's location in the material array. /// </summary> /// <param name="matID"></param> public static void setMaterial(byte matID) { materialID = matID; } /// <summary> /// Applies a brush to the terrain. /// </summary> /// <param name="type">The type/shape of the brush.</param> /// <param name="size">The size (radius) of the brush.</param> /// <param name="pos">The (real world) position to apply the brush.</param> /// <param name="val">Density to apply.</param> public static void applyBrush(BrushType type, int size, Vector3 pos, float val) { List<Node> changedNodes = new List<Node>(); float nodeWidth = NodeManager.LODSize[0]; Vector3 realPos = new Vector3(); Vector3I point = new Vector3I((int)Math.Round(pos.x / nodeWidth), (int)Math.Round(pos.y / nodeWidth), (int)Math.Round(pos.z / nodeWidth)); List<Vector3> points = getPoints(type, size, pos); for (int o = 0; o < points.Count; o++) { realPos = points[o]; Node[] editNodes = NodeManager.searchNodeContainingDensity(realPos, 0); for (int i = 0; i < editNodes.Length; i++) { Node editNode = editNodes[i]; if (editNode != null && editNode.LOD == 0) { if (!changedNodes.Contains(editNode)) changedNodes.Add(editNode); if (type == BrushType.SPHERE) { float v = val; float dist = Vector3.Distance(pos, realPos); if (val > MeshFactory.isolevel) v = 10f - ((dist / (float)size) * 5f); if (val < MeshFactory.isolevel) v = 10f + ((dist / (float)size) * 5f); } editNode.setDensityFromWorldPos(realPos, val); editNode.setMaterialFromWorldPos(realPos, materialID); } } } applyPaint(type, size + 1, pos, false); for (int i = 0; i < changedNodes.Count; i++) changedNodes[i].regenerateChunk(); } /// <summary> /// 'Heals' the terrain around a given point, essentially returning the terrain to it's original state. /// </summary> /// <param name="type">The type/shape of the brush.</param> /// <param name="size">The size (radius) of the brush.</param> /// <param name="pos">The (real world) position to apply the brush.</param> public static void applyHeal(BrushType type, int size, Vector3 pos) { byte mID = materialID; materialID = 0; applyBrush(type, size, pos, -100000f); materialID = mID; } /// <summary> /// Applies 'paint' to the area around the brush. /// </summary> /// <param name="type">The type/shape of the brush.</param> /// <param name="size">The size (radius) of the brush.</param> /// <param name="pos">The (real world) position to apply the brush.</param> /// <param name="regen">Set to true to have the engine regen the chunk after painting.</param> public static void applyPaint(BrushType type, int size, Vector3 pos, bool regen) { List<Node> changedNodes = new List<Node>(); float nodeWidth = NodeManager.LODSize[0]; Vector3 realPos = new Vector3(); Vector3I point = new Vector3I((int)Math.Round(pos.x / nodeWidth), (int)Math.Round(pos.y / nodeWidth), (int)Math.Round(pos.z / nodeWidth)); List<Vector3> points = getPoints(type, size, pos); for (int o = 0; o < points.Count; o++) { realPos = points[o]; Node[] editNodes = NodeManager.searchNodeContainingDensity(realPos, 0); for (int i = 0; i < editNodes.Length; i++) { Node editNode = editNodes[i]; if (editNode != null && editNode.LOD == 0) { if (!changedNodes.Contains(editNode)) changedNodes.Add(editNode); editNode.setMaterialFromWorldPos(realPos, materialID); } } } if (regen) for (int i = 0; i < changedNodes.Count; i++) changedNodes[i].regenerateChunk(); } /// <summary> /// Returns a list of points inside of a given brush type and size. /// </summary> /// <param name="type"></param> /// <param name="size"></param> /// <param name="pos"></param> /// <returns></returns> private static List<Vector3> getPoints(BrushType type, int size, Vector3 pos) { float nodeWidth = NodeManager.LODSize[0]; Vector3I point = new Vector3I((int)Math.Round(pos.x / nodeWidth), (int)Math.Round(pos.y / nodeWidth), (int)Math.Round(pos.z / nodeWidth)); List<Vector3> ret = new List<Vector3>(); switch (type) { case BrushType.BOX: for (int x = 0; x <= size; x++) { for (int y = 0; y <= size; y++) { for (int z = 0; z <= size; z++) { Vector3 realPos = new Vector3(); realPos.x = ((point.x + x) * nodeWidth); realPos.y = ((point.y + y) * nodeWidth); realPos.z = ((point.z + z) * nodeWidth); ret.Add(realPos); } } } break; case BrushType.SPHERE: for (int x = -size; x < size; x++) { for (int y = -size * 2; y < size; y++) { for (int z = -size; z < size; z++) { Vector3 realPos = new Vector3(); realPos.x = ((point.x + x) * nodeWidth); realPos.y = ((point.y + y) * nodeWidth); realPos.z = ((point.z + z) * nodeWidth); if (Vector3.Distance(realPos, pos) < size * nodeWidth) { ret.Add(realPos); } } } } break; } return ret; } } }
// <copyright file="PushingCollectionBase{T}.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using System.Threading; using IX.Abstractions.Collections; using IX.StandardExtensions.Threading; using JetBrains.Annotations; // ReSharper disable once CheckNamespace namespace IX.System.Collections.Generic { /// <summary> /// A base class for pushing collections. /// </summary> /// <typeparam name="T">The type of item in the pushing collection.</typeparam> /// <seealso cref="ReaderWriterSynchronizedBase" /> /// <seealso cref="ICollection" /> [DataContract( Namespace = Constants.DataContractNamespace, Name = "PushOutQueueOf{0}")] [PublicAPI] public abstract class PushingCollectionBase<T> : ReaderWriterSynchronizedBase, ICollection { /// <summary> /// The internal container. /// </summary> [DataMember(Name = "Items")] private List<T> internalContainer; /// <summary> /// The limit. /// </summary> private int limit; /// <summary> /// Initializes a new instance of the <see cref="PushingCollectionBase{T}" /> class. /// </summary> /// <param name="limit">The limit.</param> /// <exception cref="LimitArgumentNegativeException"> /// <paramref name="limit" /> is a negative /// integer. /// </exception> protected PushingCollectionBase(int limit) { if (limit < 0) { throw new LimitArgumentNegativeException(nameof(limit)); } this.limit = limit; this.internalContainer = new List<T>(); } /// <summary> /// Gets the number of elements in the push-out queue. /// </summary> /// <value>The current element count.</value> public int Count => this.InvokeIfNotDisposed( cThis => cThis.ReadLock( c2This => c2This.internalContainer.Count, cThis), this); /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection" /> is synchronized /// (thread safe). /// </summary> /// <value><see langword="true" /> if this instance is synchronized; otherwise, <see langword="false" />.</value> bool ICollection.IsSynchronized => ((ICollection)this.internalContainer).IsSynchronized; /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection" />. /// </summary> /// <value>The synchronize root.</value> object ICollection.SyncRoot => ((ICollection)this.internalContainer).SyncRoot; /// <summary> /// Gets or sets the number of items in the push-down stack. /// </summary> [DataMember] public int Limit { get => this.limit; set { this.ThrowIfCurrentObjectDisposed(); if (value < 0) { throw new LimitArgumentNegativeException(); } this.WriteLock( ( val, cThis) => { cThis.limit = val; if (val != 0) { while (cThis.internalContainer.Count > val) { cThis.internalContainer.RemoveAt(0); } } else { cThis.internalContainer.Clear(); } }, value, this); } } /// <summary> /// Gets the internal container. /// </summary> /// <value> /// The internal container. /// </value> protected IList<T> InternalContainer => this.internalContainer; /// <summary> /// Clears the observable stack. /// </summary> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "We ned to get a reference to this method to the locker")] public void Clear() => this.InvokeIfNotDisposed( thisL1 => thisL1.WriteLock(thisL1.internalContainer.Clear), this); /// <summary> /// Checks whether or not a certain item is in the stack. /// </summary> /// <param name="item">The item to check for.</param> /// <returns><see langword="true" /> if the item was found, <see langword="false" /> otherwise.</returns> public bool Contains(T item) => this.InvokeIfNotDisposed( ( itemL2, thisL2) => thisL2.ReadLock( ( itemL1, thisL1) => thisL1.internalContainer.Contains(itemL1), itemL2, thisL2), item, this); /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An enumerator that can be used to iterate through the collection.</returns> [SuppressMessage( "IDisposableAnalyzers.Correctness", "IDISP004:Don't ignore return value of type IDisposable.", Justification = "We're not.")] [SuppressMessage( "Performance", "HAA0401:Possible allocation of reference type enumerator", Justification = "That's expected for an atomic enumerator.")] public IEnumerator<T> GetEnumerator() => this.SpawnAtomicEnumerator<T, List<T>.Enumerator>(this.internalContainer.GetEnumerator()); /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.</returns> [SuppressMessage( "Performance", "HAA0401:Possible allocation of reference type enumerator", Justification = "Unavoidable.")] IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); /// <summary> /// Copies all elements of the stack to a new array. /// </summary> /// <returns>An array containing all items in the stack.</returns> public T[] ToArray() => this.InvokeIfNotDisposed( reference => reference.ReadLock( ref2 => ref2.internalContainer.ToArray(), reference), this); /// <summary> /// Copies the elements of the <see cref="PushingCollectionBase{T}" /> to an <see cref="T:System.Array" />, /// starting at a particular <see cref="T:System.Array" /> index. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied /// from <see cref="PushingCollectionBase{T}" />. The <see cref="T:System.Array" /> must have zero-based /// indexing. /// </param> /// <param name="index">The zero-based index in <paramref name="array" /> at which copying begins.</param> public void CopyTo( Array array, int index) => this.InvokeIfNotDisposed( ( arrayL2, indexL2, referenceL2) => referenceL2.ReadLock( ( arrayL1, indexL1, referenceL1) => ((ICollection)referenceL1.internalContainer).CopyTo( arrayL1, indexL1), arrayL2, indexL2, referenceL2), array, index, this); /// <summary> /// Disposes in the managed context. /// </summary> protected override void DisposeManagedContext() { base.DisposeManagedContext(); Interlocked.Exchange( ref this.internalContainer, null)?.Clear(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Security; using System.Security.Principal; using System.Threading; using System.ComponentModel; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; namespace System.Net.Security { // // The class maintains the state of the authentication process and the security context. // It encapsulates security context and does the real work in authentication and // user data encryption with NEGO SSPI package. // // This is part of the NegotiateStream PAL. // internal class NegoState { private const int ERROR_TRUST_FAILURE = 1790; // Used to serialize protectionLevel or impersonationLevel mismatch error to the remote side. private static readonly byte[] s_emptyMessage = new byte[0]; private static readonly AsyncCallback s_readCallback = new AsyncCallback(ReadCallback); private static readonly AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback); private Stream _innerStream; private bool _leaveStreamOpen; private Exception _exception; private StreamFramer _framer; private NTAuthentication _context; private int _nestedAuth; internal const int MaxReadFrameSize = 64 * 1024; internal const int MaxWriteDataSize = 63 * 1024; // 1k for the framing and trailer that is always less as per SSPI. private bool _canRetryAuthentication; private ProtectionLevel _expectedProtectionLevel; private TokenImpersonationLevel _expectedImpersonationLevel; private uint _writeSequenceNumber; private uint _readSequenceNumber; private ExtendedProtectionPolicy _extendedProtectionPolicy; // SSPI does not send a server ack on successful auth. // This is a state variable used to gracefully handle auth confirmation. private bool _remoteOk = false; internal NegoState(Stream innerStream, bool leaveStreamOpen) { if (innerStream == null) { throw new ArgumentNullException("stream"); } _innerStream = innerStream; _leaveStreamOpen = leaveStreamOpen; } internal static string DefaultPackage { get { return NegotiationInfoClass.Negotiate; } } internal void ValidateCreateContext( string package, NetworkCredential credential, string servicePrincipalName, ExtendedProtectionPolicy policy, ProtectionLevel protectionLevel, TokenImpersonationLevel impersonationLevel) { if (policy != null) { // One of these must be set if EP is turned on if (policy.CustomChannelBinding == null && policy.CustomServiceNames == null) { throw new ArgumentException(SR.net_auth_must_specify_extended_protection_scheme, "policy"); } _extendedProtectionPolicy = policy; } else { _extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never); } ValidateCreateContext(package, true, credential, servicePrincipalName, _extendedProtectionPolicy.CustomChannelBinding, protectionLevel, impersonationLevel); } internal void ValidateCreateContext( string package, bool isServer, NetworkCredential credential, string servicePrincipalName, ChannelBinding channelBinding, ProtectionLevel protectionLevel, TokenImpersonationLevel impersonationLevel) { if (_exception != null && !_canRetryAuthentication) { throw _exception; } if (_context != null && _context.IsValidContext) { throw new InvalidOperationException(SR.net_auth_reauth); } if (credential == null) { throw new ArgumentNullException("credential"); } if (servicePrincipalName == null) { throw new ArgumentNullException("servicePrincipalName"); } if (impersonationLevel != TokenImpersonationLevel.Identification && impersonationLevel != TokenImpersonationLevel.Impersonation && impersonationLevel != TokenImpersonationLevel.Delegation) { throw new ArgumentOutOfRangeException("impersonationLevel", impersonationLevel.ToString(), SR.net_auth_supported_impl_levels); } if (_context != null && IsServer != isServer) { throw new InvalidOperationException(SR.net_auth_client_server); } _exception = null; _remoteOk = false; _framer = new StreamFramer(_innerStream); _framer.WriteHeader.MessageId = FrameHeader.HandshakeId; _expectedProtectionLevel = protectionLevel; _expectedImpersonationLevel = isServer ? impersonationLevel : TokenImpersonationLevel.None; _writeSequenceNumber = 0; _readSequenceNumber = 0; Interop.SspiCli.ContextFlags flags = Interop.SspiCli.ContextFlags.Connection; // A workaround for the client when talking to Win9x on the server side. if (protectionLevel == ProtectionLevel.None && !isServer) { package = NegotiationInfoClass.NTLM; } else if (protectionLevel == ProtectionLevel.EncryptAndSign) { flags |= Interop.SspiCli.ContextFlags.Confidentiality; } else if (protectionLevel == ProtectionLevel.Sign) { // Assuming user expects NT4 SP4 and above. flags |= Interop.SspiCli.ContextFlags.ReplayDetect | Interop.SspiCli.ContextFlags.SequenceDetect | Interop.SspiCli.ContextFlags.InitIntegrity; } if (isServer) { if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.WhenSupported) { flags |= Interop.SspiCli.ContextFlags.AllowMissingBindings; } if (_extendedProtectionPolicy.PolicyEnforcement != PolicyEnforcement.Never && _extendedProtectionPolicy.ProtectionScenario == ProtectionScenario.TrustedProxy) { flags |= Interop.SspiCli.ContextFlags.ProxyBindings; } } else { // Server side should not request any of these flags. if (protectionLevel != ProtectionLevel.None) { flags |= Interop.SspiCli.ContextFlags.MutualAuth; } if (impersonationLevel == TokenImpersonationLevel.Identification) { flags |= Interop.SspiCli.ContextFlags.InitIdentify; } if (impersonationLevel == TokenImpersonationLevel.Delegation) { flags |= Interop.SspiCli.ContextFlags.Delegate; } } _canRetryAuthentication = false; try { _context = new NTAuthentication(isServer, package, credential, servicePrincipalName, flags, channelBinding); } catch (Win32Exception e) { throw new AuthenticationException(SR.net_auth_SSPI, e); } } private Exception SetException(Exception e) { if (_exception == null || !(_exception is ObjectDisposedException)) { _exception = e; } if (_exception != null && _context != null) { _context.CloseContext(); } return _exception; } internal bool IsAuthenticated { get { return _context != null && HandshakeComplete && _exception == null && _remoteOk; } } internal bool IsMutuallyAuthenticated { get { if (!IsAuthenticated) { return false; } // Suppressing for NTLM since SSPI does not return correct value in the context flags. if (_context.IsNTLM) { return false; } return _context.IsMutualAuthFlag; } } internal bool IsEncrypted { get { return IsAuthenticated && _context.IsConfidentialityFlag; } } internal bool IsSigned { get { return IsAuthenticated && (_context.IsIntegrityFlag || _context.IsConfidentialityFlag); } } internal bool IsServer { get { return _context != null && _context.IsServer; } } internal bool CanGetSecureStream { get { return (_context.IsConfidentialityFlag || _context.IsIntegrityFlag); } } internal TokenImpersonationLevel AllowedImpersonation { get { CheckThrow(true); return PrivateImpersonationLevel; } } private TokenImpersonationLevel PrivateImpersonationLevel { get { // We should suppress the delegate flag in NTLM case. return (_context.IsDelegationFlag && _context.ProtocolName != NegotiationInfoClass.NTLM) ? TokenImpersonationLevel.Delegation : _context.IsIdentifyFlag ? TokenImpersonationLevel.Identification : TokenImpersonationLevel.Impersonation; } } private bool HandshakeComplete { get { return _context.IsCompleted && _context.IsValidContext; } } internal IIdentity GetIdentity() { CheckThrow(true); IIdentity result = null; string name = _context.IsServer ? _context.AssociatedName : _context.Spn; string protocol = "NTLM"; protocol = _context.ProtocolName; if (_context.IsServer) { SecurityContextTokenHandle token = null; try { token = _context.GetContextToken(); string authtype = _context.ProtocolName; // TODO #5241: // The following call was also specifying WindowsAccountType.Normal, true. // WindowsIdentity.IsAuthenticated is no longer supported in CoreFX. result = new WindowsIdentity(token.DangerousGetHandle(), authtype); return result; } catch (SecurityException) { // Ignore and construct generic Identity if failed due to security problem. } finally { if (token != null) { token.Dispose(); } } } // On the client we don't have access to the remote side identity. result = new GenericIdentity(name, protocol); return result; } internal void CheckThrow(bool authSucessCheck) { if (_exception != null) { throw _exception; } if (authSucessCheck && !IsAuthenticated) { throw new InvalidOperationException(SR.net_auth_noauth); } } // // This is to not depend on GC&SafeHandle class if the context is not needed anymore. // internal void Close() { // Mark this instance as disposed. _exception = new ObjectDisposedException("NegotiateStream"); if (_context != null) { _context.CloseContext(); } } internal void ProcessAuthentication(LazyAsyncResult lazyResult) { CheckThrow(false); if (Interlocked.Exchange(ref _nestedAuth, 1) == 1) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidnestedcall, lazyResult == null ? "BeginAuthenticate" : "Authenticate", "authenticate")); } try { if (_context.IsServer) { // Listen for a client blob. StartReceiveBlob(lazyResult); } else { // Start with the first blob. StartSendBlob(null, lazyResult); } } catch (Exception e) { // Round-trip it through SetException(). e = SetException(e); throw; } finally { if (lazyResult == null || _exception != null) { _nestedAuth = 0; } } } internal void EndProcessAuthentication(IAsyncResult result) { if (result == null) { throw new ArgumentNullException("asyncResult"); } LazyAsyncResult lazyResult = result as LazyAsyncResult; if (lazyResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, result.GetType().FullName), "asyncResult"); } if (Interlocked.Exchange(ref _nestedAuth, 0) == 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndAuthenticate")); } // No "artificial" timeouts implemented so far, InnerStream controls that. lazyResult.InternalWaitForCompletion(); Exception e = lazyResult.Result as Exception; if (e != null) { // Round-trip it through the SetException(). e = SetException(e); throw e; } } private bool CheckSpn() { if (_context.IsKerberos) { return true; } if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Never || _extendedProtectionPolicy.CustomServiceNames == null) { return true; } string clientSpn = _context.ClientSpecifiedSpn; if (String.IsNullOrEmpty(clientSpn)) { if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.WhenSupported) { return true; } } else { return _extendedProtectionPolicy.CustomServiceNames.Contains(clientSpn); } return false; } // // Client side starts here, but server also loops through this method. // private void StartSendBlob(byte[] message, LazyAsyncResult lazyResult) { Win32Exception win32exception = null; if (message != s_emptyMessage) { message = GetOutgoingBlob(message, ref win32exception); } if (win32exception != null) { // Signal remote side on a failed attempt. StartSendAuthResetSignal(lazyResult, message, win32exception); return; } if (HandshakeComplete) { if (_context.IsServer && !CheckSpn()) { Exception exception = new AuthenticationException(SR.net_auth_bad_client_creds_or_target_mismatch); int statusCode = ERROR_TRUST_FAILURE; message = new byte[8]; //sizeof(long) for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(statusCode & 0xFF); statusCode = (int)((uint)statusCode >> 8); } StartSendAuthResetSignal(lazyResult, message, exception); return; } if (PrivateImpersonationLevel < _expectedImpersonationLevel) { Exception exception = new AuthenticationException(SR.Format(SR.net_auth_context_expectation, _expectedImpersonationLevel.ToString(), PrivateImpersonationLevel.ToString())); int statusCode = ERROR_TRUST_FAILURE; message = new byte[8]; //sizeof(long) for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(statusCode & 0xFF); statusCode = (int)((uint)statusCode >> 8); } StartSendAuthResetSignal(lazyResult, message, exception); return; } ProtectionLevel result = _context.IsConfidentialityFlag ? ProtectionLevel.EncryptAndSign : _context.IsIntegrityFlag ? ProtectionLevel.Sign : ProtectionLevel.None; if (result < _expectedProtectionLevel) { Exception exception = new AuthenticationException(SR.Format(SR.net_auth_context_expectation, result.ToString(), _expectedProtectionLevel.ToString())); int statusCode = ERROR_TRUST_FAILURE; message = new byte[8]; //sizeof(long) for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(statusCode & 0xFF); statusCode = (int)((uint)statusCode >> 8); } StartSendAuthResetSignal(lazyResult, message, exception); return; } // Signal remote party that we are done _framer.WriteHeader.MessageId = FrameHeader.HandshakeDoneId; if (_context.IsServer) { // Server may complete now because client SSPI would not complain at this point. _remoteOk = true; // However the client will wait for server to send this ACK //Force signaling server OK to the client if (message == null) { message = s_emptyMessage; } } } else if (message == null || message == s_emptyMessage) { throw new InternalException(); } if (message != null) { //even if we are completed, there could be a blob for sending. if (lazyResult == null) { _framer.WriteMessage(message); } else { IAsyncResult ar = _framer.BeginWriteMessage(message, s_writeCallback, lazyResult); if (!ar.CompletedSynchronously) { return; } _framer.EndWriteMessage(ar); } } CheckCompletionBeforeNextReceive(lazyResult); } // // This will check and logically complete the auth handshake. // private void CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult) { if (HandshakeComplete && _remoteOk) { // We are done with success. if (lazyResult != null) { lazyResult.InvokeCallback(); } return; } StartReceiveBlob(lazyResult); } // // Server side starts here, but client also loops through this method. // private void StartReceiveBlob(LazyAsyncResult lazyResult) { byte[] message; if (lazyResult == null) { message = _framer.ReadMessage(); } else { IAsyncResult ar = _framer.BeginReadMessage(s_readCallback, lazyResult); if (!ar.CompletedSynchronously) { return; } message = _framer.EndReadMessage(ar); } ProcessReceivedBlob(message, lazyResult); } private void ProcessReceivedBlob(byte[] message, LazyAsyncResult lazyResult) { // This is an EOF otherwise we would get at least *empty* message but not a null one. if (message == null) { throw new AuthenticationException(SR.net_auth_eof, null); } // Process Header information. if (_framer.ReadHeader.MessageId == FrameHeader.HandshakeErrId) { Win32Exception e = null; if (message.Length >= 8) // sizeof(long) { // Try to recover remote win32 Exception. long error = 0; for (int i = 0; i < 8; ++i) { error = (error << 8) + message[i]; } e = new Win32Exception((int)error); } if (e != null) { if (e.NativeErrorCode == (int)Interop.SecurityStatus.LogonDenied) { throw new InvalidCredentialException(SR.net_auth_bad_client_creds, e); } if (e.NativeErrorCode == ERROR_TRUST_FAILURE) { throw new AuthenticationException(SR.net_auth_context_expectation_remote, e); } } throw new AuthenticationException(SR.net_auth_alert, e); } if (_framer.ReadHeader.MessageId == FrameHeader.HandshakeDoneId) { _remoteOk = true; } else if (_framer.ReadHeader.MessageId != FrameHeader.HandshakeId) { throw new AuthenticationException(SR.Format(SR.net_io_header_id, "MessageId", _framer.ReadHeader.MessageId, FrameHeader.HandshakeId), null); } CheckCompletionBeforeNextSend(message, lazyResult); } // // This will check and logically complete the auth handshake. // private void CheckCompletionBeforeNextSend(byte[] message, LazyAsyncResult lazyResult) { //If we are done don't go into send. if (HandshakeComplete) { if (!_remoteOk) { throw new AuthenticationException(SR.Format(SR.net_io_header_id, "MessageId", _framer.ReadHeader.MessageId, FrameHeader.HandshakeDoneId), null); } if (lazyResult != null) { lazyResult.InvokeCallback(); } return; } // Not yet done, get a new blob and send it if any. StartSendBlob(message, lazyResult); } // // This is to reset auth state on the remote side. // If this write succeeds we will allow auth retrying. // private void StartSendAuthResetSignal(LazyAsyncResult lazyResult, byte[] message, Exception exception) { _framer.WriteHeader.MessageId = FrameHeader.HandshakeErrId; Win32Exception win32exception = exception as Win32Exception; if (win32exception != null && win32exception.NativeErrorCode == (int)Interop.SecurityStatus.LogonDenied) { if (IsServer) { exception = new InvalidCredentialException(SR.net_auth_bad_client_creds, exception); } else { exception = new InvalidCredentialException(SR.net_auth_bad_client_creds_or_target_mismatch, exception); } } if (!(exception is AuthenticationException)) { exception = new AuthenticationException(SR.net_auth_SSPI, exception); } if (lazyResult == null) { _framer.WriteMessage(message); } else { lazyResult.Result = exception; IAsyncResult ar = _framer.BeginWriteMessage(message, s_writeCallback, lazyResult); if (!ar.CompletedSynchronously) { return; } _framer.EndWriteMessage(ar); } _canRetryAuthentication = true; throw exception; } private static void WriteCallback(IAsyncResult transportResult) { if ((transportResult.AsyncState is LazyAsyncResult) && GlobalLog.IsEnabled) { GlobalLog.Assert("WriteCallback|State type is wrong, expected LazyAsyncResult."); } if (transportResult.CompletedSynchronously) { return; } LazyAsyncResult lazyResult = (LazyAsyncResult)transportResult.AsyncState; // Async completion. try { NegoState authState = (NegoState)lazyResult.AsyncObject; authState._framer.EndWriteMessage(transportResult); // Special case for an error notification. if (lazyResult.Result is Exception) { authState._canRetryAuthentication = true; throw (Exception)lazyResult.Result; } authState.CheckCompletionBeforeNextReceive(lazyResult); } catch (Exception e) { if (lazyResult.InternalPeekCompleted) { // This will throw on a worker thread. throw; } lazyResult.InvokeCallback(e); } } private static void ReadCallback(IAsyncResult transportResult) { if ((transportResult.AsyncState is LazyAsyncResult) && GlobalLog.IsEnabled) { GlobalLog.Assert("ReadCallback|State type is wrong, expected LazyAsyncResult."); } if (transportResult.CompletedSynchronously) { return; } LazyAsyncResult lazyResult = (LazyAsyncResult)transportResult.AsyncState; // Async completion. try { NegoState authState = (NegoState)lazyResult.AsyncObject; byte[] message = authState._framer.EndReadMessage(transportResult); authState.ProcessReceivedBlob(message, lazyResult); } catch (Exception e) { if (lazyResult.InternalPeekCompleted) { // This will throw on a worker thread. throw; } lazyResult.InvokeCallback(e); } } private unsafe byte[] GetOutgoingBlob(byte[] incomingBlob, ref Win32Exception e) { Interop.SecurityStatus statusCode; byte[] message = _context.GetOutgoingBlob(incomingBlob, false, out statusCode); if (((int)statusCode & unchecked((int)0x80000000)) != 0) { e = new System.ComponentModel.Win32Exception((int)statusCode); message = new byte[8]; //sizeof(long) for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)((uint)statusCode & 0xFF); statusCode = (Interop.SecurityStatus)((uint)statusCode >> 8); } } if (message != null && message.Length == 0) { message = s_emptyMessage; } return message; } internal int EncryptData(byte[] buffer, int offset, int count, ref byte[] outBuffer) { CheckThrow(true); // SSPI seems to ignore this sequence number. ++_writeSequenceNumber; return _context.Encrypt(buffer, offset, count, ref outBuffer, _writeSequenceNumber); } internal int DecryptData(byte[] buffer, int offset, int count, out int newOffset) { CheckThrow(true); // SSPI seems to ignore this sequence number. ++_readSequenceNumber; return _context.Decrypt(buffer, offset, count, out newOffset, _readSequenceNumber); } } }
// 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.IO; using System.Runtime.InteropServices; using System.Security.Cryptography.Asn1; using Internal.Cryptography; namespace System.Security.Cryptography { public abstract partial class RSA : AsymmetricAlgorithm { public static new RSA Create(string algName) { return (RSA)CryptoConfig.CreateFromName(algName); } public static RSA Create(int keySizeInBits) { RSA rsa = Create(); try { rsa.KeySize = keySizeInBits; return rsa; } catch { rsa.Dispose(); throw; } } public static RSA Create(RSAParameters parameters) { RSA rsa = Create(); try { rsa.ImportParameters(parameters); return rsa; } catch { rsa.Dispose(); throw; } } public abstract RSAParameters ExportParameters(bool includePrivateParameters); public abstract void ImportParameters(RSAParameters parameters); public virtual byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) => throw DerivedClassMustOverride(); public virtual byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) => throw DerivedClassMustOverride(); public virtual byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => throw DerivedClassMustOverride(); public virtual bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => throw DerivedClassMustOverride(); protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) => throw DerivedClassMustOverride(); protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) => throw DerivedClassMustOverride(); public virtual bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { byte[] result = Decrypt(data.ToArray(), padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { byte[] result = Encrypt(data.ToArray(), padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } protected virtual bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) { byte[] result; // Use ArrayPool.Shared instead of CryptoPool because the array is passed out. byte[] array = ArrayPool<byte>.Shared.Rent(data.Length); try { data.CopyTo(array); result = HashData(array, 0, data.Length, hashAlgorithm); } finally { Array.Clear(array, 0, data.Length); ArrayPool<byte>.Shared.Return(array); } if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) { byte[] result = SignHash(hash.ToArray(), hashAlgorithm, padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => VerifyHash(hash.ToArray(), signature.ToArray(), hashAlgorithm, padding); private static Exception DerivedClassMustOverride() => new NotImplementedException(SR.NotSupported_SubclassOverride); public virtual byte[] DecryptValue(byte[] rgb) => throw new NotSupportedException(SR.NotSupported_Method); // Same as Desktop public virtual byte[] EncryptValue(byte[] rgb) => throw new NotSupportedException(SR.NotSupported_Method); // Same as Desktop public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) { throw new ArgumentNullException(nameof(data)); } return SignData(data, 0, data.Length, hashAlgorithm, padding); } public virtual byte[] SignData( byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, offset, count, hashAlgorithm); return SignHash(hash, hashAlgorithm, padding); } public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, hashAlgorithm); return SignHash(hash, hashAlgorithm, padding); } public virtual bool TrySignData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) { if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); } if (padding == null) { throw new ArgumentNullException(nameof(padding)); } if (TryHashData(data, destination, hashAlgorithm, out int hashLength) && TrySignHash(destination.Slice(0, hashLength), destination, hashAlgorithm, padding, out bytesWritten)) { return true; } bytesWritten = 0; return false; } public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); return VerifyData(data, 0, data.Length, signature, hashAlgorithm, padding); } public virtual bool VerifyData( byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); if (signature == null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, offset, count, hashAlgorithm); return VerifyHash(hash, signature, hashAlgorithm, padding); } public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (signature == null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, hashAlgorithm); return VerifyHash(hash, signature, hashAlgorithm, padding); } public virtual bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); } if (padding == null) { throw new ArgumentNullException(nameof(padding)); } for (int i = 256; ; i = checked(i * 2)) { int hashLength = 0; byte[] hash = CryptoPool.Rent(i); try { if (TryHashData(data, hash, hashAlgorithm, out hashLength)) { return VerifyHash(new ReadOnlySpan<byte>(hash, 0, hashLength), signature, hashAlgorithm, padding); } } finally { CryptoPool.Return(hash, hashLength); } } } public virtual byte[] ExportRSAPrivateKey() { using (AsnWriter pkcs1PrivateKey = WritePkcs1PrivateKey()) { return pkcs1PrivateKey.Encode(); } } public virtual bool TryExportRSAPrivateKey(Span<byte> destination, out int bytesWritten) { using (AsnWriter pkcs1PrivateKey = WritePkcs1PrivateKey()) { return pkcs1PrivateKey.TryEncode(destination, out bytesWritten); } } public virtual byte[] ExportRSAPublicKey() { using (AsnWriter pkcs1PublicKey = WritePkcs1PublicKey()) { return pkcs1PublicKey.Encode(); } } public virtual bool TryExportRSAPublicKey(Span<byte> destination, out int bytesWritten) { using (AsnWriter pkcs1PublicKey = WritePkcs1PublicKey()) { return pkcs1PublicKey.TryEncode(destination, out bytesWritten); } } public override unsafe bool TryExportSubjectPublicKeyInfo(Span<byte> destination, out int bytesWritten) { // The PKCS1 RSAPublicKey format is just the modulus (KeySize bits) and Exponent (usually 3 bytes), // with each field having up to 7 bytes of overhead and then up to 6 extra bytes of overhead for the // SEQUENCE tag. // // So KeySize / 4 is ideally enough to start. int rentSize = KeySize / 4; while (true) { byte[] rented = CryptoPool.Rent(rentSize); rentSize = rented.Length; int pkcs1Size = 0; fixed (byte* rentPtr = rented) { try { if (!TryExportRSAPublicKey(rented, out pkcs1Size)) { rentSize = checked(rentSize * 2); continue; } using (AsnWriter writer = RSAKeyFormatHelper.WriteSubjectPublicKeyInfo(rented.AsSpan(0, pkcs1Size))) { return writer.TryEncode(destination, out bytesWritten); } } finally { CryptoPool.Return(rented, pkcs1Size); } } } } public override bool TryExportPkcs8PrivateKey(Span<byte> destination, out int bytesWritten) { using (AsnWriter writer = WritePkcs8PrivateKey()) { return writer.TryEncode(destination, out bytesWritten); } } private unsafe AsnWriter WritePkcs8PrivateKey() { // A PKCS1 RSAPrivateKey is the Modulus (KeySize bits), D (~KeySize bits) // P, Q, DP, DQ, InverseQ (all ~KeySize/2 bits) // Each field can have up to 7 bytes of overhead, and then another 9 bytes // of fixed overhead. // So it should fit in 5 * KeySizeInBytes, but Exponent is a wildcard. int rentSize = checked(5 * KeySize / 8); while (true) { byte[] rented = CryptoPool.Rent(rentSize); rentSize = rented.Length; int pkcs1Size = 0; fixed (byte* rentPtr = rented) { try { if (!TryExportRSAPrivateKey(rented, out pkcs1Size)) { rentSize = checked(rentSize * 2); continue; } return RSAKeyFormatHelper.WritePkcs8PrivateKey(new ReadOnlySpan<byte>(rented, 0, pkcs1Size)); } finally { CryptoPool.Return(rented, pkcs1Size); } } } } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); using (AsnWriter pkcs8PrivateKey = WritePkcs8PrivateKey()) using (AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8( password, pkcs8PrivateKey, pbeParameters)) { return writer.TryEncode(destination, out bytesWritten); } } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan<char>.Empty, passwordBytes); using (AsnWriter pkcs8PrivateKey = WritePkcs8PrivateKey()) using (AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8( passwordBytes, pkcs8PrivateKey, pbeParameters)) { return writer.TryEncode(destination, out bytesWritten); } } private AsnWriter WritePkcs1PublicKey() { RSAParameters rsaParameters = ExportParameters(false); return RSAKeyFormatHelper.WritePkcs1PublicKey(rsaParameters); } private unsafe AsnWriter WritePkcs1PrivateKey() { RSAParameters rsaParameters = ExportParameters(true); fixed (byte* dPin = rsaParameters.D) fixed (byte* pPin = rsaParameters.P) fixed (byte* qPin = rsaParameters.Q) fixed (byte* dpPin = rsaParameters.DP) fixed (byte* dqPin = rsaParameters.DQ) fixed (byte* qInvPin = rsaParameters.InverseQ) { try { return RSAKeyFormatHelper.WritePkcs1PrivateKey(rsaParameters); } finally { ClearPrivateParameters(rsaParameters); } } } public override unsafe void ImportSubjectPublicKeyInfo(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { ReadOnlyMemory<byte> pkcs1 = RSAKeyFormatHelper.ReadSubjectPublicKeyInfo( manager.Memory, out int localRead); ImportRSAPublicKey(pkcs1.Span, out _); bytesRead = localRead; } } } public virtual unsafe void ImportRSAPublicKey(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { AsnReader reader = new AsnReader(manager.Memory, AsnEncodingRules.BER); ReadOnlyMemory<byte> firstValue = reader.PeekEncodedValue(); int localRead = firstValue.Length; AlgorithmIdentifierAsn ignored = default; RSAKeyFormatHelper.ReadRsaPublicKey(firstValue, ignored, out RSAParameters rsaParameters); ImportParameters(rsaParameters); bytesRead = localRead; } } } public virtual unsafe void ImportRSAPrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { AsnReader reader = new AsnReader(manager.Memory, AsnEncodingRules.BER); ReadOnlyMemory<byte> firstValue = reader.PeekEncodedValue(); int localRead = firstValue.Length; AlgorithmIdentifierAsn ignored = default; RSAKeyFormatHelper.FromPkcs1PrivateKey(firstValue, ignored, out RSAParameters rsaParameters); fixed (byte* dPin = rsaParameters.D) fixed (byte* pPin = rsaParameters.P) fixed (byte* qPin = rsaParameters.Q) fixed (byte* dpPin = rsaParameters.DP) fixed (byte* dqPin = rsaParameters.DQ) fixed (byte* qInvPin = rsaParameters.InverseQ) { try { ImportParameters(rsaParameters); } finally { ClearPrivateParameters(rsaParameters); } } bytesRead = localRead; } } } public override unsafe void ImportPkcs8PrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { ReadOnlyMemory<byte> pkcs1 = RSAKeyFormatHelper.ReadPkcs8( manager.Memory, out int localRead); ImportRSAPrivateKey(pkcs1.Span, out _); bytesRead = localRead; } } } public override unsafe void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, ReadOnlySpan<byte> source, out int bytesRead) { RSAKeyFormatHelper.ReadEncryptedPkcs8( source, passwordBytes, out int localRead, out RSAParameters ret); fixed (byte* dPin = ret.D) fixed (byte* pPin = ret.P) fixed (byte* qPin = ret.Q) fixed (byte* dpPin = ret.DP) fixed (byte* dqPin = ret.DQ) fixed (byte* qInvPin = ret.InverseQ) { try { ImportParameters(ret); } finally { ClearPrivateParameters(ret); } } bytesRead = localRead; } public override unsafe void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, ReadOnlySpan<byte> source, out int bytesRead) { RSAKeyFormatHelper.ReadEncryptedPkcs8( source, password, out int localRead, out RSAParameters ret); fixed (byte* dPin = ret.D) fixed (byte* pPin = ret.P) fixed (byte* qPin = ret.Q) fixed (byte* dpPin = ret.DP) fixed (byte* dqPin = ret.DQ) fixed (byte* qInvPin = ret.InverseQ) { try { ImportParameters(ret); } finally { ClearPrivateParameters(ret); } } bytesRead = localRead; } private static void ClearPrivateParameters(in RSAParameters rsaParameters) { CryptographicOperations.ZeroMemory(rsaParameters.D); CryptographicOperations.ZeroMemory(rsaParameters.P); CryptographicOperations.ZeroMemory(rsaParameters.Q); CryptographicOperations.ZeroMemory(rsaParameters.DP); CryptographicOperations.ZeroMemory(rsaParameters.DQ); CryptographicOperations.ZeroMemory(rsaParameters.InverseQ); } public override string KeyExchangeAlgorithm => "RSA"; public override string SignatureAlgorithm => "RSA"; private static Exception HashAlgorithmNameNullOrEmpty() => new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using FFmpeg.AutoGen; using osuTK; using osu.Framework.Graphics.Textures; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.EnumExtensions; using osu.Framework.Logging; using osu.Framework.Platform; using AGffmpeg = FFmpeg.AutoGen.ffmpeg; namespace osu.Framework.Graphics.Video { /// <summary> /// Represents a video decoder that can be used convert video streams and files into textures. /// </summary> public unsafe class VideoDecoder : IDisposable { /// <summary> /// The duration of the video that is being decoded. Can only be queried after the decoder has started decoding has loaded. This value may be an estimate by FFmpeg, depending on the video loaded. /// </summary> public double Duration { get; private set; } /// <summary> /// True if the decoder currently does not decode any more frames, false otherwise. /// </summary> public bool IsRunning => State == DecoderState.Running; /// <summary> /// True if the decoder has faulted after starting to decode. You can try to restart a failed decoder by invoking <see cref="StartDecoding"/> again. /// </summary> public bool IsFaulted => State == DecoderState.Faulted; /// <summary> /// The timestamp of the last frame that was decoded by this video decoder, or 0 if no frames have been decoded. /// </summary> public float LastDecodedFrameTime => lastDecodedFrameTime; /// <summary> /// The frame rate of the video stream this decoder is decoding. /// </summary> public double FrameRate => stream == null ? 0 : stream->avg_frame_rate.GetValue(); /// <summary> /// True if the decoder can seek, false otherwise. Determined by the stream this decoder was created with. /// </summary> public bool CanSeek => videoStream?.CanSeek == true; /// <summary> /// The current state of the decoding process. /// </summary> public DecoderState State { get; private set; } /// <summary> /// Determines which hardware acceleration device(s) should be used. /// </summary> public readonly Bindable<HardwareVideoDecoder> TargetHardwareVideoDecoders = new Bindable<HardwareVideoDecoder>(); // libav-context-related private AVFormatContext* formatContext; private AVIOContext* ioContext; private AVStream* stream; private AVCodecContext* codecContext; private SwsContext* swsContext; private avio_alloc_context_read_packet readPacketCallback; private avio_alloc_context_seek seekCallback; private bool inputOpened; private bool isDisposed; private Stream videoStream; private double timeBaseInSeconds; // active decoder state private volatile float lastDecodedFrameTime; private Task decodingTask; private CancellationTokenSource decodingTaskCancellationTokenSource; private double? skipOutputUntilTime; private readonly ConcurrentQueue<DecodedFrame> decodedFrames; private readonly ConcurrentQueue<Action> decoderCommands; private readonly ConcurrentQueue<Texture> availableTextures; private ObjectHandle<VideoDecoder> handle; private readonly FFmpegFuncs ffmpeg; internal bool Looping; /// <summary> /// Creates a new video decoder that decodes the given video file. /// </summary> /// <param name="filename">The path to the file that should be decoded.</param> public VideoDecoder(string filename) : this(File.OpenRead(filename)) { } /// <summary> /// Creates a new video decoder that decodes the given video stream. /// </summary> /// <param name="videoStream">The stream that should be decoded.</param> public VideoDecoder(Stream videoStream) { ffmpeg = CreateFuncs(); this.videoStream = videoStream; if (!videoStream.CanRead) throw new InvalidOperationException($"The given stream does not support reading. A stream used for a {nameof(VideoDecoder)} must support reading."); State = DecoderState.Ready; decodedFrames = new ConcurrentQueue<DecodedFrame>(); decoderCommands = new ConcurrentQueue<Action>(); availableTextures = new ConcurrentQueue<Texture>(); // TODO: use "real" object pool when there's some public pool supporting disposables handle = new ObjectHandle<VideoDecoder>(this, GCHandleType.Normal); TargetHardwareVideoDecoders.BindValueChanged(e => { // ignore if decoding wasn't initialized yet. if (formatContext == null) return; decoderCommands.Enqueue(recreateCodecContext); }); } /// <summary> /// Seek the decoder to the given timestamp. This will fail if <see cref="CanSeek"/> is false. /// </summary> /// <param name="targetTimestamp">The timestamp to seek to.</param> public void Seek(double targetTimestamp) { if (!CanSeek) throw new InvalidOperationException("This decoder cannot seek because the underlying stream used to decode the video does not support seeking."); decoderCommands.Enqueue(() => { ffmpeg.av_seek_frame(formatContext, stream->index, (long)(targetTimestamp / timeBaseInSeconds / 1000.0), AGffmpeg.AVSEEK_FLAG_BACKWARD); skipOutputUntilTime = targetTimestamp; State = DecoderState.Ready; }); } /// <summary> /// Returns the given frames back to the decoder, allowing the decoder to reuse the textures contained in the frames to draw new frames. /// </summary> /// <param name="frames">The frames that should be returned to the decoder.</param> public void ReturnFrames(IEnumerable<DecodedFrame> frames) { foreach (var f in frames) { ((VideoTexture)f.Texture.TextureGL).FlushUploads(); availableTextures.Enqueue(f.Texture); } } /// <summary> /// Starts the decoding process. The decoding will happen asynchronously in a separate thread. The decoded frames can be retrieved by using <see cref="GetDecodedFrames"/>. /// </summary> public void StartDecoding() { if (decodingTask != null) throw new InvalidOperationException($"Cannot start decoding once already started. Call {nameof(StopDecodingAsync)} first."); // only prepare for decoding if this is our first time starting the decoding process if (formatContext == null) { try { prepareDecoding(); recreateCodecContext(); } catch (Exception e) { Logger.Log($"VideoDecoder faulted: {e}"); State = DecoderState.Faulted; return; } } decodingTaskCancellationTokenSource = new CancellationTokenSource(); decodingTask = Task.Factory.StartNew(() => decodingLoop(decodingTaskCancellationTokenSource.Token), decodingTaskCancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); } /// <summary> /// Stops the decoding process. /// </summary> public Task StopDecodingAsync() { if (decodingTask == null) return Task.CompletedTask; decodingTaskCancellationTokenSource.Cancel(); return decodingTask.ContinueWith(_ => { decodingTask = null; decodingTaskCancellationTokenSource.Dispose(); decodingTaskCancellationTokenSource = null; State = DecoderState.Ready; }); } /// <summary> /// Gets all frames that have been decoded by the decoder up until the point in time when this method was called. /// Retrieving decoded frames using this method consumes them, ie calling this method again will never retrieve the same frame twice. /// </summary> /// <returns>The frames that have been decoded up until the point in time this method was called.</returns> public IEnumerable<DecodedFrame> GetDecodedFrames() { var frames = new List<DecodedFrame>(decodedFrames.Count); while (decodedFrames.TryDequeue(out var df)) frames.Add(df); return frames; } // https://en.wikipedia.org/wiki/YCbCr public Matrix3 GetConversionMatrix() { if (codecContext == null) return Matrix3.Zero; switch (codecContext->colorspace) { case AVColorSpace.AVCOL_SPC_BT709: return new Matrix3(1.164f, 1.164f, 1.164f, 0.000f, -0.213f, 2.112f, 1.793f, -0.533f, 0.000f); case AVColorSpace.AVCOL_SPC_UNSPECIFIED: case AVColorSpace.AVCOL_SPC_SMPTE170M: case AVColorSpace.AVCOL_SPC_SMPTE240M: default: return new Matrix3(1.164f, 1.164f, 1.164f, 0.000f, -0.392f, 2.017f, 1.596f, -0.813f, 0.000f); } } [MonoPInvokeCallback(typeof(avio_alloc_context_read_packet))] private static int readPacket(void* opaque, byte* bufferPtr, int bufferSize) { var handle = new ObjectHandle<VideoDecoder>((IntPtr)opaque); if (!handle.GetTarget(out VideoDecoder decoder)) return 0; var span = new Span<byte>(bufferPtr, bufferSize); return decoder.videoStream.Read(span); } [MonoPInvokeCallback(typeof(avio_alloc_context_seek))] private static long streamSeekCallbacks(void* opaque, long offset, int whence) { var handle = new ObjectHandle<VideoDecoder>((IntPtr)opaque); if (!handle.GetTarget(out VideoDecoder decoder)) return -1; if (!decoder.videoStream.CanSeek) throw new InvalidOperationException("Tried seeking on a video sourced by a non-seekable stream."); switch (whence) { case StdIo.SEEK_CUR: decoder.videoStream.Seek(offset, SeekOrigin.Current); break; case StdIo.SEEK_END: decoder.videoStream.Seek(offset, SeekOrigin.End); break; case StdIo.SEEK_SET: decoder.videoStream.Seek(offset, SeekOrigin.Begin); break; case AGffmpeg.AVSEEK_SIZE: return decoder.videoStream.Length; default: return -1; } return decoder.videoStream.Position; } // sets up libavformat state: creates the AVFormatContext, the frames, etc. to start decoding, but does not actually start the decodingLoop private void prepareDecoding() { const int context_buffer_size = 4096; readPacketCallback = readPacket; seekCallback = streamSeekCallbacks; // we shouldn't keep a reference to this buffer as it can be freed and replaced by the native libs themselves. // https://ffmpeg.org/doxygen/4.1/aviobuf_8c.html#a853f5149136a27ffba3207d8520172a5 byte* contextBuffer = (byte*)ffmpeg.av_malloc(context_buffer_size); ioContext = ffmpeg.avio_alloc_context(contextBuffer, context_buffer_size, 0, (void*)handle.Handle, readPacketCallback, null, seekCallback); var fcPtr = ffmpeg.avformat_alloc_context(); formatContext = fcPtr; formatContext->pb = ioContext; formatContext->flags |= AGffmpeg.AVFMT_FLAG_GENPTS; // required for most HW decoders as they only read `pts` int openInputResult = ffmpeg.avformat_open_input(&fcPtr, "dummy", null, null); inputOpened = openInputResult >= 0; if (!inputOpened) throw new InvalidOperationException($"Error opening file or stream: {getErrorMessage(openInputResult)}"); int findStreamInfoResult = ffmpeg.avformat_find_stream_info(formatContext, null); if (findStreamInfoResult < 0) throw new InvalidOperationException($"Error finding stream info: {getErrorMessage(findStreamInfoResult)}"); int streamIndex = ffmpeg.av_find_best_stream(formatContext, AVMediaType.AVMEDIA_TYPE_VIDEO, -1, -1, null, 0); if (streamIndex < 0) throw new InvalidOperationException($"Couldn't find video stream: {getErrorMessage(streamIndex)}"); stream = formatContext->streams[streamIndex]; timeBaseInSeconds = stream->time_base.GetValue(); if (stream->duration > 0) Duration = stream->duration * timeBaseInSeconds * 1000.0; else Duration = formatContext->duration / (double)AGffmpeg.AV_TIME_BASE * 1000.0; } private void recreateCodecContext() { if (stream == null) return; var codecParams = *stream->codecpar; bool openSuccessful = false; foreach (var (decoder, hwDeviceType) in GetAvailableDecoders(formatContext->iformat, codecParams.codec_id, TargetHardwareVideoDecoders.Value)) { // free context in case it was allocated in a previous iteration or recreate call. if (codecContext != null) { fixed (AVCodecContext** ptr = &codecContext) ffmpeg.avcodec_free_context(ptr); } codecContext = ffmpeg.avcodec_alloc_context3(decoder.Pointer); codecContext->pkt_timebase = stream->time_base; if (codecContext == null) { Logger.Log($"Couldn't allocate codec context. Codec: {decoder.Name}"); continue; } int paramCopyResult = ffmpeg.avcodec_parameters_to_context(codecContext, &codecParams); if (paramCopyResult < 0) { Logger.Log($"Couldn't copy codec parameters from {decoder.Name}: {getErrorMessage(paramCopyResult)}"); continue; } // initialize hardware decode context. if (hwDeviceType != AVHWDeviceType.AV_HWDEVICE_TYPE_NONE) { int hwDeviceCreateResult = ffmpeg.av_hwdevice_ctx_create(&codecContext->hw_device_ctx, hwDeviceType, null, null, 0); if (hwDeviceCreateResult < 0) { Logger.Log($"Couldn't create hardware video decoder context {hwDeviceType} for codec {decoder.Name}: {getErrorMessage(hwDeviceCreateResult)}"); continue; } Logger.Log($"Successfully opened hardware video decoder context {hwDeviceType} for codec {decoder.Name}"); } int openCodecResult = ffmpeg.avcodec_open2(codecContext, decoder.Pointer, null); if (openCodecResult < 0) { Logger.Log($"Error trying to open {decoder.Name} codec: {getErrorMessage(openCodecResult)}"); continue; } Logger.Log($"Successfully initialized decoder: {decoder.Name}"); openSuccessful = true; break; } if (!openSuccessful) throw new InvalidOperationException("No usable decoder found"); } private void decodingLoop(CancellationToken cancellationToken) { var packet = ffmpeg.av_packet_alloc(); var receiveFrame = ffmpeg.av_frame_alloc(); const int max_pending_frames = 3; try { while (!cancellationToken.IsCancellationRequested) { switch (State) { case DecoderState.Ready: case DecoderState.Running: if (decodedFrames.Count < max_pending_frames) { decodeNextFrame(packet, receiveFrame); } else { // wait until existing buffers are consumed. State = DecoderState.Ready; Thread.Sleep(1); } break; case DecoderState.EndOfStream: // While at the end of the stream, avoid attempting to read further as this comes with a non-negligible overhead. // A Seek() operation will trigger a state change, allowing decoding to potentially start again. Thread.Sleep(50); break; default: Debug.Fail($"Video decoder should never be in a \"{State}\" state during decode."); return; } while (!decoderCommands.IsEmpty) { if (cancellationToken.IsCancellationRequested) return; if (decoderCommands.TryDequeue(out var cmd)) cmd(); } } } catch (Exception e) { Logger.Error(e, "VideoDecoder faulted"); State = DecoderState.Faulted; } finally { ffmpeg.av_packet_free(&packet); ffmpeg.av_frame_free(&receiveFrame); if (State != DecoderState.Faulted) State = DecoderState.Stopped; } } private void decodeNextFrame(AVPacket* packet, AVFrame* receiveFrame) { // read data from input into AVPacket. // only read if the packet is empty, otherwise we would overwrite what's already there which can lead to visual glitches. int readFrameResult = 0; if (packet->buf == null) readFrameResult = ffmpeg.av_read_frame(formatContext, packet); if (readFrameResult >= 0) { State = DecoderState.Running; bool unrefPacket = true; if (packet->stream_index == stream->index) { // send the packet for decoding. int sendPacketResult = ffmpeg.avcodec_send_packet(codecContext, packet); // Note: EAGAIN can be returned if there's too many pending frames, which we have to read, // otherwise we would get stuck in an infinite loop. if (sendPacketResult == 0 || sendPacketResult == -AGffmpeg.EAGAIN) { readDecodedFrames(receiveFrame); // keep the packet data for next frame if we didn't send it successfully. if (sendPacketResult != 0) unrefPacket = false; } else Logger.Log($"Failed to send avcodec packet: {getErrorMessage(sendPacketResult)}"); } if (unrefPacket) ffmpeg.av_packet_unref(packet); } else if (readFrameResult == AGffmpeg.AVERROR_EOF) { if (Looping) { Seek(0); } else { // This marks the video stream as no longer relevant (until a future potential Seek operation). State = DecoderState.EndOfStream; } } else if (readFrameResult == -AGffmpeg.EAGAIN) { State = DecoderState.Ready; Thread.Sleep(1); } else { Logger.Log($"Failed to read data into avcodec packet: {getErrorMessage(readFrameResult)}"); Thread.Sleep(1); } } private readonly ConcurrentQueue<FFmpegFrame> hwTransferFrames = new ConcurrentQueue<FFmpegFrame>(); private void returnHwTransferFrame(FFmpegFrame frame) => hwTransferFrames.Enqueue(frame); private void readDecodedFrames(AVFrame* receiveFrame) { while (true) { int receiveFrameResult = ffmpeg.avcodec_receive_frame(codecContext, receiveFrame); if (receiveFrameResult < 0) { if (receiveFrameResult != -AGffmpeg.EAGAIN && receiveFrameResult != AGffmpeg.AVERROR_EOF) { Logger.Log($"Failed to receive frame from avcodec: {getErrorMessage(receiveFrameResult)}"); } break; } // use `best_effort_timestamp` as it can be more accurate if timestamps from the source file (pts) are broken. // but some HW codecs don't set it in which case fallback to `pts` long frameTimestamp = receiveFrame->best_effort_timestamp != AGffmpeg.AV_NOPTS_VALUE ? receiveFrame->best_effort_timestamp : receiveFrame->pts; double frameTime = (frameTimestamp - stream->start_time) * timeBaseInSeconds * 1000; if (skipOutputUntilTime > frameTime) continue; // get final frame. FFmpegFrame frame; if (((AVPixelFormat)receiveFrame->format).IsHardwarePixelFormat()) { // transfer data from HW decoder to RAM. if (!hwTransferFrames.TryDequeue(out var hwTransferFrame)) hwTransferFrame = new FFmpegFrame(ffmpeg, returnHwTransferFrame); // WARNING: frames from `av_hwframe_transfer_data` have their timestamps set to AV_NOPTS_VALUE instead of real values. // if you need to use them later, take them from `receiveFrame`. int transferResult = ffmpeg.av_hwframe_transfer_data(hwTransferFrame.Pointer, receiveFrame, 0); if (transferResult < 0) { Logger.Log($"Failed to transfer frame from HW decoder: {getErrorMessage(transferResult)}"); // dispose of the frame instead of enqueueing it in case that the failure was caused by it's configuration. hwTransferFrame.Dispose(); continue; } frame = hwTransferFrame; } else { // copy data to a new AVFrame so that `receiveFrame` can be reused. frame = new FFmpegFrame(ffmpeg); ffmpeg.av_frame_move_ref(frame.Pointer, receiveFrame); } lastDecodedFrameTime = (float)frameTime; // Note: this is the pixel format that `VideoTexture` expects internally frame = ensureFramePixelFormat(frame, AVPixelFormat.AV_PIX_FMT_YUV420P); if (frame == null) continue; if (!availableTextures.TryDequeue(out var tex)) tex = new Texture(new VideoTexture(frame.Pointer->width, frame.Pointer->height)); var upload = new VideoTextureUpload(frame); tex.SetData(upload); decodedFrames.Enqueue(new DecodedFrame { Time = frameTime, Texture = tex }); } } private readonly ConcurrentQueue<FFmpegFrame> scalerFrames = new ConcurrentQueue<FFmpegFrame>(); private void returnScalerFrame(FFmpegFrame frame) => scalerFrames.Enqueue(frame); [CanBeNull] private FFmpegFrame ensureFramePixelFormat(FFmpegFrame frame, AVPixelFormat targetPixelFormat) { if (frame.PixelFormat == targetPixelFormat) return frame; int width = frame.Pointer->width; int height = frame.Pointer->height; swsContext = ffmpeg.sws_getCachedContext( swsContext, width, height, frame.PixelFormat, width, height, targetPixelFormat, 1, null, null, null); if (!scalerFrames.TryDequeue(out var scalerFrame)) scalerFrame = new FFmpegFrame(ffmpeg, returnScalerFrame); // (re)initialize the scaler frame if needed. if (scalerFrame.PixelFormat != targetPixelFormat || scalerFrame.Pointer->width != width || scalerFrame.Pointer->height != height) { ffmpeg.av_frame_unref(scalerFrame.Pointer); // Note: this field determines the scaler's output pix format. scalerFrame.PixelFormat = targetPixelFormat; scalerFrame.Pointer->width = width; scalerFrame.Pointer->height = height; int getBufferResult = ffmpeg.av_frame_get_buffer(scalerFrame.Pointer, 0); if (getBufferResult < 0) { Logger.Log($"Failed to allocate SWS frame buffer: {getErrorMessage(getBufferResult)}"); scalerFrame.Dispose(); frame.Return(); return null; } } int scalerResult = ffmpeg.sws_scale( swsContext, frame.Pointer->data, frame.Pointer->linesize, 0, height, scalerFrame.Pointer->data, scalerFrame.Pointer->linesize); // return the original frame regardless of the scaler result. frame.Return(); if (scalerResult < 0) { Logger.Log($"Failed to scale frame: {getErrorMessage(scalerResult)}"); scalerFrame.Dispose(); return null; } return scalerFrame; } private string getErrorMessage(int errorCode) { const ulong buffer_size = 256; byte[] buffer = new byte[buffer_size]; int strErrorCode; fixed (byte* bufPtr = buffer) { strErrorCode = ffmpeg.av_strerror(errorCode, bufPtr, buffer_size); } if (strErrorCode < 0) return $"{errorCode} (av_strerror failed with code {strErrorCode})"; int messageLength = Math.Max(0, Array.IndexOf(buffer, (byte)0)); return $"{Encoding.ASCII.GetString(buffer[..messageLength])} ({errorCode})"; } /// <remarks> /// Returned HW devices are not guaranteed to be available on the current machine, they only represent what the loaded FFmpeg libraries support. /// </remarks> protected virtual IEnumerable<(FFmpegCodec codec, AVHWDeviceType hwDeviceType)> GetAvailableDecoders( AVInputFormat* inputFormat, AVCodecID codecId, HardwareVideoDecoder targetHwDecoders ) { var comparer = new AVHWDeviceTypePerformanceComparer(); var codecs = new Lists.SortedList<(FFmpegCodec, AVHWDeviceType hwDeviceType)>((x, y) => comparer.Compare(x.hwDeviceType, y.hwDeviceType)); FFmpegCodec firstCodec = null; void* iterator = null; while (true) { var avCodec = ffmpeg.av_codec_iterate(&iterator); if (avCodec == null) break; var codec = new FFmpegCodec(ffmpeg, avCodec); if (codec.Id != codecId || !codec.IsDecoder) continue; firstCodec ??= codec; if (targetHwDecoders == HardwareVideoDecoder.None) break; foreach (var hwDeviceType in codec.SupportedHwDeviceTypes.Value) { var hwVideoDecoder = hwDeviceType.ToHardwareVideoDecoder(); if (!hwVideoDecoder.HasValue || !targetHwDecoders.HasFlagFast(hwVideoDecoder.Value)) continue; codecs.Add((codec, hwDeviceType)); } } // default to the first codec that we found with no HW devices. // The first codec is what FFmpeg's `avcodec_find_decoder` would return so this way we'll automatically fallback to that. if (firstCodec != null) codecs.Add((firstCodec, AVHWDeviceType.AV_HWDEVICE_TYPE_NONE)); return codecs; } protected virtual FFmpegFuncs CreateFuncs() { // other frameworks should handle native libraries themselves #if NET6_0 AGffmpeg.GetOrLoadLibrary = name => { int version = AGffmpeg.LibraryVersionMap[name]; string libraryName = null; // "lib" prefix and extensions are resolved by .net core switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.macOS: libraryName = $"{name}.{version}"; break; case RuntimeInfo.Platform.Windows: libraryName = $"{name}-{version}"; break; case RuntimeInfo.Platform.Linux: libraryName = name; break; } return NativeLibrary.Load(libraryName, System.Reflection.Assembly.GetEntryAssembly(), DllImportSearchPath.UseDllDirectoryForDependencies | DllImportSearchPath.SafeDirectories); }; #endif return new FFmpegFuncs { av_frame_alloc = AGffmpeg.av_frame_alloc, av_frame_free = AGffmpeg.av_frame_free, av_frame_unref = AGffmpeg.av_frame_unref, av_frame_move_ref = AGffmpeg.av_frame_move_ref, av_frame_get_buffer = AGffmpeg.av_frame_get_buffer, av_strdup = AGffmpeg.av_strdup, av_strerror = AGffmpeg.av_strerror, av_malloc = AGffmpeg.av_malloc, av_freep = AGffmpeg.av_freep, av_packet_alloc = AGffmpeg.av_packet_alloc, av_packet_unref = AGffmpeg.av_packet_unref, av_packet_free = AGffmpeg.av_packet_free, av_read_frame = AGffmpeg.av_read_frame, av_seek_frame = AGffmpeg.av_seek_frame, av_hwdevice_ctx_create = AGffmpeg.av_hwdevice_ctx_create, av_hwframe_transfer_data = AGffmpeg.av_hwframe_transfer_data, av_codec_iterate = AGffmpeg.av_codec_iterate, av_codec_is_decoder = AGffmpeg.av_codec_is_decoder, avcodec_get_hw_config = AGffmpeg.avcodec_get_hw_config, avcodec_alloc_context3 = AGffmpeg.avcodec_alloc_context3, avcodec_free_context = AGffmpeg.avcodec_free_context, avcodec_parameters_to_context = AGffmpeg.avcodec_parameters_to_context, avcodec_open2 = AGffmpeg.avcodec_open2, avcodec_receive_frame = AGffmpeg.avcodec_receive_frame, avcodec_send_packet = AGffmpeg.avcodec_send_packet, avformat_alloc_context = AGffmpeg.avformat_alloc_context, avformat_close_input = AGffmpeg.avformat_close_input, avformat_find_stream_info = AGffmpeg.avformat_find_stream_info, avformat_open_input = AGffmpeg.avformat_open_input, av_find_best_stream = AGffmpeg.av_find_best_stream, avio_alloc_context = AGffmpeg.avio_alloc_context, avio_context_free = AGffmpeg.avio_context_free, sws_freeContext = AGffmpeg.sws_freeContext, sws_getCachedContext = AGffmpeg.sws_getCachedContext, sws_scale = AGffmpeg.sws_scale }; } #region Disposal ~VideoDecoder() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (isDisposed) return; isDisposed = true; decoderCommands.Clear(); StopDecodingAsync().ContinueWith(_ => { if (formatContext != null && inputOpened) { fixed (AVFormatContext** ptr = &formatContext) ffmpeg.avformat_close_input(ptr); } if (codecContext != null) { fixed (AVCodecContext** ptr = &codecContext) ffmpeg.avcodec_free_context(ptr); } seekCallback = null; readPacketCallback = null; videoStream.Dispose(); videoStream = null; if (swsContext != null) ffmpeg.sws_freeContext(swsContext); while (decodedFrames.TryDequeue(out var f)) { ((VideoTexture)f.Texture.TextureGL).FlushUploads(); f.Texture.Dispose(); } while (availableTextures.TryDequeue(out var t)) t.Dispose(); while (hwTransferFrames.TryDequeue(out var hwF)) hwF.Dispose(); while (scalerFrames.TryDequeue(out var sf)) sf.Dispose(); handle.Dispose(); }); } #endregion /// <summary> /// Represents the possible states the decoder can be in. /// </summary> public enum DecoderState { /// <summary> /// The decoder is ready to begin decoding. This is the default state before the decoder starts operations. /// </summary> Ready = 0, /// <summary> /// The decoder is currently running and decoding frames. /// </summary> Running = 1, /// <summary> /// The decoder has faulted with an exception. /// </summary> Faulted = 2, /// <summary> /// The decoder has reached the end of the video data. /// </summary> EndOfStream = 3, /// <summary> /// The decoder has been completely stopped and cannot be resumed. /// </summary> Stopped = 4, } } }
//----------------------------------------------------------------------- // <copyright file="ActorSubscriberSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Akka.Actor; using Akka.Configuration; using Akka.Routing; using Akka.Streams.Actors; using Akka.Streams.Dsl; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using Akka.Util.Internal; using FluentAssertions; using Reactive.Streams; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Actor { public class ActorSubscriberSpec : AkkaSpec { public ActorSubscriberSpec(ITestOutputHelper helper) : base( AkkaSpecConfig.WithFallback( ConfigurationFactory.FromResource<ScriptedTest>("Akka.Streams.TestKit.Tests.reference.conf")), helper) { } [Fact] public void ActorSubscriber_should_receive_requested_elements() { var actorRef = Source.From(new[] { 1, 2, 3 }) .RunWith(Sink.ActorSubscriber<int>(ManualSubscriber.Props(TestActor)), Sys.Materializer()); ExpectNoMsg(200); actorRef.Tell("ready"); //requesting 2 ExpectMsg<OnNext>().Element.Should().Be(1); ExpectMsg<OnNext>().Element.Should().Be(2); ExpectNoMsg(200); actorRef.Tell("ready"); ExpectMsg<OnNext>().Element.Should().Be(3); ExpectMsg<OnComplete>(); } [Fact] public void ActorSubscriber_should_signal_error() { var e = new Exception("simulated"); var actorRef = Source.FromEnumerator<int>(() => { throw e; }) .RunWith(Sink.ActorSubscriber<int>(ManualSubscriber.Props(TestActor)), Sys.Materializer()); actorRef.Tell("ready"); ExpectMsg<OnError>().Cause.Should().Be(e); } [Fact] public void ActorSubscriberSpec_should_remember_requested_after_restart() { // creating actor with default supervision, because stream supervisor default strategy is to var actorRef = Sys.ActorOf(ManualSubscriber.Props(TestActor)); Source.From(Enumerable.Range(1, 7)) .RunWith(Sink.FromSubscriber(new ActorSubscriberImpl<int>(actorRef)), Sys.Materializer()); actorRef.Tell("ready"); ExpectMsg<OnNext>().Element.Should().Be(1); ExpectMsg<OnNext>().Element.Should().Be(2); ExpectNoMsg(200); actorRef.Tell("boom"); actorRef.Tell("ready"); actorRef.Tell("ready"); actorRef.Tell("boom"); Enumerable.Range(3, 4).ForEach(n => ExpectMsg<OnNext>().Element.Should().Be(n)); ExpectNoMsg(200); actorRef.Tell("ready"); ExpectMsg<OnNext>().Element.Should().Be(7); ExpectMsg<OnComplete>(); } [Fact] public void ActorSubscriberSpec_should_not_deliver_more_after_cancel() { var actorRef = Source.From(Enumerable.Range(1, 5)) .RunWith(Sink.ActorSubscriber<int>(ManualSubscriber.Props(TestActor)), Sys.Materializer()); actorRef.Tell("ready"); ExpectMsg<OnNext>().Element.Should().Be(1); ExpectMsg<OnNext>().Element.Should().Be(2); actorRef.Tell("requestAndCancel"); ExpectNoMsg(200); } [Fact] public void ActorSubscriberSpec_should_terminate_after_cancel() { var actorRef = Source.From(Enumerable.Range(1, 5)) .RunWith(Sink.ActorSubscriber<int>(ManualSubscriber.Props(TestActor)), Sys.Materializer()); Watch(actorRef); actorRef.Tell("requestAndCancel"); ExpectTerminated(actorRef, TimeSpan.FromMilliseconds(200)); } [Fact] public void ActorSubscriberSpec_should_cancel_incoming_subscription_when_cancel_was_called_before_it_arrived() { var actorRef = Sys.ActorOf(ImmediatelyCancelledSubscriber.Props(TestActor)); var sub = new ActorSubscriberImpl<object>(actorRef); Watch(actorRef); ExpectNoMsg(200); sub.OnSubscribe(new CancelSubscription(TestActor)); ExpectMsg("cancel"); ExpectTerminated(actorRef, TimeSpan.FromMilliseconds(200)); } [Fact] public void ActorSubscriberSpec_should_work_with_OneByOneRequestStrategy() { Source.From(Enumerable.Range(1, 17)) .RunWith(Sink.ActorSubscriber<int>(RequestStrategySubscriber.Props(TestActor, OneByOneRequestStrategy.Instance)), Sys.Materializer()); Enumerable.Range(1, 17).ForEach(n => ExpectMsg<OnNext>().Element.Should().Be(n)); ExpectMsg<OnComplete>(); } [Fact] public void ActorSubscriberSpec_should_should_work_with_WatermarkRequestStrategy() { Source.From(Enumerable.Range(1, 17)) .RunWith(Sink.ActorSubscriber<int>(RequestStrategySubscriber.Props(TestActor, new WatermarkRequestStrategy(highWatermark: 10))), Sys.Materializer()); Enumerable.Range(1, 17).ForEach(n => ExpectMsg<OnNext>().Element.Should().Be(n)); ExpectMsg<OnComplete>(); } [Fact] public void ActorSubscriberSpec_should_support_custom_max_in_flight_request_strategy_with_child_workers() { var n = 117; Source.From(Enumerable.Range(1, n)) .Select(i => new Msg(i, TestActor)) .RunWith(Sink.ActorSubscriber<Msg>(Streamer.Props), Sys.Materializer()); ReceiveN(n).ShouldAllBeEquivalentTo(Enumerable.Range(1, n).Select(i => new Done(i))); } } internal class ManualSubscriber : ActorSubscriber { public static Props Props(IActorRef probe) => Akka.Actor.Props.Create(() => new ManualSubscriber(probe)).WithDispatcher("akka.test.stream-dispatcher"); private readonly IActorRef _probe; public ManualSubscriber(IActorRef probe) { _probe = probe; } public override IRequestStrategy RequestStrategy { get; } = ZeroRequestStrategy.Instance; protected override bool Receive(object message) { return message.Match() .With<OnNext>(_probe.Tell) .With<OnComplete>(_probe.Tell) .With<OnError>(_probe.Tell) .With<string>(s => { if (s.Equals("ready")) Request(2); else if (s.Equals("boom")) throw new Exception(s); else if (s.Equals("requestAndCancel")) { Request(1); Cancel(); } else if (s.Equals("cancel")) Cancel(); }) .WasHandled; } } internal class ImmediatelyCancelledSubscriber : ManualSubscriber { public new static Props Props(IActorRef probe) => Akka.Actor.Props.Create(() => new ImmediatelyCancelledSubscriber(probe)).WithDispatcher("akka.test.stream-dispatcher"); public ImmediatelyCancelledSubscriber(IActorRef probe) : base(probe) { } protected override void PreStart() { Cancel(); base.PreStart(); } } internal class RequestStrategySubscriber : ActorSubscriber { public static Props Props(IActorRef probe, IRequestStrategy strat) => Akka.Actor.Props.Create(() => new RequestStrategySubscriber(probe, strat)).WithDispatcher("akka.test.stream-dispatcher"); private readonly IActorRef _probe; public RequestStrategySubscriber(IActorRef probe, IRequestStrategy strat) { _probe = probe; RequestStrategy = strat; } protected override bool Receive(object message) { return message.Match() .With<OnNext>(_probe.Tell) .With<OnComplete>(_probe.Tell) .WasHandled; } public override IRequestStrategy RequestStrategy { get; } } internal class CancelSubscription : ISubscription { private readonly IActorRef _probe; public CancelSubscription(IActorRef probe) { _probe = probe; } public void Request(long n) { } public void Cancel() { _probe.Tell("cancel"); } } internal abstract class IdBase { protected IdBase(int id) { Id = id; } public int Id { get; } } internal class Msg : IdBase { public Msg(int id, IActorRef replyTo) : base(id) { ReplyTo = replyTo; } public IActorRef ReplyTo { get; } } internal class Work : IdBase { public Work(int id) : base(id) { } } internal class Reply : IdBase { public Reply(int id) : base(id) { } } internal class Done : IdBase { public Done(int id) : base(id) { } } internal class Streamer : ActorSubscriber { public static Props Props { get; } = Props.Create<Streamer>().WithDispatcher("akka.test.stream-dispatcher"); private class InFlightStrategy : MaxInFlightRequestStrategy { private readonly Streamer _streamer; public InFlightStrategy(Streamer streamer) : base(10) { _streamer = streamer; } public override int InFlight => _streamer._queue.Count; } private readonly Dictionary<int, IActorRef> _queue = new Dictionary<int, IActorRef>(); private readonly Router _router; public Streamer() { RequestStrategy = new InFlightStrategy(this); var routees = new[] { Routee.FromActorRef(Context.ActorOf(Props.Create<Worker>().WithDispatcher(Context.Props.Dispatcher))), Routee.FromActorRef(Context.ActorOf(Props.Create<Worker>().WithDispatcher(Context.Props.Dispatcher))), Routee.FromActorRef(Context.ActorOf(Props.Create<Worker>().WithDispatcher(Context.Props.Dispatcher))) }; _router = new Router(new RoundRobinRoutingLogic(), routees); } public override IRequestStrategy RequestStrategy { get; } protected override bool Receive(object message) { return message.Match() .With<OnNext>(next => { var msg = (Msg)next.Element; _queue.Add(msg.Id, msg.ReplyTo); if (_queue.Count > 10) throw new InvalidOperationException($"queued too many: {_queue.Count}"); _router.Route(new Work(msg.Id), Self); }) .With<Reply>(reply => { _queue[reply.Id].Tell(new Done(reply.Id)); _queue.Remove(reply.Id); }) .WasHandled; } } internal class Worker : ReceiveActor { public Worker() { Receive<Work>(work => Sender.Tell(new Reply(work.Id))); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv4 { using System; using System.Runtime.InteropServices; using Microsoft.Zelig.TargetModel.ArmProcessor; using TS = Microsoft.Zelig.Runtime.TypeSystem; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; public abstract partial class ProcessorARMv4 : Processor { protected static EncDef s_Encoding = (EncodingDefinition_ARM)CurrentInstructionSetEncoding.GetEncoding(); //--// public abstract new class Context : Processor.Context { // // WARNING: Don't assume the actual layout of the structure is sequential!!! // WARNING: The code generator rearranges the fields to minimize the cost of a context switch!!! // [TS.WellKnownType( "Microsoft_Zelig_ProcessorARMv4_RegistersOnStack" )] [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct RegistersOnStack { public const uint StackRegister = EncDef.c_register_sp; public const uint LinkRegister = EncDef.c_register_lr; public const uint ProgramCounterRegister = EncDef.c_register_pc; // // State // [TS.AssumeReferenced] public uint CPSR; [TS.AssumeReferenced] public UIntPtr SP; [TS.AssumeReferenced] public UIntPtr LR; [TS.AssumeReferenced] public UIntPtr R0; [TS.AssumeReferenced] public UIntPtr R1; [TS.AssumeReferenced] public UIntPtr R2; [TS.AssumeReferenced] public UIntPtr R3; [TS.AssumeReferenced] public UIntPtr R4; [TS.AssumeReferenced] public UIntPtr R5; [TS.AssumeReferenced] public UIntPtr R6; [TS.AssumeReferenced] public UIntPtr R7; [TS.AssumeReferenced] public UIntPtr R8; [TS.AssumeReferenced] public UIntPtr R9; [TS.AssumeReferenced] public UIntPtr R10; [TS.AssumeReferenced] public UIntPtr R11; [TS.AssumeReferenced] public UIntPtr R12; [TS.AssumeReferenced] public UIntPtr PC; // // Helper Methods // internal unsafe UIntPtr* GetRegisterPointer( uint idx ) { switch(idx) { case 0: fixed(UIntPtr* ptr = &this.R0 ) { return ptr; }; case 1: fixed(UIntPtr* ptr = &this.R1 ) { return ptr; }; case 2: fixed(UIntPtr* ptr = &this.R2 ) { return ptr; }; case 3: fixed(UIntPtr* ptr = &this.R3 ) { return ptr; }; case 4: fixed(UIntPtr* ptr = &this.R4 ) { return ptr; }; case 5: fixed(UIntPtr* ptr = &this.R5 ) { return ptr; }; case 6: fixed(UIntPtr* ptr = &this.R6 ) { return ptr; }; case 7: fixed(UIntPtr* ptr = &this.R7 ) { return ptr; }; case 8: fixed(UIntPtr* ptr = &this.R8 ) { return ptr; }; case 9: fixed(UIntPtr* ptr = &this.R9 ) { return ptr; }; case 10: fixed(UIntPtr* ptr = &this.R10) { return ptr; }; case 11: fixed(UIntPtr* ptr = &this.R11) { return ptr; }; case 12: fixed(UIntPtr* ptr = &this.R12) { return ptr; }; case 13: fixed(UIntPtr* ptr = &this.SP ) { return ptr; }; case 14: fixed(UIntPtr* ptr = &this.LR ) { return ptr; }; case 15: fixed(UIntPtr* ptr = &this.PC ) { return ptr; }; } return null; } public void Assign( ref RegistersOnStack other ) { //// fixed(RegistersOnStack* dst = &this) //// { //// fixed(RegistersOnStack* src = &other) //// { //// UIntPtr dstStart = new UIntPtr( dst ); //// UIntPtr srcStart = new UIntPtr( src ); //// UIntPtr srcEnd = AddressMath.Increment( srcStart, (uint)Marshal.SizeOf( typeof(RegistersOnStack) ) ); //// //// Memory.CopyNonOverlapping( srcStart, srcEnd, dstStart ); //// } //// } this.R0 = other.R0; this.R1 = other.R1; this.R2 = other.R2; this.R3 = other.R3; this.R4 = other.R4; this.R5 = other.R5; this.R6 = other.R6; this.R7 = other.R7; this.R8 = other.R8; this.R9 = other.R9; this.R10 = other.R10; this.R11 = other.R11; this.R12 = other.R12; this.SP = other.SP; this.LR = other.LR; this.PC = other.PC; this.CPSR = other.CPSR; } } // // State // const uint c_STMFD_Mask = 0xFFFF0000; const uint c_STMFD_Opcode = 0xE92D0000; const uint c_SUBSP_Mask = 0xFFFFF000; const uint c_SUBSP_Opcode = 0xE24DD000; //--// const uint c_LDMFD_Mask = 0xFFFF0000; const uint c_LDMFD_Opcode = 0xE8BD0000; //--// public RegistersOnStack Registers; // // Constructor Methods // public Context() { } // // Helper Methods // [NoInline] public override void Populate() { GetAllTheRegisters(); // // Now we have all the registers at this method boundary, unwind one more time and we have the state at the caller's site. // Unwind(); } [NoInline] public override void Populate( Processor.Context context ) { Context ctx = (Context)context; this.Registers.Assign( ref ctx.Registers ); } [NoInline] public unsafe override void PopulateFromDelegate( Delegate dlg , uint[] stack ) { DelegateImpl dlgImpl = (DelegateImpl)(object)dlg; ArrayImpl stackImpl = (ArrayImpl )(object)stack; ObjectImpl objImpl = (ObjectImpl )(object)dlg.Target; this.Registers.CPSR = c_psr_mode_SYS; this.Registers.PC = new UIntPtr( dlgImpl.InnerGetCodePointer().Target.ToPointer() ); this.Registers.SP = new UIntPtr( stackImpl.GetEndDataPointer() ); if(objImpl != null) { this.Registers.R0 = new UIntPtr( objImpl.Unpack() ); } } [NoInline] public override void SetupForExceptionHandling( uint mode ) { using(Runtime.SmartHandles.InterruptState.DisableAll()) { UIntPtr stack = this.Registers.SP; uint oldMode = GetStatusRegister(); // // Enter target mode, with interrupts disabled. // SetStatusRegister( c_psr_field_c, c_psr_I | c_psr_F | mode ); SetRegister( Context.RegistersOnStack.StackRegister, stack ); // // Switch back to original mode. // SetStatusRegister( c_psr_field_c, oldMode ); } } [NoInline] public unsafe override bool Unwind() { UIntPtr pc = this.ProgramCounter; TS.CodeMap cm = TS.CodeMap.ResolveAddressToCodeMap( pc ); this.InPrologue = false; this.InEpilogue = false; if(cm != null) { for(int i = 0; i < cm.Ranges.Length; i++) { TS.CodeMap.Range rng = cm.Ranges[i]; if((rng.Flags & TS.CodeMap.Flags.EntryPoint) != 0) { if((rng.Flags & TS.CodeMap.Flags.BottomOfCallStack) != 0) { return false; } UIntPtr sp = this.StackPointer; UIntPtr address = rng.Start; uint regRestoreMap = 0; uint stackAdjustment = 0; bool fReturnAddressinLR = false; bool fDone = false; if(pc == address) { // // We are at the beginning of a method, the return address is in LR for sure. // fReturnAddressinLR = true; // // The PC has not executed the next prologue instruction, stop processing. // fDone = true; this.InPrologue = true; } if(fDone == false) { if((rng.Flags & TS.CodeMap.Flags.HasIntRegisterSave) != 0) { uint* ptr = (uint*)address.ToPointer(); uint opcode_STMFD = DebuggerAwareRead( ptr++ ); address = new UIntPtr( ptr ); if((opcode_STMFD & c_STMFD_Mask) == c_STMFD_Opcode) { regRestoreMap = opcode_STMFD & 0xFFFF; } else { //CHECKS.ASSERT( false, "Expecting a STMFD opcode, got 0x{0:X8}", opcode_STMFD ); return false; } } else { // // No register push, the return address is in LR for sure. // fReturnAddressinLR = true; } } if(pc == address) { // // The PC has not executed the next prologue instruction, stop processing. // fDone = true; this.InPrologue = true; } if(fDone == false) { if((rng.Flags & TS.CodeMap.Flags.HasStackAdjustment) != 0) { uint* ptr = (uint*)address.ToPointer(); uint opcode_SUBSP = DebuggerAwareRead( ptr ); if((opcode_SUBSP & c_SUBSP_Mask) == c_SUBSP_Opcode) { stackAdjustment = s_Encoding.get_DataProcessing_ImmediateValue( opcode_SUBSP ); } else { //CHECKS.ASSERT( false, "Expecting a STMFD opcode, got 0x{0:X8}", opcode_SUBSP ); return false; } } } //--// // // Deal with method epilogue: if we are on one of the return instructions, we need to restore less state. // uint opcode = *(uint*)pc.ToPointer(); if((opcode & c_LDMFD_Mask) == c_LDMFD_Opcode) { stackAdjustment = 0; } //--// sp = AddressMath.Increment( sp, stackAdjustment ); if(fReturnAddressinLR) { this.Registers.PC = this.Registers.LR; } else { UIntPtr* src = (UIntPtr*)sp.ToPointer(); for(uint idx = 0; idx < 16; idx++) { if((regRestoreMap & (1u << (int)idx)) != 0) { // // Prologue saves LR, but we need to restore it as PC. // uint regIdx = (idx == RegistersOnStack.LinkRegister) ? RegistersOnStack.ProgramCounterRegister : idx; UIntPtr* dst = this.Registers.GetRegisterPointer( regIdx ); *dst = *src++; } } sp = new UIntPtr( src ); } this.StackPointer = sp; return true; } } } return false; } [NoInline] public override void SwitchTo() { LongJump( ref this.Registers ); } public override unsafe UIntPtr GetRegisterByIndex( uint idx ) { return *(this.Registers.GetRegisterPointer( idx )); } public override unsafe void SetRegisterByIndex( uint idx , UIntPtr value ) { *(this.Registers.GetRegisterPointer( idx )) = value; } //--// [NoInline] [SaveFullProcessorContext] private unsafe void GetAllTheRegisters() { this.Registers.SP = GetRegister( RegistersOnStack.StackRegister ); this.Registers.PC = GetRegister( RegistersOnStack.ProgramCounterRegister ); Unwind(); } //--// [NoInline] [NoReturn()] [HardwareExceptionHandler(HardwareException.LongJump)] static void LongJump( ref RegistersOnStack registers ) { // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // // We need a way to make a long jump as part of the exception handling code. // // The code responsible for emitting the prologue of the method will detect that // this method is decorated with the ContextSwitch flag and it will generate the proper code. // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // } //--// [Inline] public static void InterruptHandlerWithContextSwitch( ref RegistersOnStack registers ) { Peripherals.Instance.ProcessInterrupt(); ThreadManager tm = ThreadManager.Instance; // // We keep looping until the current and next threads are the same, // because when swapping out a dead thread, we might wake up a different thread. // while(tm.ShouldContextSwitch) { ContextSwitch( tm, ref registers ); } } [Inline] public static void InterruptHandlerWithoutContextSwitch() { Peripherals.Instance.ProcessInterrupt(); } [Inline] public static void FastInterruptHandlerWithoutContextSwitch() { Peripherals.Instance.ProcessFastInterrupt(); } [Inline] public static void GenericSoftwareInterruptHandler( ref RegistersOnStack registers ) { } //--// private static void ContextSwitch( ThreadManager tm , ref RegistersOnStack registers ) { ThreadImpl currentThread = tm.CurrentThread; ThreadImpl nextThread = tm.NextThread; Context ctx; if(currentThread != null) { ctx = (Context)currentThread.SwappedOutContext; ctx.Registers.Assign( ref registers ); } ctx = (Context)nextThread.SwappedOutContext; registers.Assign( ref ctx.Registers ); tm.CurrentThread = nextThread; ThreadImpl.CurrentThread = nextThread; } // // Access Methods // public override UIntPtr StackPointer { get { return this.Registers.SP; } set { this.Registers.SP = value; } } public override UIntPtr ProgramCounter { get { return this.Registers.PC; } set { this.Registers.PC = value; } } public override uint ScratchedIntegerRegisters { get { return MethodWrapperHelpers.ScratchedRegisters(); } } } } }
// 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\General\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; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithLowerAndUpperInt64() { var test = new VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperInt64(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperInt64 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Int64[] values = new Int64[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt64(); } Vector256<Int64> value = Vector256.Create(values[0], values[1], values[2], values[3]); Vector128<Int64> lowerResult = value.GetLower(); Vector128<Int64> upperResult = value.GetUpper(); ValidateGetResult(lowerResult, upperResult, values); Vector256<Int64> result = value.WithLower(upperResult); result = result.WithUpper(lowerResult); ValidateWithResult(result, values); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Int64[] values = new Int64[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt64(); } Vector256<Int64> value = Vector256.Create(values[0], values[1], values[2], values[3]); object lowerResult = typeof(Vector256) .GetMethod(nameof(Vector256.GetLower)) .MakeGenericMethod(typeof(Int64)) .Invoke(null, new object[] { value }); object upperResult = typeof(Vector256) .GetMethod(nameof(Vector256.GetUpper)) .MakeGenericMethod(typeof(Int64)) .Invoke(null, new object[] { value }); ValidateGetResult((Vector128<Int64>)(lowerResult), (Vector128<Int64>)(upperResult), values); object result = typeof(Vector256) .GetMethod(nameof(Vector256.WithLower)) .MakeGenericMethod(typeof(Int64)) .Invoke(null, new object[] { value, upperResult }); result = typeof(Vector256) .GetMethod(nameof(Vector256.WithUpper)) .MakeGenericMethod(typeof(Int64)) .Invoke(null, new object[] { result, lowerResult }); ValidateWithResult((Vector256<Int64>)(result), values); } private void ValidateGetResult(Vector128<Int64> lowerResult, Vector128<Int64> upperResult, Int64[] values, [CallerMemberName] string method = "") { Int64[] lowerElements = new Int64[ElementCount / 2]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref lowerElements[0]), lowerResult); Int64[] upperElements = new Int64[ElementCount / 2]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref upperElements[0]), upperResult); ValidateGetResult(lowerElements, upperElements, values, method); } private void ValidateGetResult(Int64[] lowerResult, Int64[] upperResult, Int64[] values, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount / 2; i++) { if (lowerResult[i] != values[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Int64>.GetLower(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", lowerResult)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = true; for (int i = ElementCount / 2; i < ElementCount; i++) { if (upperResult[i - (ElementCount / 2)] != values[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Int64>.GetUpper(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", upperResult)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } private void ValidateWithResult(Vector256<Int64> result, Int64[] values, [CallerMemberName] string method = "") { Int64[] resultElements = new Int64[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, method); } private void ValidateWithResult(Int64[] result, Int64[] values, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount / 2; i++) { if (result[i] != values[i + (ElementCount / 2)]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Int64.WithLower(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = true; for (int i = ElementCount / 2; i < ElementCount; i++) { if (result[i] != values[i - (ElementCount / 2)]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Int64.WithUpper(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
#region Copyright (c) 2009 S. van Deursen /* The CuttingEdge.Conditions library enables developers to validate pre- and postconditions in a fluent * manner. * * To contact me, please visit my blog at http://www.cuttingedge.it/blogs/steven/ * * Copyright (c) 2009 S. van Deursen * * 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; using System.Collections.Generic; namespace CuttingEdge.Conditions { /// <summary> /// Helper methods for the Collection validation methods of the <see cref="ValidatorExtensions"/> methods. /// </summary> internal static class CollectionHelpers { internal static bool Contains<T>(IEnumerable<T> sequence, T value) { // NOTE that we don't try to cast sequence to an ICollection<T> and call it's Contains method, // because it is possible that source uses a non-default implementation of equality. Consequence // of this is that we always have to iterate the sequence, with a cost of O(n). // See work item 10480 on CodePlex for more info: // http://conditions.codeplex.com/WorkItem/View.aspx?WorkItemId=10480. IEqualityComparer<T> comparer = EqualityComparer<T>.Default; foreach (T local in sequence) { if (comparer.Equals(local, value)) { return true; } } return false; } internal static bool Contains(IEnumerable sequence, object value) { // NOTE that we don't try to cast sequence to an IList and call it's Contains method, because it // is possible that sequence uses a non-default implementation of equality. Consequence of this is // that we always have to iterate the sequence, with a cost of O(n). // See work item 10480 on CodePlex for more info: // http://conditions.codeplex.com/WorkItem/View.aspx?WorkItemId=10480. Comparer<object> comparer = Comparer<object>.Default; foreach (object element in sequence) { if (comparer.Compare(element, value) == 0) { return true; } } return false; } // TODO: Optimize this method for performance. // While creating a O(1) set of the sequence, might reduce the cost of this call to O(m) (where m: // the number of elements in 'values'), copying the sequence might cost a lot, and a different // implementation might improve overall performance. internal static bool ContainsAny<T>(IEnumerable<T> sequence, IEnumerable<T> values) { // When the values list is empty we can say that there is none of them in the collection. if (IsSequenceNullOrEmpty(values)) { return false; } // When the collection is empty there can not be a single value in that collection. if (IsSequenceNullOrEmpty(sequence)) { return false; } // NOTE that we don't try to cast sequence to an ICollection<T> and call it's Contains method, // because it is possible that source uses a non-default implementation of equality. Consequence // of this is that we always have to iterate the sequence, with a cost of O(n). // See work item 10480 on CodePlex for more info: // http://conditions.codeplex.com/WorkItem/View.aspx?WorkItemId=10480. // To prevent a cost of O(n*m) we copy the sequence into a set (copy cost: O(n), using set: O(1)). // Which gives a total cost of: O(n) + O(2m). Note that copying sequence is equal to iterating it. bool sequenceContainsNull; var set = ConvertToSet<T>(sequence, out sequenceContainsNull); // Determine whether sequence contains one of the values. foreach (T element in values) { if (element == null) { if (sequenceContainsNull) { return true; } } else { if (set.ContainsKey(element)) { return true; } } } return false; } // TODO: Optimize this method for performance. // While creating a O(1) set of the sequence, might reduce the cost of this call to O(m) (where m: // the number of elements in 'values'), copying the sequence might cost a lot, and a different // implementation might improve overall performance. internal static bool ContainsAny(IEnumerable sequence, IEnumerable values) { // When the values list is empty we can say that there is none of them in the collection. if (IsSequenceNullOrEmpty(values)) { return false; } // When the sequence is empty there can not be a single value in that collection. if (IsSequenceNullOrEmpty(sequence)) { return false; } // NOTE that we don't try to cast sequence to an IList and call it's Contains method, because it // is possible that source uses a non-default implementation of equality. Consequence of this is // that we always have to iterate the sequence, with a cost of O(n). // See work item 10480 on CodePlex for more info: // http://conditions.codeplex.com/WorkItem/View.aspx?WorkItemId=10480. // To prevent a cost of O(n*m) we copy the sequence into a set (copy cost: O(n), using set: O(1)). // Which gives a total cost of: O(n) + O(2m). Note that copying sequence is equal to iterating it. bool sequenceContainsNull; var set = ConvertToSet(sequence, out sequenceContainsNull); // Determine whether sequence contains one of the values. foreach (object element in values) { if (element == null) { if (sequenceContainsNull) { return true; } } else { if (set.ContainsKey(element)) { return true; } } } return false; } // TODO: Optimize this method for performance. // While creating a O(1) set of the sequence, might reduce the cost of this call to O(m) (where m: // the number of elements in 'values'), copying the sequence might cost a lot, and a different // implementation might improve overall performance. internal static bool ContainsAll<T>(IEnumerable<T> sequence, IEnumerable<T> values) { // When the values list is empty we consider all of them to be in the collection (even if the // collection itself is also empty). if (IsSequenceNullOrEmpty(values)) { return true; } // When the values list isn't empty, but the collection is, then there must be at least one value // that is not in the collection. if (IsSequenceNullOrEmpty(sequence)) { return false; } // NOTE that we don't try to cast sequence to an ICollection<T> and call it's Contains method, // because it is possible that source uses a non-default implementation of equality. Consequence // of this is that we always have to iterate the sequence, with a cost of O(n). // See work item 10480 on CodePlex for more info: // http://conditions.codeplex.com/WorkItem/View.aspx?WorkItemId=10480. // To prevent a cost of O(n*m) we copy the sequence into a set (copy cost: O(n), using set: O(1)). // Which gives a total cost of: O(n) + O(2m). Note that copying sequence is equal to iterating it. bool sequenceContainsNull; var set = ConvertToSet<T>(sequence, out sequenceContainsNull); // Determine whether sequence contains one of the values. foreach (T element in values) { if (element == null) { if (!sequenceContainsNull) { return false; } } else { if (!set.ContainsKey(element)) { return false; } } } return true; } // TODO: Optimize this method for performance. // While creating a O(1) set of the sequence, might reduce the cost of this call to O(m) (where m: // the number of elements in 'values'), copying the sequence might cost a lot, and a different // implementation might improve overall performance. internal static bool ContainsAll(IEnumerable sequence, IEnumerable values) { // When the values list is empty we consider all of them to be in the collection (even if the // collection itself is also empty). if (IsSequenceNullOrEmpty(values)) { return true; } // When the values list isn't empty, but the collection is, then there must be at least one value // that is not in the collection. if (IsSequenceNullOrEmpty(sequence)) { return false; } // NOTE that we don't try to cast sequence to an IList and call it's Contains method, because it // is possible that source uses a non-default implementation of equality. Consequence of this is // that we always have to iterate the sequence, with a cost of O(n). // See work item 10480 on CodePlex for more info: // http://conditions.codeplex.com/WorkItem/View.aspx?WorkItemId=10480. // To prevent a cost of O(n*m) we copy the sequence into a set (copy cost: O(n), using set: O(1)). // Which gives a total cost of: O(n) + O(2m). Note that copying sequence is equal to iterating it. bool sequenceContainsNull; var set = ConvertToSet(sequence, out sequenceContainsNull); foreach (object element in values) { if (element == null) { if (!sequenceContainsNull) { return false; } } else { if (!set.ContainsKey(element)) { return false; } } } return true; } internal static bool SequenceHasLength(IEnumerable sequence, int numberOfElements) { // When the given enumerable is a null reference, we can do a fast check for numberOfElements == 0, // because we consider a null reference to have zero elements. if (sequence == null) { return 0 == numberOfElements; } // When the given enumerable is an ICollection, we can do a simple interface call. ICollection collection = sequence as ICollection; if (collection != null) { return collection.Count == numberOfElements; } // When we get at this point, we'll have to iterate over the enumerable to find out the size. IEnumerator enumerator = sequence.GetEnumerator(); try { int lengthOfSequence = 0; // Optimization: We use the while statement instead of foreach, because we don't need a value, // we don't have to call enumerator.Current. foreach Calls Current always and this could lead // to boxing of elements when the enumerator is a IEnumerator<T> and T is a struct. while (enumerator.MoveNext()) { lengthOfSequence++; // Optimization: We can return immediately when we notice that the sequence is bigger. if (lengthOfSequence > numberOfElements) { return false; } } return lengthOfSequence == numberOfElements; } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } } internal static bool IsSequenceNullOrEmpty<TSource>(IEnumerable<TSource> sequence) { if (sequence == null) { return true; } ICollection<TSource> collection = sequence as ICollection<TSource>; if (collection != null) { // We expect this to be the normal flow. return collection.Count == 0; } else { // We expect this to be the exceptional flow, because most collections implement // ICollection<T>. return IsSequenceNullOrEmpty((IEnumerable)sequence); } } internal static bool IsSequenceNullOrEmpty(IEnumerable sequence) { if (sequence == null) { return true; } ICollection collection = sequence as ICollection; if (collection != null) { // We expect this to be the normal flow. return collection.Count == 0; } else { // We expect this to be the exceptional flow, because most collections implement ICollection. return IsEnumerableEmpty(sequence); } } internal static bool SequenceIsShorterThan(IEnumerable sequence, int numberOfElements) { // When the given enumerable is a null reference, we can do a fast check for numberOfElements > 0, // because we consider a null reference to have zero elements. if (sequence == null) { return 0 < numberOfElements; } // When the given enumerable is an ICollection, we can do a simple interface call. ICollection collection = sequence as ICollection; if (collection != null) { return collection.Count < numberOfElements; } // When we get at this point, we'll have to iterate over the enumerable to find out the size. IEnumerator enumerator = sequence.GetEnumerator(); try { int lengthOfSequence = 0; // Optimization: We use the while statement instead of foreach, because we don't need a value, // we don't have to call enumerator.Current. foreach Calls Current always and this could lead // to boxing of elements when the enumerator is a IEnumerator<T> and T is a struct. while (enumerator.MoveNext()) { lengthOfSequence++; // Optimization: We can return immediately when we see that the sequence is not smaller. if (lengthOfSequence >= numberOfElements) { return false; } } return lengthOfSequence < numberOfElements; } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } } internal static bool SequenceIsShorterOrEqual(IEnumerable sequence, int numberOfElements) { // When the given enumerable is a null reference, we can do a fast check for 0 <= numberOfElements, // because we consider a null reference to have zero elements. if (sequence == null) { return 0 <= numberOfElements; } // When the given enumerable is an ICollection, we can do a simple interface call. ICollection collection = sequence as ICollection; if (collection != null) { return collection.Count <= numberOfElements; } // When we get at this point, we'll have to iterate over the enumerable to find out the size. IEnumerator enumerator = sequence.GetEnumerator(); try { int lengthOfSequence = 0; // Optimization: We use the while statement instead of foreach, because we don't need a value, // we don't have to call enumerator.Current. foreach Calls Current always and this could lead // to boxing of elements when the enumerator is a IEnumerator<T> and T is a struct. while (enumerator.MoveNext()) { lengthOfSequence++; // Optimization: We can return immediately when we see that the sequence is bigger. if (lengthOfSequence > numberOfElements) { return false; } } return lengthOfSequence <= numberOfElements; } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } } internal static bool SequenceIsLongerThan(IEnumerable sequence, int numberOfElements) { // When the given enumerable is a null reference, we can do a fast check for numberOfElements < 0, // because we consider a null reference to have zero elements. if (sequence == null) { return 0 > numberOfElements; } // When the given enumerable is an ICollection, we can do a simple interface call. ICollection collection = sequence as ICollection; if (collection != null) { return collection.Count > numberOfElements; } // When we get at this point, we'll have to iterate over the enumerable to find out the size. IEnumerator enumerator = sequence.GetEnumerator(); try { int lengthOfSequence = 0; // Optimization: We use the while statement instead of foreach, because we don't need a value, // we don't have to call enumerator.Current. foreach Calls Current always and this could lead // to boxing of elements when the enumerator is a IEnumerator<T> and T is a struct. while (enumerator.MoveNext()) { lengthOfSequence++; // Optimization: We can return immediately when we see that the sequence is bigger. if (lengthOfSequence > numberOfElements) { return true; } } return lengthOfSequence > numberOfElements; } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } } internal static bool SequenceIsLongerOrEqual(IEnumerable sequence, int numberOfElements) { // When the given enumerable is a null reference, we can do a fast check for 0 <= numberOfElements, // because we consider a null reference to have zero elements. if (sequence == null) { return 0 >= numberOfElements; } // When the given enumerable is an ICollection, we can do a simple interface call. ICollection collection = sequence as ICollection; if (collection != null) { return collection.Count >= numberOfElements; } // When we get at this point, we'll have to iterate over the enumerable to find out the size. IEnumerator enumerator = sequence.GetEnumerator(); try { int lengthOfSequence = 0; // Optimization: We use the while statement instead of foreach, because we don't need a value, // we don't have to call enumerator.Current. foreach Calls Current always and this could lead // to boxing of elements when the enumerator is a IEnumerator<T> and T is a struct. while (enumerator.MoveNext()) { lengthOfSequence++; // Optimization: We can return immediately when we see that the sequence is bigger. if (lengthOfSequence >= numberOfElements) { return true; } } return lengthOfSequence >= numberOfElements; } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } } // Returns the number of elements in the sequence. internal static int GetLength(IEnumerable sequence) { // When the given enumerable is an ICollection, we can do a simple interface call to determine // it's size. ICollection collection = sequence as ICollection; if (collection != null) { return collection.Count; } // When we get at this point, we'll have to iterate over the enumerable to find out the size. IEnumerator enumerator = sequence.GetEnumerator(); try { int count = 0; while (enumerator.MoveNext()) { count++; } return count; } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } } private static bool IsEnumerableEmpty(IEnumerable sequence) { IEnumerator enumerator = sequence.GetEnumerator(); try { return !enumerator.MoveNext(); } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } } private static Dictionary<T, byte> ConvertToSet<T>(IEnumerable<T> sequence, out bool sequenceContainsNull) { // A dictionary can have null as one of it's keys, therefore we have to communicate whether the // sequence contains null. (HashSet<T> does have this ability). sequenceContainsNull = false; int capacity = DetermineInitialCapacity<T>(sequence); // A Dictionary is used to improve performance. Using 'Contains' on a collection would give a // performance characteristic of O(n*m) and with a Dictionary it's of O(m). // Using HashSet<T> is slightly faster, but HashSet<T> is part of .NET 3.5 and we // don't want to have to reference to 3.5 unless it's really needed. Dictionary<T, byte> set = new Dictionary<T, byte>(capacity); foreach (T element in sequence) { if (element != null) { const byte Dummy = 0; set[element] = Dummy; } else { sequenceContainsNull = true; } } return set; } private static int DetermineInitialCapacity<T>(IEnumerable<T> sequence) { ICollection<T> collection = sequence as ICollection<T>; if (collection != null) { return collection.Count; } return 0; } private static Dictionary<object, byte> ConvertToSet(IEnumerable sequence, out bool sequenceContainsNull) { // A dictionary can have null as one of it's keys, therefore we have to communicate whether the // sequence contains null. sequenceContainsNull = false; int capacity = DetermineInitialCapacity(sequence); // A Dictionary is used to improve performance. Using 'Contains' on a collection would give a // performance characteristic of O(n*m) and with a Dictionary it's of O(m). // Using HashSet<T> is slightly faster, but HashSet<T> is part of .NET 3.5 and we // don't want to have to reference to 3.5 unless it's really needed. Dictionary<object, byte> set = new Dictionary<object, byte>(capacity); foreach (object element in sequence) { if (element != null) { const byte Dummy = 0; set[element] = Dummy; } else { sequenceContainsNull = true; } } return set; } private static int DetermineInitialCapacity(IEnumerable sequence) { ICollection collection = sequence as ICollection; if (collection != null) { return collection.Count; } return 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Moq; using Xunit; namespace Microsoft.AspNetCore.WebUtilities { public class PagedByteBufferTest { [Fact] public void Add_CreatesNewPage() { // Arrange var input = Encoding.UTF8.GetBytes("Hello world"); using var buffer = new PagedByteBuffer(ArrayPool<byte>.Shared); // Act buffer.Add(input, 0, input.Length); // Assert Assert.Single(buffer.Pages); Assert.Equal(input.Length, buffer.Length); Assert.Equal(input, ReadBufferedContent(buffer)); } [Fact] public void Add_AppendsToExistingPage() { // Arrange var input1 = Encoding.UTF8.GetBytes("Hello"); var input2 = Encoding.UTF8.GetBytes("world"); using var buffer = new PagedByteBuffer(ArrayPool<byte>.Shared); buffer.Add(input1, 0, input1.Length); // Act buffer.Add(input2, 0, input2.Length); // Assert Assert.Single(buffer.Pages); Assert.Equal(10, buffer.Length); Assert.Equal(Enumerable.Concat(input1, input2).ToArray(), ReadBufferedContent(buffer)); } [Fact] public void Add_WithOffsets() { // Arrange var input = new byte[] { 1, 2, 3, 4, 5 }; using var buffer = new PagedByteBuffer(ArrayPool<byte>.Shared); // Act buffer.Add(input, 1, 3); // Assert Assert.Single(buffer.Pages); Assert.Equal(3, buffer.Length); Assert.Equal(new byte[] { 2, 3, 4 }, ReadBufferedContent(buffer)); } [Fact] public void Add_FillsUpBuffer() { // Arrange var input1 = Enumerable.Repeat((byte)0xba, PagedByteBuffer.PageSize - 1).ToArray(); var input2 = new byte[] { 0xca }; using var buffer = new PagedByteBuffer(ArrayPool<byte>.Shared); buffer.Add(input1, 0, input1.Length); // Act buffer.Add(input2, 0, 1); // Assert Assert.Single(buffer.Pages); Assert.Equal(PagedByteBuffer.PageSize, buffer.Length); Assert.Equal(Enumerable.Concat(input1, input2).ToArray(), ReadBufferedContent(buffer)); } [Fact] public void Add_AppendsToMultiplePages() { // Arrange var input = Enumerable.Repeat((byte)0xba, PagedByteBuffer.PageSize + 10).ToArray(); using var buffer = new PagedByteBuffer(ArrayPool<byte>.Shared); // Act buffer.Add(input, 0, input.Length); // Assert Assert.Equal(2, buffer.Pages.Count); Assert.Equal(PagedByteBuffer.PageSize + 10, buffer.Length); Assert.Equal(input.ToArray(), ReadBufferedContent(buffer)); } [Fact] public void MoveTo_CopiesContentToStream() { // Arrange var input = Enumerable.Repeat((byte)0xba, PagedByteBuffer.PageSize * 3 + 10).ToArray(); using var buffer = new PagedByteBuffer(ArrayPool<byte>.Shared); buffer.Add(input, 0, input.Length); var stream = new MemoryStream(); // Act buffer.MoveTo(stream); // Assert Assert.Equal(input, stream.ToArray()); // Verify moving new content works. var newInput = Enumerable.Repeat((byte)0xcb, PagedByteBuffer.PageSize * 2 + 13).ToArray(); buffer.Add(newInput, 0, newInput.Length); stream.SetLength(0); buffer.MoveTo(stream); Assert.Equal(newInput, stream.ToArray()); } [Fact] public async Task MoveToAsync_CopiesContentToStream() { // Arrange var input = Enumerable.Repeat((byte)0xba, PagedByteBuffer.PageSize * 3 + 10).ToArray(); using var buffer = new PagedByteBuffer(ArrayPool<byte>.Shared); buffer.Add(input, 0, input.Length); var stream = new MemoryStream(); // Act await buffer.MoveToAsync(stream, default); // Assert Assert.Equal(input, stream.ToArray()); // Verify adding and moving new content works. var newInput = Enumerable.Repeat((byte)0xcb, PagedByteBuffer.PageSize * 2 + 13).ToArray(); buffer.Add(newInput, 0, newInput.Length); stream.SetLength(0); await buffer.MoveToAsync(stream, default); Assert.Equal(newInput, stream.ToArray()); } [Fact] public async Task MoveToAsync_ClearsBuffers() { // Arrange var input = Enumerable.Repeat((byte)0xba, PagedByteBuffer.PageSize * 3 + 10).ToArray(); using var buffer = new PagedByteBuffer(ArrayPool<byte>.Shared); buffer.Add(input, 0, input.Length); var stream = new MemoryStream(); // Act await buffer.MoveToAsync(stream, default); // Assert Assert.Equal(input, stream.ToArray()); // Verify copying it again works. Assert.Equal(0, buffer.Length); Assert.False(buffer.Disposed); Assert.Empty(buffer.Pages); } [Fact] public void MoveTo_WithClear_ReturnsBuffers() { // Arrange var input = new byte[] { 1, }; var arrayPool = new Mock<ArrayPool<byte>>(); var byteArray = new byte[PagedByteBuffer.PageSize]; arrayPool.Setup(p => p.Rent(PagedByteBuffer.PageSize)) .Returns(byteArray); arrayPool.Setup(p => p.Return(byteArray, false)).Verifiable(); var memoryStream = new MemoryStream(); using (var buffer = new PagedByteBuffer(arrayPool.Object)) { // Act buffer.Add(input, 0, input.Length); buffer.MoveTo(memoryStream); // Assert Assert.Equal(input, memoryStream.ToArray()); } arrayPool.Verify(p => p.Rent(It.IsAny<int>()), Times.Once()); arrayPool.Verify(p => p.Return(It.IsAny<byte[]>(), It.IsAny<bool>()), Times.Once()); } [Fact] public async Task MoveToAsync_ReturnsBuffers() { // Arrange var input = new byte[] { 1, }; var arrayPool = new Mock<ArrayPool<byte>>(); var byteArray = new byte[PagedByteBuffer.PageSize]; arrayPool.Setup(p => p.Rent(PagedByteBuffer.PageSize)) .Returns(byteArray); var memoryStream = new MemoryStream(); using (var buffer = new PagedByteBuffer(arrayPool.Object)) { // Act buffer.Add(input, 0, input.Length); await buffer.MoveToAsync(memoryStream, default); // Assert Assert.Equal(input, memoryStream.ToArray()); } arrayPool.Verify(p => p.Rent(It.IsAny<int>()), Times.Once()); arrayPool.Verify(p => p.Return(It.IsAny<byte[]>(), It.IsAny<bool>()), Times.Once()); } [Fact] public void Dispose_ReturnsBuffers_ExactlyOnce() { // Arrange var input = Enumerable.Repeat((byte)0xba, PagedByteBuffer.PageSize * 3 + 10).ToArray(); var arrayPool = new Mock<ArrayPool<byte>>(); arrayPool.Setup(p => p.Rent(PagedByteBuffer.PageSize)) .Returns(new byte[PagedByteBuffer.PageSize]); var buffer = new PagedByteBuffer(arrayPool.Object); // Act buffer.Add(input, 0, input.Length); buffer.Dispose(); buffer.Dispose(); arrayPool.Verify(p => p.Rent(It.IsAny<int>()), Times.Exactly(4)); arrayPool.Verify(p => p.Return(It.IsAny<byte[]>(), It.IsAny<bool>()), Times.Exactly(4)); } private static byte[] ReadBufferedContent(PagedByteBuffer buffer) { using var stream = new MemoryStream(); buffer.MoveTo(stream); return stream.ToArray(); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Metastore.V1Beta.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedDataprocMetastoreClientTest { [xunit::FactAttribute] public void GetServiceRequestObject() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServiceRequest request = new GetServiceRequest { ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"), }; Service expectedResponse = new Service { ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, HiveMetastoreConfig = new HiveMetastoreConfig(), NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"), EndpointUri = "endpoint_uri59c03c94", Port = -78310000, State = Service.Types.State.Deleting, StateMessage = "state_message46cf28c0", ArtifactGcsUri = "artifact_gcs_uri4d2b3985", Tier = Service.Types.Tier.Developer, MetadataIntegration = new MetadataIntegration(), MaintenanceWindow = new MaintenanceWindow(), Uid = "uida2d37198", MetadataManagementActivity = new MetadataManagementActivity(), ReleaseChannel = Service.Types.ReleaseChannel.Stable, }; mockGrpcClient.Setup(x => x.GetService(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); Service response = client.GetService(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetServiceRequestObjectAsync() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServiceRequest request = new GetServiceRequest { ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"), }; Service expectedResponse = new Service { ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, HiveMetastoreConfig = new HiveMetastoreConfig(), NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"), EndpointUri = "endpoint_uri59c03c94", Port = -78310000, State = Service.Types.State.Deleting, StateMessage = "state_message46cf28c0", ArtifactGcsUri = "artifact_gcs_uri4d2b3985", Tier = Service.Types.Tier.Developer, MetadataIntegration = new MetadataIntegration(), MaintenanceWindow = new MaintenanceWindow(), Uid = "uida2d37198", MetadataManagementActivity = new MetadataManagementActivity(), ReleaseChannel = Service.Types.ReleaseChannel.Stable, }; mockGrpcClient.Setup(x => x.GetServiceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Service>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); Service responseCallSettings = await client.GetServiceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Service responseCancellationToken = await client.GetServiceAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetService() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServiceRequest request = new GetServiceRequest { ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"), }; Service expectedResponse = new Service { ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, HiveMetastoreConfig = new HiveMetastoreConfig(), NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"), EndpointUri = "endpoint_uri59c03c94", Port = -78310000, State = Service.Types.State.Deleting, StateMessage = "state_message46cf28c0", ArtifactGcsUri = "artifact_gcs_uri4d2b3985", Tier = Service.Types.Tier.Developer, MetadataIntegration = new MetadataIntegration(), MaintenanceWindow = new MaintenanceWindow(), Uid = "uida2d37198", MetadataManagementActivity = new MetadataManagementActivity(), ReleaseChannel = Service.Types.ReleaseChannel.Stable, }; mockGrpcClient.Setup(x => x.GetService(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); Service response = client.GetService(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetServiceAsync() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServiceRequest request = new GetServiceRequest { ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"), }; Service expectedResponse = new Service { ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, HiveMetastoreConfig = new HiveMetastoreConfig(), NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"), EndpointUri = "endpoint_uri59c03c94", Port = -78310000, State = Service.Types.State.Deleting, StateMessage = "state_message46cf28c0", ArtifactGcsUri = "artifact_gcs_uri4d2b3985", Tier = Service.Types.Tier.Developer, MetadataIntegration = new MetadataIntegration(), MaintenanceWindow = new MaintenanceWindow(), Uid = "uida2d37198", MetadataManagementActivity = new MetadataManagementActivity(), ReleaseChannel = Service.Types.ReleaseChannel.Stable, }; mockGrpcClient.Setup(x => x.GetServiceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Service>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); Service responseCallSettings = await client.GetServiceAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Service responseCancellationToken = await client.GetServiceAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetServiceResourceNames() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServiceRequest request = new GetServiceRequest { ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"), }; Service expectedResponse = new Service { ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, HiveMetastoreConfig = new HiveMetastoreConfig(), NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"), EndpointUri = "endpoint_uri59c03c94", Port = -78310000, State = Service.Types.State.Deleting, StateMessage = "state_message46cf28c0", ArtifactGcsUri = "artifact_gcs_uri4d2b3985", Tier = Service.Types.Tier.Developer, MetadataIntegration = new MetadataIntegration(), MaintenanceWindow = new MaintenanceWindow(), Uid = "uida2d37198", MetadataManagementActivity = new MetadataManagementActivity(), ReleaseChannel = Service.Types.ReleaseChannel.Stable, }; mockGrpcClient.Setup(x => x.GetService(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); Service response = client.GetService(request.ServiceName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetServiceResourceNamesAsync() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServiceRequest request = new GetServiceRequest { ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"), }; Service expectedResponse = new Service { ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, HiveMetastoreConfig = new HiveMetastoreConfig(), NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"), EndpointUri = "endpoint_uri59c03c94", Port = -78310000, State = Service.Types.State.Deleting, StateMessage = "state_message46cf28c0", ArtifactGcsUri = "artifact_gcs_uri4d2b3985", Tier = Service.Types.Tier.Developer, MetadataIntegration = new MetadataIntegration(), MaintenanceWindow = new MaintenanceWindow(), Uid = "uida2d37198", MetadataManagementActivity = new MetadataManagementActivity(), ReleaseChannel = Service.Types.ReleaseChannel.Stable, }; mockGrpcClient.Setup(x => x.GetServiceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Service>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); Service responseCallSettings = await client.GetServiceAsync(request.ServiceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Service responseCancellationToken = await client.GetServiceAsync(request.ServiceName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetMetadataImportRequestObject() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetMetadataImportRequest request = new GetMetadataImportRequest { MetadataImportName = MetadataImportName.FromProjectLocationServiceMetadataImport("[PROJECT]", "[LOCATION]", "[SERVICE]", "[METADATA_IMPORT]"), }; MetadataImport expectedResponse = new MetadataImport { MetadataImportName = MetadataImportName.FromProjectLocationServiceMetadataImport("[PROJECT]", "[LOCATION]", "[SERVICE]", "[METADATA_IMPORT]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = MetadataImport.Types.State.Updating, DatabaseDump = new MetadataImport.Types.DatabaseDump(), }; mockGrpcClient.Setup(x => x.GetMetadataImport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); MetadataImport response = client.GetMetadataImport(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMetadataImportRequestObjectAsync() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetMetadataImportRequest request = new GetMetadataImportRequest { MetadataImportName = MetadataImportName.FromProjectLocationServiceMetadataImport("[PROJECT]", "[LOCATION]", "[SERVICE]", "[METADATA_IMPORT]"), }; MetadataImport expectedResponse = new MetadataImport { MetadataImportName = MetadataImportName.FromProjectLocationServiceMetadataImport("[PROJECT]", "[LOCATION]", "[SERVICE]", "[METADATA_IMPORT]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = MetadataImport.Types.State.Updating, DatabaseDump = new MetadataImport.Types.DatabaseDump(), }; mockGrpcClient.Setup(x => x.GetMetadataImportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MetadataImport>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); MetadataImport responseCallSettings = await client.GetMetadataImportAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); MetadataImport responseCancellationToken = await client.GetMetadataImportAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetMetadataImport() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetMetadataImportRequest request = new GetMetadataImportRequest { MetadataImportName = MetadataImportName.FromProjectLocationServiceMetadataImport("[PROJECT]", "[LOCATION]", "[SERVICE]", "[METADATA_IMPORT]"), }; MetadataImport expectedResponse = new MetadataImport { MetadataImportName = MetadataImportName.FromProjectLocationServiceMetadataImport("[PROJECT]", "[LOCATION]", "[SERVICE]", "[METADATA_IMPORT]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = MetadataImport.Types.State.Updating, DatabaseDump = new MetadataImport.Types.DatabaseDump(), }; mockGrpcClient.Setup(x => x.GetMetadataImport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); MetadataImport response = client.GetMetadataImport(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMetadataImportAsync() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetMetadataImportRequest request = new GetMetadataImportRequest { MetadataImportName = MetadataImportName.FromProjectLocationServiceMetadataImport("[PROJECT]", "[LOCATION]", "[SERVICE]", "[METADATA_IMPORT]"), }; MetadataImport expectedResponse = new MetadataImport { MetadataImportName = MetadataImportName.FromProjectLocationServiceMetadataImport("[PROJECT]", "[LOCATION]", "[SERVICE]", "[METADATA_IMPORT]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = MetadataImport.Types.State.Updating, DatabaseDump = new MetadataImport.Types.DatabaseDump(), }; mockGrpcClient.Setup(x => x.GetMetadataImportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MetadataImport>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); MetadataImport responseCallSettings = await client.GetMetadataImportAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); MetadataImport responseCancellationToken = await client.GetMetadataImportAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetMetadataImportResourceNames() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetMetadataImportRequest request = new GetMetadataImportRequest { MetadataImportName = MetadataImportName.FromProjectLocationServiceMetadataImport("[PROJECT]", "[LOCATION]", "[SERVICE]", "[METADATA_IMPORT]"), }; MetadataImport expectedResponse = new MetadataImport { MetadataImportName = MetadataImportName.FromProjectLocationServiceMetadataImport("[PROJECT]", "[LOCATION]", "[SERVICE]", "[METADATA_IMPORT]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = MetadataImport.Types.State.Updating, DatabaseDump = new MetadataImport.Types.DatabaseDump(), }; mockGrpcClient.Setup(x => x.GetMetadataImport(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); MetadataImport response = client.GetMetadataImport(request.MetadataImportName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetMetadataImportResourceNamesAsync() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetMetadataImportRequest request = new GetMetadataImportRequest { MetadataImportName = MetadataImportName.FromProjectLocationServiceMetadataImport("[PROJECT]", "[LOCATION]", "[SERVICE]", "[METADATA_IMPORT]"), }; MetadataImport expectedResponse = new MetadataImport { MetadataImportName = MetadataImportName.FromProjectLocationServiceMetadataImport("[PROJECT]", "[LOCATION]", "[SERVICE]", "[METADATA_IMPORT]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), State = MetadataImport.Types.State.Updating, DatabaseDump = new MetadataImport.Types.DatabaseDump(), }; mockGrpcClient.Setup(x => x.GetMetadataImportAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MetadataImport>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); MetadataImport responseCallSettings = await client.GetMetadataImportAsync(request.MetadataImportName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); MetadataImport responseCancellationToken = await client.GetMetadataImportAsync(request.MetadataImportName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetBackupRequestObject() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetBackupRequest request = new GetBackupRequest { BackupName = BackupName.FromProjectLocationServiceBackup("[PROJECT]", "[LOCATION]", "[SERVICE]", "[BACKUP]"), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectLocationServiceBackup("[PROJECT]", "[LOCATION]", "[SERVICE]", "[BACKUP]"), CreateTime = new wkt::Timestamp(), EndTime = new wkt::Timestamp(), State = Backup.Types.State.Active, ServiceRevision = new Service(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetBackup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); Backup response = client.GetBackup(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetBackupRequestObjectAsync() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetBackupRequest request = new GetBackupRequest { BackupName = BackupName.FromProjectLocationServiceBackup("[PROJECT]", "[LOCATION]", "[SERVICE]", "[BACKUP]"), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectLocationServiceBackup("[PROJECT]", "[LOCATION]", "[SERVICE]", "[BACKUP]"), CreateTime = new wkt::Timestamp(), EndTime = new wkt::Timestamp(), State = Backup.Types.State.Active, ServiceRevision = new Service(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetBackupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Backup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); Backup responseCallSettings = await client.GetBackupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Backup responseCancellationToken = await client.GetBackupAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetBackup() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetBackupRequest request = new GetBackupRequest { BackupName = BackupName.FromProjectLocationServiceBackup("[PROJECT]", "[LOCATION]", "[SERVICE]", "[BACKUP]"), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectLocationServiceBackup("[PROJECT]", "[LOCATION]", "[SERVICE]", "[BACKUP]"), CreateTime = new wkt::Timestamp(), EndTime = new wkt::Timestamp(), State = Backup.Types.State.Active, ServiceRevision = new Service(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetBackup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); Backup response = client.GetBackup(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetBackupAsync() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetBackupRequest request = new GetBackupRequest { BackupName = BackupName.FromProjectLocationServiceBackup("[PROJECT]", "[LOCATION]", "[SERVICE]", "[BACKUP]"), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectLocationServiceBackup("[PROJECT]", "[LOCATION]", "[SERVICE]", "[BACKUP]"), CreateTime = new wkt::Timestamp(), EndTime = new wkt::Timestamp(), State = Backup.Types.State.Active, ServiceRevision = new Service(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetBackupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Backup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); Backup responseCallSettings = await client.GetBackupAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Backup responseCancellationToken = await client.GetBackupAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetBackupResourceNames() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetBackupRequest request = new GetBackupRequest { BackupName = BackupName.FromProjectLocationServiceBackup("[PROJECT]", "[LOCATION]", "[SERVICE]", "[BACKUP]"), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectLocationServiceBackup("[PROJECT]", "[LOCATION]", "[SERVICE]", "[BACKUP]"), CreateTime = new wkt::Timestamp(), EndTime = new wkt::Timestamp(), State = Backup.Types.State.Active, ServiceRevision = new Service(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetBackup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); Backup response = client.GetBackup(request.BackupName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetBackupResourceNamesAsync() { moq::Mock<DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock<DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetBackupRequest request = new GetBackupRequest { BackupName = BackupName.FromProjectLocationServiceBackup("[PROJECT]", "[LOCATION]", "[SERVICE]", "[BACKUP]"), }; Backup expectedResponse = new Backup { BackupName = BackupName.FromProjectLocationServiceBackup("[PROJECT]", "[LOCATION]", "[SERVICE]", "[BACKUP]"), CreateTime = new wkt::Timestamp(), EndTime = new wkt::Timestamp(), State = Backup.Types.State.Active, ServiceRevision = new Service(), Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetBackupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Backup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null); Backup responseCallSettings = await client.GetBackupAsync(request.BackupName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Backup responseCancellationToken = await client.GetBackupAsync(request.BackupName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- /// The texture filename filter used with OpenFileDialog. $TerrainEditor::TextureFileSpec = "Image Files (*.png, *.jpg, *.dds)|*.png;*.jpg;*.dds|All Files (*.*)|*.*|"; function TerrainEditor::init( %this ) { %this.attachTerrain(); %this.setBrushSize( 9, 9 ); new PersistenceManager( ETerrainPersistMan ); } /// function EPainter_TerrainMaterialUpdateCallback( %mat, %matIndex ) { // Skip over a bad selection. if ( %matIndex == -1 || !isObject( %mat ) ) return; // Update the material and the UI. ETerrainEditor.updateMaterial( %matIndex, %mat.getInternalName() ); EPainter.setup( %matIndex ); } function EPainter_TerrainMaterialAddCallback( %mat, %matIndex ) { // Ignore bad materials. if ( !isObject( %mat ) ) return; // Add it and update the UI. ETerrainEditor.addMaterial( %mat.getInternalName() ); EPainter.setup( %matIndex ); } function TerrainEditor::setPaintMaterial( %this, %matIndex, %terrainMat ) { assert( isObject( %terrainMat ), "TerrainEditor::setPaintMaterial - Got bad material!" ); ETerrainEditor.paintIndex = %matIndex; ETerrainMaterialSelected.selectedMatIndex = %matIndex; ETerrainMaterialSelected.selectedMat = %terrainMat; ETerrainMaterialSelected.bitmap = %terrainMat.diffuseMap; ETerrainMaterialSelectedEdit.Visible = isObject(%terrainMat); TerrainTextureText.text = %terrainMat.getInternalName(); } function TerrainEditor::setup( %this ) { %action = %this.savedAction; %desc = %this.savedActionDesc; if ( %this.savedAction $= "" ) { %action = brushAdjustHeight; } %this.switchAction( %action ); } function EPainter::updateLayers( %this, %matIndex ) { // Default to whatever was selected before. if ( %matIndex $= "" ) %matIndex = ETerrainEditor.paintIndex; // The material string is a newline seperated string of // TerrainMaterial internal names which we can use to find // the actual material data in TerrainMaterialSet. %mats = ETerrainEditor.getMaterials(); %matList = %this-->theMaterialList; %matList.deleteAllObjects(); %listWidth = getWord( %matList.getExtent(), 0 ); for( %i = 0; %i < getRecordCount( %mats ); %i++ ) { %matInternalName = getRecord( %mats, %i ); %mat = TerrainMaterialSet.findObjectByInternalName( %matInternalName ); // Is there no material info for this slot? if ( !isObject( %mat ) ) continue; %index = %matList.getCount(); %command = "ETerrainEditor.setPaintMaterial( " @ %index @ ", " @ %mat @ " );"; %altCommand = "TerrainMaterialDlg.show( " @ %index @ ", " @ %mat @ ", EPainter_TerrainMaterialUpdateCallback );"; %ctrl = new GuiIconButtonCtrl() { class = "EPainterIconBtn"; internalName = "EPainterMaterialButton" @ %i; profile = "GuiCreatorIconButtonProfile"; iconLocation = "Left"; textLocation = "Right"; extent = %listWidth SPC "46"; textMargin = 5; buttonMargin = "4 4"; buttonType = "RadioButton"; sizeIconToButton = true; makeIconSquare = true; tooltipprofile = "GuiToolTipProfile"; command = %command; altCommand = %altCommand; useMouseEvents = true; new GuiBitmapButtonCtrl() { bitmap = "tools/gui/images/delete"; buttonType = "PushButton"; HorizSizing = "left"; VertSizing = "bottom"; position = ( %listwidth - 20 ) SPC "26"; Extent = "17 17"; command = "EPainter.showMaterialDeleteDlg( " @ %matInternalName @ " );"; }; }; %ctrl.setText( %matInternalName ); %ctrl.setBitmap( %mat.diffuseMap ); %tooltip = %matInternalName; if(%i < 9) %tooltip = %tooltip @ " (" @ (%i+1) @ ")"; else if(%i == 9) %tooltip = %tooltip @ " (0)"; %ctrl.tooltip = %tooltip; %matList.add( %ctrl ); } %matCount = %matList.getCount(); // Add one more layer as the 'add new' layer. %ctrl = new GuiIconButtonCtrl() { profile = "GuiCreatorIconButtonProfile"; iconBitmap = "~/worldEditor/images/terrainpainter/new_layer_icon"; iconLocation = "Left"; textLocation = "Right"; extent = %listWidth SPC "46"; textMargin = 5; buttonMargin = "4 4"; buttonType = "PushButton"; sizeIconToButton = true; makeIconSquare = true; tooltipprofile = "GuiToolTipProfile"; text = "New Layer"; tooltip = "New Layer"; command = "TerrainMaterialDlg.show( " @ %matCount @ ", 0, EPainter_TerrainMaterialAddCallback );"; }; %matList.add( %ctrl ); // Make sure our selection is valid and that we're // not selecting the 'New Layer' button. if( %matIndex < 0 ) return; if( %matIndex >= %matCount ) %matIndex = 0; // To make things simple... click the paint material button to // active it and initialize other state. %ctrl = %matList.getObject( %matIndex ); %ctrl.performClick(); } function EPainter::showMaterialDeleteDlg( %this, %matInternalName ) { MessageBoxYesNo( "Confirmation", "Really remove material '" @ %matInternalName @ "' from the terrain?", %this @ ".removeMaterial( " @ %matInternalName @ " );", "" ); } function EPainter::removeMaterial( %this, %matInternalName ) { %selIndex = ETerrainEditor.paintIndex - 1; // Remove the material from the terrain. %index = ETerrainEditor.getMaterialIndex( %matInternalName ); if( %index != -1 ) ETerrainEditor.removeMaterial( %index ); // Update the material list. %this.updateLayers( %selIndex ); } function EPainter::setup( %this, %matIndex ) { // Update the layer listing. %this.updateLayers( %matIndex ); // Automagically put us into material paint mode. ETerrainEditor.currentMode = "paint"; ETerrainEditor.selectionHidden = true; ETerrainEditor.currentAction = paintMaterial; ETerrainEditor.currentActionDesc = "Paint material on terrain"; ETerrainEditor.setAction( ETerrainEditor.currentAction ); EditorGuiStatusBar.setInfo(ETerrainEditor.currentActionDesc); ETerrainEditor.renderVertexSelection = true; } function onNeedRelight() { if( RelightMessage.visible == false ) RelightMessage.visible = true; } function TerrainEditor::onGuiUpdate(%this, %text) { %minHeight = getWord(%text, 1); %avgHeight = getWord(%text, 2); %maxHeight = getWord(%text, 3); %mouseBrushInfo = " (Mouse) #: " @ getWord(%text, 0) @ " avg: " @ %avgHeight @ " " @ ETerrainEditor.currentAction; %selectionInfo = " (Selected) #: " @ getWord(%text, 4) @ " avg: " @ getWord(%text, 5); TEMouseBrushInfo.setValue(%mouseBrushInfo); TEMouseBrushInfo1.setValue(%mouseBrushInfo); TESelectionInfo.setValue(%selectionInfo); TESelectionInfo1.setValue(%selectionInfo); EditorGuiStatusBar.setSelection("min: " @ %minHeight @ " avg: " @ %avgHeight @ " max: " @ %maxHeight); } function TerrainEditor::onBrushChanged( %this ) { EditorGui.currentEditor.syncBrushInfo(); } function TerrainEditor::toggleBrushType( %this, %brush ) { %this.setBrushType( %brush.internalName ); } function TerrainEditor::offsetBrush(%this, %x, %y) { %curPos = %this.getBrushPos(); %this.setBrushPos(getWord(%curPos, 0) + %x, getWord(%curPos, 1) + %y); } function TerrainEditor::onActiveTerrainChange(%this, %newTerrain) { // Need to refresh the terrain painter. if ( EditorGui.currentEditor.getId() == TerrainPainterPlugin.getId() ) EPainter.setup(ETerrainEditor.paintIndex); } function TerrainEditor::getActionDescription( %this, %action ) { switch$( %action ) { case "brushAdjustHeight": return "Adjust terrain height up or down."; case "raiseHeight": return "Raise terrain height."; case "lowerHeight": return "Lower terrain height."; case "smoothHeight": return "Smooth terrain."; case "paintNoise": return "Modify terrain height using noise."; case "flattenHeight": return "Flatten terrain."; case "setHeight": return "Set terrain height to defined value."; case "setEmpty": return "Remove terrain collision."; case "clearEmpty": return "Add back terrain collision."; default: return ""; } } /// This is only ment for terrain editing actions and not /// processed actions or the terrain material painting action. function TerrainEditor::switchAction( %this, %action ) { %actionDesc = %this.getActionDescription(%action); %this.currentMode = "paint"; %this.selectionHidden = true; %this.currentAction = %action; %this.currentActionDesc = %actionDesc; %this.savedAction = %action; %this.savedActionDesc = %actionDesc; if ( %action $= "setEmpty" || %action $= "clearEmpty" || %action $= "setHeight" ) %this.renderSolidBrush = true; else %this.renderSolidBrush = false; EditorGuiStatusBar.setInfo(%actionDesc); %this.setAction( %this.currentAction ); } function TerrainEditor::onSmoothHeightmap( %this ) { if ( !%this.getActiveTerrain() ) return; // Show the dialog first and let the user // set the smoothing parameters. // Now create the terrain smoothing action to // get the work done and perform later undos. %action = new TerrainSmoothAction(); %action.smooth( %this.getActiveTerrain(), 1.0, 1 ); %action.addToManager( Editor.getUndoManager() ); } function TerrainEditor::onMaterialUndo( %this ) { // Update the gui to reflect the current materials. EPainter.updateLayers(); } //------------------------------------------------------------------------------ // Functions //------------------------------------------------------------------------------ function TerrainEditorSettingsGui::onWake(%this) { TESoftSelectFilter.setValue(ETerrainEditor.softSelectFilter); } function TerrainEditorSettingsGui::onSleep(%this) { ETerrainEditor.softSelectFilter = TESoftSelectFilter.getValue(); } function TESettingsApplyButton::onAction(%this) { ETerrainEditor.softSelectFilter = TESoftSelectFilter.getValue(); ETerrainEditor.resetSelWeights(true); ETerrainEditor.processAction("softSelect"); } function getPrefSetting(%pref, %default) { // if(%pref $= "") return(%default); else return(%pref); } function TerrainEditorPlugin::setEditorFunction(%this) { %terrainExists = parseMissionGroup( "TerrainBlock" ); if( %terrainExists == false ) MessageBoxYesNoCancel("No Terrain","Would you like to create a New Terrain?", "Canvas.pushDialog(CreateNewTerrainGui);"); return %terrainExists; } function TerrainPainterPlugin::setEditorFunction(%this, %overrideGroup) { %terrainExists = parseMissionGroup( "TerrainBlock" ); if( %terrainExists == false ) MessageBoxYesNoCancel("No Terrain","Would you like to create a New Terrain?", "Canvas.pushDialog(CreateNewTerrainGui);"); return %terrainExists; } function EPainterIconBtn::onMouseDragged( %this ) { %payload = new GuiControl() { profile = GuiCreatorIconButtonProfile; position = "0 0"; extent = %this.extent.x SPC "5"; dragSourceControl = %this; }; %xOffset = getWord( %payload.extent, 0 ) / 2; %yOffset = getWord( %payload.extent, 1 ) / 2; %cursorpos = Canvas.getCursorPos(); %xPos = getWord( %cursorpos, 0 ) - %xOffset; %yPos = getWord( %cursorpos, 1 ) - %yOffset; // Create the drag control. %ctrl = new GuiDragAndDropControl() { canSaveDynamicFields = "0"; Profile = EPainterDragDropProfile; HorizSizing = "right"; VertSizing = "bottom"; Position = %xPos SPC %yPos; extent = %payload.extent; MinExtent = "4 4"; canSave = "1"; Visible = "1"; hovertime = "1000"; deleteOnMouseUp = true; }; %ctrl.add( %payload ); Canvas.getContent().add( %ctrl ); %ctrl.startDragging( %xOffset, %yOffset ); } function EPainterIconBtn::onControlDragged( %this, %payload ) { %payload.getParent().position = %this.getGlobalPosition(); } function EPainterIconBtn::onControlDropped( %this, %payload ) { %srcBtn = %payload.dragSourceControl; %dstBtn = %this; %stack = %this.getParent(); // Not dropped on a valid Button. // Really this shouldnt happen since we are in a callback on our specialized // EPainterIconBtn namespace. if ( %stack != %dstBtn.getParent() || %stack != EPainterStack.getId() ) { echo( "Not dropped on valid control" ); return; } // Dropped on the original control, no order change. // Simulate a click on the control, instead of a drag/drop. if ( %srcBtn == %dstBtn ) { %dstBtn.performClick(); return; } %dstIndex = %stack.getObjectIndex( %dstBtn ); ETerrainEditor.reorderMaterial( %stack.getObjectIndex( %srcBtn ), %dstIndex ); // select the button/material we just reordered. %stack.getObject( %dstIndex ).performClick(); }
// Copyright 2014, 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. // Author: api.anash@gmail.com (Anash P. Oommen) using Google.Api.Ads.Common.Util; using Google.Api.Ads.Dfp.Lib; using Google.Api.Ads.Dfp.v201405; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Threading; namespace Google.Api.Ads.Dfp.Tests.v201405 { /// <summary> /// UnitTests for <see cref="LineItemCreativeAssociationServiceTests"/> class. /// </summary> [TestFixture] public class LineItemCreativeAssociationServiceTests : BaseTests { /// <summary> /// UnitTests for <see cref="LineItemCreativeAssociationService"/> class. /// </summary> private LineItemCreativeAssociationService licaService; /// <summary> /// Advertiser company id for running tests. /// </summary> private long advertiserId; /// <summary> /// Salesperson user id for running tests. /// </summary> private long salespersonId; /// <summary> /// Trafficker user id for running tests. /// </summary> private long traffickerId; /// <summary> /// Order id for running tests. /// </summary> private long orderId; /// <summary> /// Ad unit id for running tests. /// </summary> private string adUnitId; /// <summary> /// Creative id 1 for running tests. /// </summary> private long creativeId1; /// <summary> /// Creative id 2 for running tests. /// </summary> private long creativeId2; /// <summary> /// Creative id 3 for running tests. /// </summary> private long creativeId3; /// <summary> /// Creative id 4 for running tests. /// </summary> private long creativeId4; /// <summary> /// Line item id 1 for running tests. /// </summary> private long lineItemId1; /// <summary> /// Line item id 2 for running tests. /// </summary> private long lineItemId2; /// <summary> /// Line item id 3 for running tests. /// </summary> private long lineItemId3; /// <summary> /// Line item id 4 for running tests. /// </summary> private long lineItemId4; /// <summary> /// Line item creative association 1 for running tests. /// </summary> private LineItemCreativeAssociation lica1; /// <summary> /// Line item creative association 2 for running tests. /// </summary> private LineItemCreativeAssociation lica2; /// <summary> /// Default public constructor. /// </summary> public LineItemCreativeAssociationServiceTests() : base() { } /// <summary> /// Initialize the test case. /// </summary> [SetUp] public void Init() { TestUtils utils = new TestUtils(); licaService = (LineItemCreativeAssociationService) user.GetService( DfpService.v201405.LineItemCreativeAssociationService); advertiserId = utils.CreateCompany(user, CompanyType.ADVERTISER).id; salespersonId = utils.GetSalesperson(user).id; traffickerId = utils.GetTrafficker(user).id; orderId = utils.CreateOrder(user, advertiserId, salespersonId, traffickerId).id; adUnitId = utils.CreateAdUnit(user).id; lineItemId1 = utils.CreateLineItem(user, orderId, adUnitId).id; lineItemId2 = utils.CreateLineItem(user, orderId, adUnitId).id; lineItemId3 = utils.CreateLineItem(user, orderId, adUnitId).id; lineItemId4 = utils.CreateLineItem(user, orderId, adUnitId).id; creativeId1 = utils.CreateCreative(user, advertiserId).id; creativeId2 = utils.CreateCreative(user, advertiserId).id; creativeId3 = utils.CreateCreative(user, advertiserId).id; creativeId4 = utils.CreateCreative(user, advertiserId).id; lica1 = utils.CreateLica(user, lineItemId3, creativeId3); lica2 = utils.CreateLica(user, lineItemId4, creativeId4); } /// <summary> /// Test whether we can create a list of line item creative associations. /// </summary> [Test] public void TestCreateLineItemCreativeAssociations() { LineItemCreativeAssociation localLica1 = new LineItemCreativeAssociation(); localLica1.creativeId = creativeId1; localLica1.lineItemId = lineItemId1; LineItemCreativeAssociation localLica2 = new LineItemCreativeAssociation(); localLica2.creativeId = creativeId2; localLica2.lineItemId = lineItemId2; LineItemCreativeAssociation[] newLicas = null; Assert.DoesNotThrow(delegate() { newLicas = licaService.createLineItemCreativeAssociations( new LineItemCreativeAssociation[] {localLica1, localLica2}); }); Assert.NotNull(newLicas); Assert.AreEqual(newLicas.Length, 2); Assert.NotNull(newLicas[0]); Assert.AreEqual(newLicas[0].creativeId, localLica1.creativeId); Assert.AreEqual(newLicas[0].lineItemId, localLica1.lineItemId); Assert.NotNull(newLicas[1]); Assert.AreEqual(newLicas[1].creativeId, localLica2.creativeId); Assert.AreEqual(newLicas[1].lineItemId, localLica2.lineItemId); } /// <summary> /// Test whether we can fetch a list of existing line item creative /// associations that match given statement. /// </summary> [Test] public void TestGetLineItemCreativeAssociationsByStatement() { Statement statement = new Statement(); statement.query = string.Format("WHERE lineItemId = '{0}' LIMIT 500", lineItemId3); LineItemCreativeAssociationPage page = null; Assert.DoesNotThrow(delegate() { page = licaService.getLineItemCreativeAssociationsByStatement(statement); }); Assert.NotNull(page); Assert.NotNull(page.results); Assert.AreEqual(page.totalResultSetSize, 1); Assert.NotNull(page.results[0]); Assert.AreEqual(page.results[0].creativeId, lica1.creativeId); Assert.AreEqual(page.results[0].lineItemId, lica1.lineItemId); } /// <summary> /// Test whether we can deactivate a line item create association. /// </summary> [Test] public void TestPerformLineItemCreativeAssociationAction() { Statement statement = new Statement(); statement.query = string.Format("WHERE lineItemId = '{0}' LIMIT 1", lineItemId3); DeactivateLineItemCreativeAssociations action = new DeactivateLineItemCreativeAssociations(); UpdateResult result = null; Assert.DoesNotThrow(delegate() { result = licaService.performLineItemCreativeAssociationAction(action, statement); }); Assert.NotNull(result); Assert.AreEqual(result.numChanges, 1); } /// <summary> /// Test whether we can update a list of line item creative associations. /// </summary> [Test] public void TestUpdateLineItemCreativeAssociations() { lica1.destinationUrl = "http://news.google.com"; lica2.destinationUrl = "http://news.google.com"; LineItemCreativeAssociation[] newLicas = null; Assert.DoesNotThrow(delegate() { newLicas = licaService.updateLineItemCreativeAssociations( new LineItemCreativeAssociation[] {lica1, lica2}); }); Assert.NotNull(newLicas); Assert.AreEqual(newLicas.Length, 2); Assert.NotNull(newLicas[0]); Assert.AreEqual(newLicas[0].creativeId, lica1.creativeId); Assert.AreEqual(newLicas[0].lineItemId, lica1.lineItemId); Assert.NotNull(newLicas[1]); Assert.AreEqual(newLicas[1].creativeId, lica2.creativeId); Assert.AreEqual(newLicas[1].lineItemId, lica2.lineItemId); } } }
// 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.Runtime.Serialization; namespace System.Collections.Generic { public partial class SortedSet<T> { /// <summary> /// This class represents a subset view into the tree. Any changes to this view /// are reflected in the actual tree. It uses the comparer of the underlying tree. /// </summary> internal sealed class TreeSubSet : SortedSet<T>, ISerializable, IDeserializationCallback { private SortedSet<T> _underlying; private T _min, _max; // these exist for unbounded collections // for instance, you could allow this subset to be defined for i > 10. The set will throw if // anything <= 10 is added, but there is no upper bound. These features Head(), Tail(), were punted // in the spec, and are not available, but the framework is there to make them available at some point. private bool _lBoundActive, _uBoundActive; // used to see if the count is out of date #if DEBUG internal override bool versionUpToDate() { return (_version == _underlying._version); } #endif public TreeSubSet(SortedSet<T> Underlying, T Min, T Max, bool lowerBoundActive, bool upperBoundActive) : base(Underlying.Comparer) { _underlying = Underlying; _min = Min; _max = Max; _lBoundActive = lowerBoundActive; _uBoundActive = upperBoundActive; _root = _underlying.FindRange(_min, _max, _lBoundActive, _uBoundActive); // root is first element within range _count = 0; _version = -1; VersionCheckImpl(); } internal override bool AddIfNotPresent(T item) { if (!IsWithinRange(item)) { throw new ArgumentOutOfRangeException(nameof(item)); } bool ret = _underlying.AddIfNotPresent(item); VersionCheck(); #if DEBUG Debug.Assert(this.versionUpToDate() && _root == _underlying.FindRange(_min, _max)); #endif return ret; } public override bool Contains(T item) { VersionCheck(); #if DEBUG Debug.Assert(versionUpToDate() && _root == _underlying.FindRange(_min, _max)); #endif return base.Contains(item); } internal override bool DoRemove(T item) { if (!IsWithinRange(item)) { return false; } bool ret = _underlying.Remove(item); VersionCheck(); #if DEBUG Debug.Assert(versionUpToDate() && _root == _underlying.FindRange(_min, _max)); #endif return ret; } public override void Clear() { if (_count == 0) { return; } List<T> toRemove = new List<T>(); BreadthFirstTreeWalk(n => { toRemove.Add(n.Item); return true; }); while (toRemove.Count != 0) { _underlying.Remove(toRemove[toRemove.Count - 1]); toRemove.RemoveAt(toRemove.Count - 1); } _root = null; _count = 0; _version = _underlying._version; } internal override bool IsWithinRange(T item) { int comp = _lBoundActive ? Comparer.Compare(_min, item) : -1; if (comp > 0) { return false; } comp = _uBoundActive ? Comparer.Compare(_max, item) : 1; return comp >= 0; } internal override T MinInternal { get { Node current = _root; T result = default(T); while (current != null) { int comp = _lBoundActive ? Comparer.Compare(_min, current.Item) : -1; if (comp == 1) { current = current.Right; } else { result = current.Item; if (comp == 0) { break; } current = current.Left; } } return result; } } internal override T MaxInternal { get { Node current = _root; T result = default(T); while (current != null) { int comp = _uBoundActive ? Comparer.Compare(_max, current.Item) : 1; if (comp == -1) { current = current.Left; } else { result = current.Item; if (comp == 0) { break; } current = current.Right; } } return result; } } internal override bool InOrderTreeWalk(TreeWalkPredicate<T> action) { VersionCheck(); if (_root == null) { return true; } // The maximum height of a red-black tree is 2*lg(n+1). // See page 264 of "Introduction to algorithms" by Thomas H. Cormen Stack<Node> stack = new Stack<Node>(2 * (int)SortedSet<T>.Log2(_count + 1)); // this is not exactly right if count is out of date, but the stack can grow Node current = _root; while (current != null) { if (IsWithinRange(current.Item)) { stack.Push(current); current = current.Left; } else if (_lBoundActive && Comparer.Compare(_min, current.Item) > 0) { current = current.Right; } else { current = current.Left; } } while (stack.Count != 0) { current = stack.Pop(); if (!action(current)) { return false; } Node node = current.Right; while (node != null) { if (IsWithinRange(node.Item)) { stack.Push(node); node = node.Left; } else if (_lBoundActive && Comparer.Compare(_min, node.Item) > 0) { node = node.Right; } else { node = node.Left; } } } return true; } internal override bool BreadthFirstTreeWalk(TreeWalkPredicate<T> action) { VersionCheck(); if (_root == null) { return true; } Queue<Node> processQueue = new Queue<Node>(); processQueue.Enqueue(_root); Node current; while (processQueue.Count != 0) { current = processQueue.Dequeue(); if (IsWithinRange(current.Item) && !action(current)) { return false; } if (current.Left != null && (!_lBoundActive || Comparer.Compare(_min, current.Item) < 0)) { processQueue.Enqueue(current.Left); } if (current.Right != null && (!_uBoundActive || Comparer.Compare(_max, current.Item) > 0)) { processQueue.Enqueue(current.Right); } } return true; } internal override SortedSet<T>.Node FindNode(T item) { if (!IsWithinRange(item)) { return null; } VersionCheck(); #if DEBUG Debug.Assert(this.versionUpToDate() && _root == _underlying.FindRange(_min, _max)); #endif return base.FindNode(item); } // this does indexing in an inefficient way compared to the actual sortedset, but it saves a // lot of space internal override int InternalIndexOf(T item) { int count = -1; foreach (T i in this) { count++; if (Comparer.Compare(item, i) == 0) return count; } #if DEBUG Debug.Assert(this.versionUpToDate() && _root == _underlying.FindRange(_min, _max)); #endif return -1; } /// <summary> /// Checks whether this subset is out of date, and updates it if necessary. /// </summary> internal override void VersionCheck() => VersionCheckImpl(); private void VersionCheckImpl() { Debug.Assert(_underlying != null); if (_version != _underlying._version) { _root = _underlying.FindRange(_min, _max, _lBoundActive, _uBoundActive); _version = _underlying._version; _count = 0; InOrderTreeWalk(n => { _count++; return true; }); } } // This passes functionality down to the underlying tree, clipping edges if necessary // There's nothing gained by having a nested subset. May as well draw it from the base // Cannot increase the bounds of the subset, can only decrease it public override SortedSet<T> GetViewBetween(T lowerValue, T upperValue) { if (_lBoundActive && Comparer.Compare(_min, lowerValue) > 0) { throw new ArgumentOutOfRangeException(nameof(lowerValue)); } if (_uBoundActive && Comparer.Compare(_max, upperValue) < 0) { throw new ArgumentOutOfRangeException(nameof(upperValue)); } return (TreeSubSet)_underlying.GetViewBetween(lowerValue, upperValue); } #if DEBUG internal override void IntersectWithEnumerable(IEnumerable<T> other) { base.IntersectWithEnumerable(other); Debug.Assert(versionUpToDate() && _root == _underlying.FindRange(_min, _max)); } #endif void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) => GetObjectData(info, context); protected override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } void IDeserializationCallback.OnDeserialization(Object sender) { throw new PlatformNotSupportedException(); } protected override void OnDeserialization(Object sender) => throw new PlatformNotSupportedException(); } } }