context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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.ComponentModel; using System.Data; using System.Text; using System.Windows.Forms; using Multiverse.Lib.WorldMap; namespace Multiverse.Tools.TerrainAssembler { public partial class NewZoneDialog : Form { protected Image heightmap; protected int tilesWidth; protected int tilesHeight; public NewZoneDialog() { InitializeComponent(); mpsComboBox.SelectedIndex = 0; heightmapSizeValueLabel.Text = ""; zoneSizeValueLabel.Text = ""; } protected bool ValidateFilename(string name) { bool exists = System.IO.File.Exists(name); return exists; } protected void LoadHeightmap(string name) { heightmap = new Image(name); UpdateHeightmapInfo(); } protected void UpdateHeightmapInfo() { if (heightmap != null) { tilesWidth = ((heightmap.Width * MetersPerSample * WorldMap.oneMeter) + WorldMap.tileSize - 1 ) / WorldMap.tileSize; tilesHeight = ((heightmap.Height * MetersPerSample * WorldMap.oneMeter) + WorldMap.tileSize - 1 ) / WorldMap.tileSize; heightmapSizeValueLabel.Text = String.Format("{0}x{1}", heightmap.Width, heightmap.Height); zoneSizeValueLabel.Text = String.Format("{0}x{1}", tilesWidth, tilesHeight); } } #region Properties public Image Heightmap { get { return heightmap; } } public string ZoneName { get { return zoneNameTextBox.Text; } } public string HeightmapName { get { return heightmapImageTextBox.Text; } } public int MetersPerSample { get { return int.Parse(mpsComboBox.Text); } } public float MinTerrainHeight { get { return float.Parse(minHeightTextBox.Text) * 1000; } } public float MaxTerrainHeight { get { return float.Parse(maxHeightTextBox.Text) * 1000; } } public NewZoneData NewZoneData { get { return new NewZoneData(ZoneName, HeightmapName, Heightmap, MetersPerSample, tilesWidth, tilesHeight, MinTerrainHeight, MaxTerrainHeight); } } #endregion Properties private void zoneNameTextBox_Validating(object sender, CancelEventArgs e) { if ((zoneNameTextBox.Text == null) || (zoneNameTextBox.Text == "")) { e.Cancel = true; validationErrorProvider.SetError(zoneNameTextBox, "Zone name required"); } } private void zoneNameTextBox_Validated(object sender, EventArgs e) { validationErrorProvider.SetError(zoneNameTextBox, ""); } private void browseHeightmapButton_Click(object sender, EventArgs e) { using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "Select heightmap image"; dlg.DefaultExt = "png"; dlg.Filter = "PNG Image File (*.png)|*.png"; dlg.RestoreDirectory = true; if (dlg.ShowDialog() == DialogResult.OK) { heightmapImageTextBox.Text = dlg.FileName; if (ValidateFilename(dlg.FileName)) { LoadHeightmap(dlg.FileName); validationErrorProvider.SetError(heightmapImageTextBox, ""); createButton.Enabled = true; } else { validationErrorProvider.SetError(heightmapImageTextBox, "File does not exist"); createButton.Enabled = false; } } } } private void mpsComboBox_SelectedIndexChanged(object sender, EventArgs e) { UpdateHeightmapInfo(); } private void heightmapImageTextBox_Validating(object sender, CancelEventArgs e) { bool valid = ValidateFilename(heightmapImageTextBox.Text); if (!valid) { e.Cancel = true; validationErrorProvider.SetError(heightmapImageTextBox, "File does not exist"); createButton.Enabled = false; } } private void heightmapImageTextBox_Validated(object sender, EventArgs e) { LoadHeightmap(heightmapImageTextBox.Text); validationErrorProvider.SetError(heightmapImageTextBox, ""); createButton.Enabled = true; } private void minHeightTextBox_Validating(object sender, CancelEventArgs e) { float result; bool valid = float.TryParse(minHeightTextBox.Text, out result); if (!valid) { e.Cancel = true; validationErrorProvider.SetError(minHeightTextBox, "Invalid floating point value"); } } private void minHeightTextBox_Validated(object sender, EventArgs e) { validationErrorProvider.SetError(minHeightTextBox, ""); } private void maxHeightTextBox_Validating(object sender, CancelEventArgs e) { float result; bool valid = float.TryParse(maxHeightTextBox.Text, out result); if (!valid) { e.Cancel = true; validationErrorProvider.SetError(maxHeightTextBox, "Invalid floating point value"); } } private void maxHeightTextBox_Validated(object sender, EventArgs e) { validationErrorProvider.SetError(maxHeightTextBox, ""); } } public struct NewZoneData { public string ZoneName; public string HeightmapFilename; public Image Heightmap; public int MetersPerSample; public int TilesWidth; public int TilesHeight; public float MinHeight; public float MaxHeight; public NewZoneData(string zoneName, string heightmapFilename, Image heightmap, int metersPerSample, int tilesWidth, int tilesHeight, float minHeight, float maxHeight) { this.ZoneName = zoneName; this.HeightmapFilename = heightmapFilename; this.Heightmap = heightmap; this.MetersPerSample = metersPerSample; this.TilesWidth = tilesWidth; this.TilesHeight = tilesHeight; this.MinHeight = minHeight; this.MaxHeight = maxHeight; } } }
//----------------------------------------------------------------------- // <copyright company="CoApp Project"> // Copyright (c) 2010-2013 Garrett Serack and CoApp Contributors. // Contributors can be discovered using the 'git log' command. // All rights reserved. // </copyright> // <license> // The software is licensed under the Apache 2.0 License (the "License") // You may not use the software except in compliance with the License. // </license> //----------------------------------------------------------------------- namespace ClrPlus.Powershell.Provider.Utility { using System; using System.Linq; using System.Text.RegularExpressions; using Core.Collections; using Core.Extensions; public class Path { private static Regex UriRx = new Regex(@"^([a-zA-Z]+):([\\|/]*)(\w*.*)"); private const char Slash = '\\'; private static readonly char[] SingleSlashes = new[] { Slash }; private static readonly char[] Colon = new[] { ':' }; private static readonly char[] Slashes = new[] { '\\', '/' }; private string _hostName; public string HostAndPort { get { return string.IsNullOrEmpty(_hostName) ? string.Empty : (Port == null ? _hostName : _hostName + ":" + Port); } set { HostName = value; } } public string Container; public string[] Parts; public string SubPath; public string ParentPath; public string Name; public bool StartsWithSlash; public bool EndsWithSlash; public uint? Port; public string Scheme; public string OriginalPath; public string FilePath { get { if (Scheme != "file") { return ""; } if (IsUnc) { return @"\\{0}\{1}\{2}".format(HostName, Share, SubPath); } return @"{0}\{1}".format(Drive, SubPath); } } public string HostName { get { return _hostName; } set { var parts = value.Split(Colon, StringSplitOptions.RemoveEmptyEntries); _hostName = parts.Length > 0 ? parts[0] : string.Empty; if (parts.Length > 1) { uint p; uint.TryParse(parts[1], out p); if (p > 0) { Port = p; } } } } public string Share { get { return Container; } set { Container = value; } } public bool HasDrive { get { return HostAndPort.Length == 2 && HostAndPort[1] == ':'; } } public bool IsUnc {get; set;} public string Drive {get; set;} private static XDictionary<string, Path> _parsedLocationCache = new XDictionary<string, Path>(); public static Path ParseWithContainer(Uri url) { return ParseWithContainer(url.AbsoluteUri); } public static Path ParseWithContainer(string path) { if (_parsedLocationCache.ContainsKey(path)) { return _parsedLocationCache[path]; } var endswithslash = path.LastIndexOfAny(Slashes) == path.Length; var pathToParse = (path ?? string.Empty).UrlDecode(); var match = UriRx.Match(pathToParse); if (match.Success) { pathToParse = match.Groups[3].Value; } var segments = pathToParse.Split(Slashes, StringSplitOptions.RemoveEmptyEntries); return _parsedLocationCache.AddOrSet(path, new Path { HostAndPort = segments.Length > 0 ? segments[0] : string.Empty, Container = segments.Length > 1 ? segments[1] : string.Empty, Parts = segments.Length > 2 ? segments.Skip(2).ToArray() : new string[0], SubPath = segments.Length > 2 ? segments.Skip(2).Aggregate((current, each) => current + Slash + each) : string.Empty, ParentPath = segments.Length > 3 ? segments.Skip(2).Take(segments.Length - 3).Aggregate((current, each) => current + Slash + each) : string.Empty, Name = segments.Length > 2 ? segments.Last() : string.Empty, StartsWithSlash = pathToParse.IndexOfAny(Slashes) == 0, EndsWithSlash = endswithslash, // pathToParse.LastIndexOfAny(Slashes) == pathToParse.Length, Scheme = match.Success ? match.Groups[1].Value.ToLower() : string.Empty, OriginalPath = path, }); } public static Path ParseUrl(Uri url) { return ParseUrl(url.AbsoluteUri); } public static Path ParseUrl(string path) { if (_parsedLocationCache.ContainsKey(path)) { return _parsedLocationCache[path]; } var endswithslash = path.LastIndexOfAny(Slashes) == path.Length; var pathToParse = (path ?? string.Empty).UrlDecode(); var match = UriRx.Match(pathToParse); if (match.Success) { pathToParse = match.Groups[3].Value; } var segments = pathToParse.Split(Slashes, StringSplitOptions.RemoveEmptyEntries); return _parsedLocationCache.AddOrSet(path, new Path { HostName = segments.Length > 0 ? segments[0] : string.Empty, Container = string.Empty, Parts = segments.Length > 1 ? segments.Skip(1).ToArray() : new string[0], SubPath = segments.Length > 1 ? segments.Skip(1).Aggregate((current, each) => current + Slash + each) : string.Empty, ParentPath = segments.Length > 2 ? segments.Skip(1).Take(segments.Length - 2).Aggregate((current, each) => current + Slash + each) : string.Empty, Name = segments.Length > 1 ? segments.Last() : string.Empty, StartsWithSlash = pathToParse.IndexOfAny(Slashes) == 0, EndsWithSlash = endswithslash, //pathToParse.LastIndexOfAny(Slashes) == pathToParse.Length, Scheme = match.Success ? match.Groups[1].Value.ToLower() : string.Empty, OriginalPath = path, }); } public static Path ParsePath(string path) { if (_parsedLocationCache.ContainsKey(path)) { return _parsedLocationCache[path]; } var endswithslash = path.LastIndexOfAny(Slashes) == path.Length; var uri = new Uri((path ?? string.Empty).UrlDecode(), UriKind.RelativeOrAbsolute); var pathToParse = uri.IsAbsoluteUri ? uri.AbsoluteUri.UrlDecode() : uri.OriginalString; var match = UriRx.Match(pathToParse); if (match.Success) { pathToParse = match.Groups[3].Value; } var segments = pathToParse.Split(Slashes, StringSplitOptions.RemoveEmptyEntries); return uri.IsAbsoluteUri ? uri.IsUnc ? _parsedLocationCache.AddOrSet(path, new Path { HostName = segments.Length > 0 ? segments[0] : string.Empty, Share = segments.Length > 1 ? segments[1] : string.Empty, Parts = segments.Length > 2 ? segments.Skip(2).ToArray() : new string[0], SubPath = segments.Length > 2 ? segments.Skip(2).Aggregate((current, each) => current + Slash + each) : string.Empty, ParentPath = segments.Length > 3 ? segments.Skip(2).Take(segments.Length - 2).Aggregate((current, each) => current + Slash + each) : string.Empty, Name = segments.Length > 2 ? segments.Last() : string.Empty, StartsWithSlash = endswithslash, // pathToParse.IndexOfAny(Slashes) == 0, EndsWithSlash = pathToParse.LastIndexOfAny(Slashes) == pathToParse.Length, Scheme = match.Success ? match.Groups[1].Value.ToLower() : string.Empty, IsUnc = true, }) : _parsedLocationCache.AddOrSet(path, new Path { Drive = segments.Length > 0 ? segments[0] : string.Empty, Share = string.Empty, Parts = segments.Length > 1 ? segments.Skip(1).ToArray() : new string[0], SubPath = segments.Length > 1 ? segments.Skip(1).Aggregate((current, each) => current + Slash + each) : string.Empty, ParentPath = segments.Length > 2 ? segments.Skip(1).Take(segments.Length - 2).Aggregate((current, each) => current + Slash + each) : string.Empty, Name = segments.Length > 1 ? segments.Last() : string.Empty, StartsWithSlash = pathToParse.IndexOfAny(Slashes) == 0, EndsWithSlash = endswithslash, // pathToParse.LastIndexOfAny(Slashes) == pathToParse.Length, Scheme = match.Success ? match.Groups[1].Value.ToLower() : string.Empty, IsUnc = false, OriginalPath = uri.AbsoluteUri.UrlDecode(), }) : _parsedLocationCache.AddOrSet(path, new Path { Drive = string.Empty, Share = string.Empty, Parts = segments.Length > 0 ? segments.ToArray() : new string[0], SubPath = segments.Length > 0 ? segments.Aggregate((current, each) => current + Slash + each) : string.Empty, ParentPath = segments.Length > 1 ? segments.Take(segments.Length - 2).Aggregate((current, each) => current + Slash + each) : string.Empty, Name = segments.Length > 0 ? segments.Last() : string.Empty, StartsWithSlash = pathToParse.IndexOfAny(Slashes) == 0, EndsWithSlash = endswithslash, // pathToParse.LastIndexOfAny(Slashes) == pathToParse.Length, Scheme = match.Success ? match.Groups[1].Value.ToLower() : string.Empty, IsUnc = false, OriginalPath = uri.OriginalString, }); } public void Validate() { if (Parts == null) { // not set from original creation SubPath = SubPath ?? string.Empty; Parts = SubPath.Split(Slashes, StringSplitOptions.RemoveEmptyEntries); ParentPath = Parts.Length > 1 ? Parts.Take(Parts.Length - 1).Aggregate((current, each) => current + Slash + each) : string.Empty; Name = Parts.Length > 0 ? Parts.Last() : string.Empty; } } public bool IsSubpath(Path childPath) { if (Parts.Length >= childPath.Parts.Length) { return false; } return !Parts.Where((t, i) => t != childPath.Parts[i]).Any(); } } }
//////////////////////////////////////////////////////////////// // // // Neoforce Controls // // // //////////////////////////////////////////////////////////////// // // // File: Container.cs // // // // Version: 0.7 // // // // Date: 11/09/2010 // // // // Author: Tom Shane // // // //////////////////////////////////////////////////////////////// // // // Copyright (c) by Tom Shane // // // //////////////////////////////////////////////////////////////// #region //// Using ///////////// //////////////////////////////////////////////////////////////////////////// using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; //////////////////////////////////////////////////////////////////////////// #endregion namespace TomShane.Neoforce.Controls { public struct ScrollBarValue { public int Vertical; public int Horizontal; } public class Container: ClipControl { #region //// Fields //////////// //////////////////////////////////////////////////////////////////////////// private ScrollBar sbVert; private ScrollBar sbHorz; private MainMenu mainMenu; private ToolBarPanel toolBarPanel; private StatusBar statusBar; private bool autoScroll = false; private Control defaultControl = null; //////////////////////////////////////////////////////////////////////////// #endregion #region //// Properties //////// //////////////////////////////////////////////////////////////////////////// public virtual ScrollBarValue ScrollBarValue { get { ScrollBarValue scb = new ScrollBarValue(); scb.Vertical = (sbVert != null ? sbVert.Value : 0); scb.Horizontal = (sbHorz != null ? sbHorz.Value : 0); return scb; } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public override bool Visible { get { return base.Visible; } set { if (value) { if (DefaultControl != null) { DefaultControl.Focused = true; } } base.Visible = value; } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual Control DefaultControl { get { return defaultControl; } set { defaultControl = value; } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual bool AutoScroll { get { return autoScroll; } set { autoScroll = value; } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual MainMenu MainMenu { get { return mainMenu; } set { if (mainMenu != null) { mainMenu.Resize -= Bars_Resize; Remove(mainMenu); } mainMenu = value; if (mainMenu != null) { Add(mainMenu, false); mainMenu.Resize += Bars_Resize; } AdjustMargins(); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual ToolBarPanel ToolBarPanel { get { return toolBarPanel; } set { if (toolBarPanel != null) { toolBarPanel.Resize -= Bars_Resize; Remove(toolBarPanel); } toolBarPanel = value; if (toolBarPanel != null) { Add(toolBarPanel, false); toolBarPanel.Resize += Bars_Resize; } AdjustMargins(); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual StatusBar StatusBar { get { return statusBar; } set { if (statusBar != null) { statusBar.Resize -= Bars_Resize; Remove(statusBar); } statusBar = value; if (statusBar != null) { Add(statusBar, false); statusBar.Resize += Bars_Resize; } AdjustMargins(); } } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Constructors ////// //////////////////////////////////////////////////////////////////////////// public Container(Manager manager): base(manager) { sbVert = new ScrollBar(manager, Orientation.Vertical); sbVert.Init(); sbVert.Detached = false; sbVert.Anchor = Anchors.Top | Anchors.Right | Anchors.Bottom; sbVert.ValueChanged += new EventHandler(ScrollBarValueChanged); sbVert.Range = 0; sbVert.PageSize = 0; sbVert.Value = 0; sbVert.Visible = false; sbHorz = new ScrollBar(manager, Orientation.Horizontal); sbHorz.Init(); sbHorz.Detached = false; sbHorz.Anchor = Anchors.Right | Anchors.Left | Anchors.Bottom; sbHorz.ValueChanged += new EventHandler(ScrollBarValueChanged); sbHorz.Range = 0; sbHorz.PageSize = 0; sbHorz.Value = 0; sbHorz.Visible = false; Add(sbVert, false); Add(sbHorz, false); } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Methods /////////// //////////////////////////////////////////////////////////////////////////// public override void Init() { base.Init(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected internal override void InitSkin() { base.InitSkin(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// private void Bars_Resize(object sender, ResizeEventArgs e) { AdjustMargins(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void AdjustMargins() { Margins m = Skin.ClientMargins; if (this.GetType() != typeof(Container)) { m = ClientMargins; } if (mainMenu != null && mainMenu.Visible) { if (!mainMenu.Initialized) mainMenu.Init(); mainMenu.Left = m.Left; mainMenu.Top = m.Top; mainMenu.Width = Width - m.Horizontal; mainMenu.Anchor = Anchors.Left | Anchors.Top | Anchors.Right; m.Top += mainMenu.Height; } if (toolBarPanel != null && toolBarPanel.Visible) { if (!toolBarPanel.Initialized) toolBarPanel.Init(); toolBarPanel.Left = m.Left; toolBarPanel.Top = m.Top; toolBarPanel.Width = Width - m.Horizontal; toolBarPanel.Anchor = Anchors.Left | Anchors.Top | Anchors.Right; m.Top += toolBarPanel.Height; } if (statusBar != null && statusBar.Visible) { if (!statusBar.Initialized) statusBar.Init(); statusBar.Left = m.Left; statusBar.Top = Height - m.Bottom - statusBar.Height; statusBar.Width = Width - m.Horizontal; statusBar.Anchor = Anchors.Left | Anchors.Bottom | Anchors.Right; m.Bottom += statusBar.Height; } if (sbVert != null && sbVert.Visible) { m.Right += (sbVert.Width + 2); } if (sbHorz != null && sbHorz.Visible) { m.Bottom += (sbHorz.Height + 2); } ClientMargins = m; PositionScrollBars(); base.AdjustMargins(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public override void Add(Control control, bool client) { base.Add(control, client); CalcScrolling(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected internal override void Update(GameTime gameTime) { base.Update(gameTime); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void DrawControl(Renderer renderer, Rectangle rect, GameTime gameTime) { base.DrawControl(renderer, rect, gameTime); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected internal override void OnSkinChanged(EventArgs e) { base.OnSkinChanged(e); if (sbVert != null && sbHorz != null) { sbVert.Visible = false; sbHorz.Visible = false; CalcScrolling(); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// private void PositionScrollBars() { if (sbVert != null) { sbVert.Left = ClientLeft + ClientWidth + 1; sbVert.Top = ClientTop + 1; int m = (sbHorz != null && sbHorz.Visible) ? 0 : 2; sbVert.Height = ClientArea.Height - m; sbVert.Range = ClientArea.VirtualHeight; sbVert.PageSize = ClientArea.ClientHeight; } if (sbHorz != null) { sbHorz.Left = ClientLeft + 1; sbHorz.Top = ClientTop + ClientHeight + 1; int m = (sbVert != null && sbVert.Visible) ? 0 : 2; sbHorz.Width = ClientArea.Width - m; sbHorz.Range = ClientArea.VirtualWidth; sbHorz.PageSize = ClientArea.ClientWidth; } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// private void CalcScrolling() { if (sbVert != null && autoScroll) { bool vis = sbVert.Visible; sbVert.Visible = ClientArea.VirtualHeight > ClientArea.ClientHeight; if (ClientArea.VirtualHeight <= ClientArea.ClientHeight) sbVert.Value = 0; if (vis != sbVert.Visible) { if (!sbVert.Visible) { foreach (Control c in ClientArea.Controls) { c.TopModifier = 0; c.Invalidate(); } } AdjustMargins(); } PositionScrollBars(); foreach (Control c in ClientArea.Controls) { c.TopModifier = -sbVert.Value; c.Invalidate(); } } if (sbHorz != null && autoScroll) { bool vis = sbHorz.Visible; sbHorz.Visible = ClientArea.VirtualWidth > ClientArea.ClientWidth; if (ClientArea.VirtualWidth <= ClientArea.ClientWidth) sbHorz.Value = 0; if (vis != sbHorz.Visible) { if (!sbHorz.Visible) { foreach (Control c in ClientArea.Controls) { c.LeftModifier = 0; sbVert.Refresh(); c.Invalidate(); } } AdjustMargins(); } PositionScrollBars(); foreach (Control c in ClientArea.Controls) { c.LeftModifier = -sbHorz.Value; sbHorz.Refresh(); c.Invalidate(); } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void ScrollTo(int x, int y) { sbVert.Value = y; sbHorz.Value = x; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void ScrollTo(Control control) { if (control != null && ClientArea != null && ClientArea.Contains(control, true)) { if (control.AbsoluteTop + control.Height > ClientArea.AbsoluteTop + ClientArea.Height) { sbVert.Value = sbVert.Value + control.AbsoluteTop - ClientArea.AbsoluteTop - sbVert.PageSize + control.Height; } else if (control.AbsoluteTop < ClientArea.AbsoluteTop) { sbVert.Value = sbVert.Value + control.AbsoluteTop - ClientArea.AbsoluteTop; } if (control.AbsoluteLeft + control.Width > ClientArea.AbsoluteLeft + ClientArea.Width) { sbHorz.Value = sbHorz.Value + control.AbsoluteLeft - ClientArea.AbsoluteLeft - sbHorz.PageSize + control.Width; } else if (control.AbsoluteLeft < ClientArea.AbsoluteLeft) { sbHorz.Value = sbHorz.Value + control.AbsoluteLeft - ClientArea.AbsoluteLeft; } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// void ScrollBarValueChanged(object sender, EventArgs e) { CalcScrolling(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void OnResize(ResizeEventArgs e) { base.OnResize(e); CalcScrolling(); // Crappy fix to certain scrolling issue //if (sbVert != null) sbVert.Value -= 1; //if (sbHorz != null) sbHorz.Value -= 1; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public override void Invalidate() { base.Invalidate(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void OnClick(EventArgs e) { MouseEventArgs ex = e as MouseEventArgs; ex.Position = new Point(ex.Position.X + sbHorz.Value, ex.Position.Y + sbVert.Value); base.OnClick(e); } //////////////////////////////////////////////////////////////////////////// #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 Xunit; using Xunit.Abstractions; using System.IO; using System.Xml.Schema; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_GlobalTypes", Desc = "")] public class TC_SchemaSet_GlobalTypes : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_GlobalTypes(ITestOutputHelper output) { _output = output; } public XmlSchema GetSchema(string ns, string type1, string type2) { string xsd = string.Empty; if (ns.Equals(string.Empty)) xsd = "<schema xmlns='http://www.w3.org/2001/XMLSchema'><complexType name='" + type1 + "'><sequence><element name='local'/></sequence></complexType><simpleType name='" + type2 + "'><restriction base='int'/></simpleType></schema>"; else xsd = "<schema xmlns='http://www.w3.org/2001/XMLSchema' targetNamespace='" + ns + "'><complexType name='" + type1 + "'><sequence><element name='local'/></sequence></complexType><simpleType name='" + type2 + "'><restriction base='int'/></simpleType></schema>"; XmlSchema schema = XmlSchema.Read(new StringReader(xsd), null); return schema; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v1 - GlobalTypes on empty collection")] [InlineData()] [Theory] public void v1() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchemaObjectTable table = sc.GlobalTypes; CError.Compare(table == null, false, "Count"); return; } //----------------------------------------------------------------------------------- // params is a pair of the following info: (namaespace, type1 type2) two schemas are made from this info //[Variation(Desc = "v2.1 - GlobalTypes with set with two schemas, both without NS", Params = new object[] { "", "t1", "t2", "", "t3", "t4" })] [InlineData("", "t1", "t2", "", "t3", "t4")] //[Variation(Desc = "v2.2 - GlobalTypes with set with two schemas, one without NS one with NS", Params = new object[] { "a", "t1", "t2", "", "t3", "t4" })] [InlineData("a", "t1", "t2", "", "t3", "t4")] //[Variation(Desc = "v2.2 - GlobalTypes with set with two schemas, both with NS", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4" })] [InlineData("a", "t1", "t2", "b", "t3", "t4")] [Theory] public void v2(object param0, object param1, object param2, object param3, object param4, object param5) { string ns1 = param0.ToString(); string ns2 = param3.ToString(); string type1 = param1.ToString(); string type2 = param2.ToString(); string type3 = param4.ToString(); string type4 = param5.ToString(); XmlSchema s1 = GetSchema(ns1, type1, type2); XmlSchema s2 = GetSchema(ns2, type3, type4); XmlSchemaSet ss = new XmlSchemaSet(); ss.Add(s1); CError.Compare(ss.GlobalTypes.Count, 0, "Types Count after add"); ss.Compile(); ss.Add(s2); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after add/compile"); //+1 for anyType ss.Compile(); //Verify CError.Compare(ss.GlobalTypes.Count, 5, "Types Count after add/compile/add/compile"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns1)), true, "Contains2"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type3, ns2)), true, "Contains3"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type4, ns2)), true, "Contains4"); //Now reprocess one schema and check ss.Reprocess(s1); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after repr"); //+1 for anyType ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 5, "Types Count after repr/comp"); //+1 for anyType //Now Remove one schema and check ss.Remove(s1); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after remove"); ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after remove/comp"); return; } // params is a pair of the following info: (namaespace, type1 type2)*, doCompile? //[Variation(Desc = "v3.1 - GlobalTypes with a set having schema (nons) to another set with schema(nons)", Params = new object[] { "", "t1", "t2", "", "t3", "t4", true })] [InlineData("", "t1", "t2", "", "t3", "t4", true)] //[Variation(Desc = "v3.2 - GlobalTypes with a set having schema (ns) to another set with schema(nons)", Params = new object[] { "a", "t1", "t2", "", "t3", "t4", true })] [InlineData("a", "t1", "t2", "", "t3", "t4", true)] //[Variation(Desc = "v3.3 - GlobalTypes with a set having schema (nons) to another set with schema(ns)", Params = new object[] { "", "t1", "t2", "a", "t3", "t4", true })] [InlineData("", "t1", "t2", "a", "t3", "t4", true)] //[Variation(Desc = "v3.4 - GlobalTypes with a set having schema (ns) to another set with schema(ns)", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4", true })] [InlineData("a", "t1", "t2", "b", "t3", "t4", true)] //[Variation(Desc = "v3.5 - GlobalTypes with a set having schema (nons) to another set with schema(nons), no compile", Params = new object[] { "", "t1", "t2", "", "t3", "t4", false })] [InlineData("", "t1", "t2", "", "t3", "t4", false)] //[Variation(Desc = "v3.6 - GlobalTypes with a set having schema (ns) to another set with schema(nons), no compile", Params = new object[] { "a", "t1", "t2", "", "t3", "t4", false })] [InlineData("a", "t1", "t2", "", "t3", "t4", false)] //[Variation(Desc = "v3.7 - GlobalTypes with a set having schema (nons) to another set with schema(ns), no compile", Params = new object[] { "", "t1", "t2", "a", "t3", "t4", false })] [InlineData("", "t1", "t2", "a", "t3", "t4", false)] //[Variation(Desc = "v3.8 - GlobalTypes with a set having schema (ns) to another set with schema(ns), no compile", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4", false })] [InlineData("a", "t1", "t2", "b", "t3", "t4", false)] [Theory] public void v3(object param0, object param1, object param2, object param3, object param4, object param5, object param6) { string ns1 = param0.ToString(); string ns2 = param3.ToString(); string type1 = param1.ToString(); string type2 = param2.ToString(); string type3 = param4.ToString(); string type4 = param5.ToString(); bool doCompile = (bool)param6; XmlSchema s1 = GetSchema(ns1, type1, type2); XmlSchema s2 = GetSchema(ns2, type3, type4); XmlSchemaSet ss1 = new XmlSchemaSet(); XmlSchemaSet ss2 = new XmlSchemaSet(); ss1.Add(s1); ss1.Compile(); ss2.Add(s2); if (doCompile) ss2.Compile(); // add one schemaset to another ss1.Add(ss2); if (!doCompile) ss1.Compile(); //Verify CError.Compare(ss1.GlobalTypes.Count, 5, "Types Count after add/comp"); //+1 for anyType CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type2, ns1)), true, "Contains2"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type3, ns2)), true, "Contains3"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type4, ns2)), true, "Contains4"); //Now reprocess one schema and check ss1.Reprocess(s1); CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count repr"); //+1 for anyType ss1.Compile(); CError.Compare(ss1.GlobalTypes.Count, 5, "Types Count repr/comp"); //+1 for anyType //Now Remove one schema and check ss1.Remove(s1); CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count after remove"); ss1.Compile(); CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count after rem/comp"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v4.1 - GlobalTypes with set having one which imports another, remove one", Priority = 1, Params = new object[] { "import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B" })] [InlineData("import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B")] //[Variation(Desc = "v4.2 - GlobalTypes with set having one which imports another, remove one", Priority = 1, Params = new object[] { "import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B" })] [InlineData("import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B")] [Theory] public void v4(object param0, object param1, object param2, object param3, object param4) { string uri1 = param0.ToString(); string ns1 = param1.ToString(); string type1 = param2.ToString(); string ns2 = param3.ToString(); string type2 = param4.ToString(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); XmlSchema schema1 = ss.Add(null, Path.Combine(TestData._Root, uri1)); ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), true, "Contains2"); //get the SOM for the imported schema foreach (XmlSchema s in ss.Schemas(ns2)) { ss.Remove(s); } ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 2, "Types Count after Remove"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), false, "Contains2"); return; } //[Variation(Desc = "v5.1 - GlobalTypes with set having one which imports another, then removerecursive", Priority = 1, Params = new object[] { "import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B" })] [InlineData("import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B")] //[Variation(Desc = "v5.2 - GlobalTypes with set having one which imports another, then removerecursive", Priority = 1, Params = new object[] { "import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B" })] [InlineData("import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B")] [Theory] public void v5(object param0, object param1, object param2, object param3, object param4) { string uri1 = param0.ToString(); string ns1 = param1.ToString(); string type1 = param2.ToString(); string ns2 = param3.ToString(); string type2 = param4.ToString(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, Path.Combine(TestData._Root, "xsdauthor.xsd")); XmlSchema schema1 = ss.Add(null, Path.Combine(TestData._Root, uri1)); ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), true, "Contains2"); ss.RemoveRecursive(schema1); // should not need to compile for RemoveRecursive to take effect CError.Compare(ss.GlobalTypes.Count, 1, "Types Count"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), false, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), false, "Contains2"); return; } //----------------------------------------------------------------------------------- //REGRESSIONS //[Variation(Desc = "v100 - XmlSchemaSet: Components are not added to the global tabels if it is already compiled", Priority = 1)] [InlineData()] [Theory] public void v100() { try { // anytype t1 t2 XmlSchema schema1 = XmlSchema.Read(new StringReader("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='a'><xs:element name='e1' type='xs:anyType'/><xs:complexType name='t1'/><xs:complexType name='t2'/></xs:schema>"), null); // anytype t3 t4 XmlSchema schema2 = XmlSchema.Read(new StringReader("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' ><xs:element name='e1' type='xs:anyType'/><xs:complexType name='t3'/><xs:complexType name='t4'/></xs:schema>"), null); XmlSchemaSet ss1 = new XmlSchemaSet(); XmlSchemaSet ss2 = new XmlSchemaSet(); ss1.Add(schema1); ss2.Add(schema2); ss2.Compile(); ss1.Add(ss2); ss1.Compile(); CError.Compare(ss1.GlobalTypes.Count, 5, "Count"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName("t1", "a")), true, "Contains"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName("t2", "a")), true, "Contains"); } catch (Exception e) { _output.WriteLine(e.Message); Assert.True(false); } return; } } }
using System; using System.Collections; /// <summary> /// System.Math.Acos(System.Double) /// </summary> public class MathAcos { public static int Main(string[] args) { MathAcos Acos = new MathAcos(); TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Acos(System.Double)..."); if (Acos.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; //TestLibrary.TestFramework.LogInformation("[Negtive]"); //retVal = NegTest1() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Verify the value of Arccos(-1) is Math.PI..."); try { double angle = Math.Acos(-1); if (!MathTestLib.DoubleIsWithinEpsilon(angle ,Math.PI)) { TestLibrary.TestFramework.LogError("001","Expected Math.Acos(-1) = " + Math.PI.ToString() +", received "+ angle.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002","Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Verify the value of Arccos(0) is Math.PI/2..."); try { double angle = Math.Acos(0); if (!MathTestLib.DoubleIsWithinEpsilon(angle, Math.PI/2)) { TestLibrary.TestFramework.LogError("003", "Expected pi/2, got " + angle.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Verify the value of Arccos(1) is 0..."); try { double angle = Math.Acos(1); if (!MathTestLib.DoubleIsWithinEpsilon(angle ,0)) { TestLibrary.TestFramework.LogError("005", "Expected 1, got " + angle.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Verify the value of Arccos(0.5) is Math.PI/3..."); try { double angle = Math.Acos(0.5); if (!MathTestLib.DoubleIsWithinEpsilon(angle, 1.0471975511965979)) { TestLibrary.TestFramework.LogError("007","Expected 1.0471975511965979, got "+angle.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Verify the value of Arccos(-0.5) is 2*Math.PI/3..."); try { double angle = Math.Acos(-0.5); if (!MathTestLib.DoubleIsWithinEpsilon(angle, 2.0943951023931957)) { TestLibrary.TestFramework.LogError("009", "Expected: 2.09439510239319573, actual: " + angle.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Verify the value of Arccos(Math.Sqrt(3)/2) is Math.PI/6..."); try { double angle = Math.Acos(Math.Sqrt(3)/2); if (!MathTestLib.DoubleIsWithinEpsilon(angle, 0.52359877559829893)) { TestLibrary.TestFramework.LogError("011", "Expected: 0.52359877559829893, actual: " + angle.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7: Verify the value of Arccos(-Math.Sqrt(3)/2) is 5*Math.PI/6..."); try { double angle = Math.Acos(-Math.Sqrt(3) / 2); if (!MathTestLib.DoubleIsWithinEpsilon(angle, 2.6179938779914944)) { TestLibrary.TestFramework.LogError("013", "Expected: 2.617993877991494, actual: " + angle.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Samples.RegistrationList.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// 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.Reflection; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Diagnostics; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using System.Threading; using System.Security; using System.Globalization; namespace System.ServiceModel.Diagnostics { internal static class TraceUtility { private const string ActivityIdKey = "ActivityId"; private const string AsyncOperationActivityKey = "AsyncOperationActivity"; private const string AsyncOperationStartTimeKey = "AsyncOperationStartTime"; private static long s_messageNumber = 0; public const string E2EActivityId = "E2EActivityId"; public const string TraceApplicationReference = "TraceApplicationReference"; public static Func<Action<AsyncCallback, IAsyncResult>> asyncCallbackGenerator; static internal void AddActivityHeader(Message message) { try { ActivityIdHeader activityIdHeader = new ActivityIdHeader(TraceUtility.ExtractActivityId(message)); activityIdHeader.AddTo(message); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } } } static internal void AddAmbientActivityToMessage(Message message) { try { ActivityIdHeader activityIdHeader = new ActivityIdHeader(DiagnosticTraceBase.ActivityId); activityIdHeader.AddTo(message); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } } } static internal void CopyActivity(Message source, Message destination) { if (DiagnosticUtility.ShouldUseActivity) { TraceUtility.SetActivity(destination, TraceUtility.ExtractActivity(source)); } } internal static long GetUtcBasedDurationForTrace(long startTicks) { if (startTicks > 0) { TimeSpan elapsedTime = new TimeSpan(DateTime.UtcNow.Ticks - startTicks); return (long)elapsedTime.TotalMilliseconds; } return 0; } internal static ServiceModelActivity ExtractActivity(Message message) { ServiceModelActivity retval = null; if ((DiagnosticUtility.ShouldUseActivity || TraceUtility.ShouldPropagateActivityGlobal) && (message != null) && (message.State != MessageState.Closed)) { object property; if (message.Properties.TryGetValue(TraceUtility.ActivityIdKey, out property)) { retval = property as ServiceModelActivity; } } return retval; } internal static Guid ExtractActivityId(Message message) { if (TraceUtility.MessageFlowTracingOnly) { return ActivityIdHeader.ExtractActivityId(message); } ServiceModelActivity activity = ExtractActivity(message); return activity == null ? Guid.Empty : activity.Id; } internal static Guid GetReceivedActivityId(OperationContext operationContext) { object activityIdFromProprties; if (!operationContext.IncomingMessageProperties.TryGetValue(E2EActivityId, out activityIdFromProprties)) { return TraceUtility.ExtractActivityId(operationContext.IncomingMessage); } else { return (Guid)activityIdFromProprties; } } internal static ServiceModelActivity ExtractAndRemoveActivity(Message message) { ServiceModelActivity retval = TraceUtility.ExtractActivity(message); if (retval != null) { // If the property is just removed, the item is disposed and we don't want the thing // to be disposed of. message.Properties[TraceUtility.ActivityIdKey] = false; } return retval; } internal static void ProcessIncomingMessage(Message message, EventTraceActivity eventTraceActivity) { ServiceModelActivity activity = ServiceModelActivity.Current; if (activity != null && DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity incomingActivity = TraceUtility.ExtractActivity(message); if (null != incomingActivity && incomingActivity.Id != activity.Id) { using (ServiceModelActivity.BoundOperation(incomingActivity)) { if (null != FxTrace.Trace) { FxTrace.Trace.TraceTransfer(activity.Id); } } } TraceUtility.SetActivity(message, activity); } TraceUtility.MessageFlowAtMessageReceived(message, null, eventTraceActivity, true); if (MessageLogger.LogMessagesAtServiceLevel) { MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelReceiveReply | MessageLoggingSource.LastChance); } } internal static void ProcessOutgoingMessage(Message message, EventTraceActivity eventTraceActivity) { ServiceModelActivity activity = ServiceModelActivity.Current; if (DiagnosticUtility.ShouldUseActivity) { TraceUtility.SetActivity(message, activity); } if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity) { TraceUtility.AddAmbientActivityToMessage(message); } TraceUtility.MessageFlowAtMessageSent(message, eventTraceActivity); if (MessageLogger.LogMessagesAtServiceLevel) { MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelSendRequest | MessageLoggingSource.LastChance); } } internal static void SetActivity(Message message, ServiceModelActivity activity) { if (DiagnosticUtility.ShouldUseActivity && message != null && message.State != MessageState.Closed) { message.Properties[TraceUtility.ActivityIdKey] = activity; } } internal static void TraceDroppedMessage(Message message, EndpointDispatcher dispatcher) { } private static string GenerateMsdnTraceCode(int traceCode) { int group = (int)(traceCode & 0xFFFF0000); string terminatorUri = null; switch (group) { case TraceCode.Administration: terminatorUri = "System.ServiceModel.Administration"; break; case TraceCode.Channels: terminatorUri = "System.ServiceModel.Channels"; break; case TraceCode.ComIntegration: terminatorUri = "System.ServiceModel.ComIntegration"; break; case TraceCode.Diagnostics: terminatorUri = "System.ServiceModel.Diagnostics"; break; case TraceCode.PortSharing: terminatorUri = "System.ServiceModel.PortSharing"; break; case TraceCode.Security: terminatorUri = "System.ServiceModel.Security"; break; case TraceCode.Serialization: terminatorUri = "System.Runtime.Serialization"; break; case TraceCode.ServiceModel: case TraceCode.ServiceModelTransaction: terminatorUri = "System.ServiceModel"; break; default: terminatorUri = string.Empty; break; } return string.Empty; } internal static Exception ThrowHelperError(Exception exception, Message message) { return exception; } internal static Exception ThrowHelperError(Exception exception, Guid activityId, object source) { return exception; } internal static Exception ThrowHelperWarning(Exception exception, Message message) { return exception; } internal static ArgumentException ThrowHelperArgument(string paramName, string message, Message msg) { return (ArgumentException)TraceUtility.ThrowHelperError(new ArgumentException(message, paramName), msg); } internal static ArgumentNullException ThrowHelperArgumentNull(string paramName, Message message) { return (ArgumentNullException)TraceUtility.ThrowHelperError(new ArgumentNullException(paramName), message); } internal static string CreateSourceString(object source) { return source.GetType().ToString() + "/" + source.GetHashCode().ToString(CultureInfo.CurrentCulture); } internal static void TraceHttpConnectionInformation(string localEndpoint, string remoteEndpoint, object source) { } internal static void TraceUserCodeException(Exception e, MethodInfo method) { } static TraceUtility() { //Maintain the order of calls TraceUtility.SetEtwProviderId(); TraceUtility.SetEndToEndTracingFlags(); } [Fx.Tag.SecurityNote(Critical = "Calls critical method DiagnosticSection.UnsafeGetSection.", Safe = "Doesn't leak config section instance, just reads and stores bool values.")] [SecuritySafeCritical] private static void SetEndToEndTracingFlags() { } static public long RetrieveMessageNumber() { return Interlocked.Increment(ref TraceUtility.s_messageNumber); } static public bool PropagateUserActivity { get { return TraceUtility.ShouldPropagateActivity && TraceUtility.PropagateUserActivityCore; } } // Most of the time, shouldPropagateActivity will be false. // This property will rarely be executed as a result. private static bool PropagateUserActivityCore { [MethodImpl(MethodImplOptions.NoInlining)] get { return false; } } static internal string GetCallerInfo(OperationContext context) { return "null"; } [Fx.Tag.SecurityNote(Critical = "Calls critical method DiagnosticSection.UnsafeGetSection.", Safe = "Doesn't leak config section instance, just reads and stores string values for Guid")] [SecuritySafeCritical] static internal void SetEtwProviderId() { } static internal void SetActivityId(MessageProperties properties) { Guid activityId; if ((null != properties) && properties.TryGetValue(TraceUtility.E2EActivityId, out activityId)) { DiagnosticTraceBase.ActivityId = activityId; } } static internal bool ShouldPropagateActivity { get { return false; } } static internal bool ShouldPropagateActivityGlobal { get { return false; } } static internal bool ActivityTracing { get { return false; } } static internal bool MessageFlowTracing { get { return false; } } static internal bool MessageFlowTracingOnly { get { return false; } } static internal void MessageFlowAtMessageSent(Message message, EventTraceActivity eventTraceActivity) { if (TraceUtility.MessageFlowTracing) { Guid activityId; Guid correlationId; bool activityIdFound = ActivityIdHeader.ExtractActivityAndCorrelationId(message, out activityId, out correlationId); if (TraceUtility.MessageFlowTracingOnly) { if (activityIdFound && activityId != DiagnosticTraceBase.ActivityId) { DiagnosticTraceBase.ActivityId = activityId; } } if (WcfEventSource.Instance.MessageSentToTransportIsEnabled()) { WcfEventSource.Instance.MessageSentToTransport(eventTraceActivity, correlationId); } } } static internal void MessageFlowAtMessageReceived(Message message, OperationContext context, EventTraceActivity eventTraceActivity, bool createNewActivityId) { if (TraceUtility.MessageFlowTracing) { Guid activityId; Guid correlationId; bool activityIdFound = ActivityIdHeader.ExtractActivityAndCorrelationId(message, out activityId, out correlationId); if (TraceUtility.MessageFlowTracingOnly) { if (createNewActivityId) { if (!activityIdFound) { activityId = Guid.NewGuid(); activityIdFound = true; } //message flow tracing only - start fresh DiagnosticTraceBase.ActivityId = Guid.Empty; } if (activityIdFound) { FxTrace.Trace.SetAndTraceTransfer(activityId, !createNewActivityId); } } if (WcfEventSource.Instance.MessageReceivedFromTransportIsEnabled()) { if (context == null) { context = OperationContext.Current; } WcfEventSource.Instance.MessageReceivedFromTransport(eventTraceActivity, correlationId, TraceUtility.GetAnnotation(context)); } } } internal static string GetAnnotation(OperationContext context) { // Desktop obtains annotation from host return String.Empty; } internal static void TransferFromTransport(Message message) { if (message != null && DiagnosticUtility.ShouldUseActivity) { Guid guid = Guid.Empty; // Only look if we are allowing user propagation if (TraceUtility.ShouldPropagateActivity) { guid = ActivityIdHeader.ExtractActivityId(message); } if (guid == Guid.Empty) { guid = Guid.NewGuid(); } ServiceModelActivity activity = null; bool emitStart = true; if (ServiceModelActivity.Current != null) { if ((ServiceModelActivity.Current.Id == guid) || (ServiceModelActivity.Current.ActivityType == ActivityType.ProcessAction)) { activity = ServiceModelActivity.Current; emitStart = false; } else if (ServiceModelActivity.Current.PreviousActivity != null && ServiceModelActivity.Current.PreviousActivity.Id == guid) { activity = ServiceModelActivity.Current.PreviousActivity; emitStart = false; } } if (activity == null) { activity = ServiceModelActivity.CreateActivity(guid); } if (DiagnosticUtility.ShouldUseActivity) { if (emitStart) { if (null != FxTrace.Trace) { FxTrace.Trace.TraceTransfer(guid); } ServiceModelActivity.Start(activity, SR.Format(SR.ActivityProcessAction, message.Headers.Action), ActivityType.ProcessAction); } } message.Properties[TraceUtility.ActivityIdKey] = activity; } } static internal void UpdateAsyncOperationContextWithActivity(object activity) { if (OperationContext.Current != null && activity != null) { OperationContext.Current.OutgoingMessageProperties[TraceUtility.AsyncOperationActivityKey] = activity; } } static internal object ExtractAsyncOperationContextActivity() { object data = null; if (OperationContext.Current != null && OperationContext.Current.OutgoingMessageProperties.TryGetValue(TraceUtility.AsyncOperationActivityKey, out data)) { OperationContext.Current.OutgoingMessageProperties.Remove(TraceUtility.AsyncOperationActivityKey); } return data; } static internal void UpdateAsyncOperationContextWithStartTime(EventTraceActivity eventTraceActivity, long startTime) { if (OperationContext.Current != null) { OperationContext.Current.OutgoingMessageProperties[TraceUtility.AsyncOperationStartTimeKey] = new EventTraceActivityTimeProperty(eventTraceActivity, startTime); } } static internal void ExtractAsyncOperationStartTime(out EventTraceActivity eventTraceActivity, out long startTime) { EventTraceActivityTimeProperty data = null; eventTraceActivity = null; startTime = 0; if (OperationContext.Current != null && OperationContext.Current.OutgoingMessageProperties.TryGetValue(TraceUtility.AsyncOperationStartTimeKey, out data)) { OperationContext.Current.OutgoingMessageProperties.Remove(TraceUtility.AsyncOperationStartTimeKey); eventTraceActivity = data.EventTraceActivity; startTime = data.StartTime; } } internal class TracingAsyncCallbackState { private Guid _activityId; internal TracingAsyncCallbackState(object innerState) { InnerState = innerState; _activityId = DiagnosticTraceBase.ActivityId; } internal object InnerState { get; } internal Guid ActivityId { get { return _activityId; } } } internal static AsyncCallback WrapExecuteUserCodeAsyncCallback(AsyncCallback callback) { return (DiagnosticUtility.ShouldUseActivity && callback != null) ? (new ExecuteUserCodeAsync(callback)).Callback : callback; } internal sealed class ExecuteUserCodeAsync { private AsyncCallback _callback; public ExecuteUserCodeAsync(AsyncCallback callback) { _callback = callback; } public AsyncCallback Callback { get { return Fx.ThunkCallback(new AsyncCallback(ExecuteUserCode)); } } private void ExecuteUserCode(IAsyncResult result) { using (ServiceModelActivity activity = ServiceModelActivity.CreateBoundedActivity()) { ServiceModelActivity.Start(activity, SR.ActivityCallback, ActivityType.ExecuteUserCode); _callback(result); } } } internal class EventTraceActivityTimeProperty { private EventTraceActivity _eventTraceActivity; public EventTraceActivityTimeProperty(EventTraceActivity eventTraceActivity, long startTime) { _eventTraceActivity = eventTraceActivity; StartTime = startTime; } internal long StartTime { get; } internal EventTraceActivity EventTraceActivity { get { return _eventTraceActivity; } } } public static InputQueue<T> CreateInputQueue<T>() where T : class { if (asyncCallbackGenerator == null) { asyncCallbackGenerator = new Func<Action<AsyncCallback, IAsyncResult>>(CallbackGenerator); } return new InputQueue<T>(asyncCallbackGenerator) { DisposeItemCallback = value => { if (value is ICommunicationObject) { ((ICommunicationObject)value).Abort(); } } }; } internal static Action<AsyncCallback, IAsyncResult> CallbackGenerator() { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity callbackActivity = ServiceModelActivity.Current; if (callbackActivity != null) { return delegate (AsyncCallback callback, IAsyncResult result) { using (ServiceModelActivity.BoundOperation(callbackActivity)) { callback(result); } }; } } return null; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using HandyUtilities; using UnityEngine.UI; namespace DynamicUI { public interface IDUIList { void OnHolderClick(object holder); void OnItemSetUp(object holder); } public interface IDUIListExtended : IDUIList { void OnHolderPointerDown(object holder); void OnHolderPointerUp(object holder); } public class DUIReordableList<Holder> : DUIList<Holder>, IDUIListExtended where Holder : DUIReordableItemHolder { [SerializeField] protected float m_dragDuration = .5f; [SerializeField] protected float m_holdersMoveSpeed = 10; [SerializeField] protected bool m_allowDeleting = false; [SerializeField] float m_maxScrollSpeed = 1f; public Holder draggedHolder { get; private set; } public bool isDraggingItem { get; private set; } bool m_moveingHoldersToPos; bool m_isHoldingItem; float m_dragTimer; Vector2 m_pressedItemPos; Vector2 m_pressedPointerPos; public event System.Action<object> onHolderPointerDown; public event System.Action<object> onHolderPointerUp; public event System.Action onListChanged; List<Holder> m_backUpHolderList; RectTransform test; protected override void SetItems(object[] itemList) { test = new GameObject("Test").AddComponent<RectTransform>(); test.SetParent(m_container); base.SetItems(itemList); for (int i = 0; i < itemHolders.Count; i++) { itemHolders[i].SetParentList(this); } m_backUpHolderList = new List<Holder>(itemHolders); SetHoldersTargetPosition(); } public void UndoDeletedItems() { m_itemHolders = new List<Holder>(m_backUpHolderList); m_items = new object[m_backUpHolderList.Count]; for (int i = 0; i < m_itemHolders.Count; i++) { m_itemHolders[i].OnUndoDelete(); m_itemHolders[i].index = i; m_items[i] = m_itemHolders[i].item; } SetHoldersTargetPosition(); ResizeContainer(); } protected virtual Vector2 GetPointer() { return Input.mousePosition; } protected virtual void OnStartDragging(Holder holder) { m_isHoldingItem = false; isDraggingItem = true; m_pressedItemPos = draggedHolder.rectTransform.position; m_pressedPointerPos = GetPointer(); scrollRect.enabled = false; draggedHolder.rectTransform.SetAsLastSibling(); SetHoldersTargetPosition(); m_moveingHoldersToPos = true; } public virtual void OnHolderPointerDown(object item) { if (onHolderPointerDown != null) onHolderPointerDown(item); } public virtual void OnHolderPointerUp(object item) { if (onHolderPointerUp != null) onHolderPointerUp(item); } void OnListChanged() { for (int i = 0; i < itemHolders.Count; i++) { itemHolders[i].index = i; items[i] = itemHolders[i].item; } if (onListChanged != null) onListChanged(); } protected virtual void OnDraggingItem(Holder holder) { var draggedItemRect = draggedHolder.rectTransform; var draggedRectHeight = draggedItemRect.sizeDelta.y * m_canvasScale; var pointer = GetPointer(); // draggedItemRect.localScale = Vector3.Lerp(draggedItemRect.localScale, new Vector3(1.2f, 1.2f, 1.2f), Time.unscaledDeltaTime * 3); var delta = m_pressedPointerPos - pointer; if(m_allowDeleting == false) delta.x = 0; draggedItemRect.position = m_pressedItemPos - delta; var draggedPos = draggedItemRect.anchoredPosition.y + (draggedItemRect.sizeDelta.y * m_canvasScale * draggedItemRect.pivot.y); var viewPortTopPos = rectTransform.position.y + (Vector3.Scale(rectTransform.sizeDelta * m_canvasScale, rectTransform.pivot)).y; var viewPortBottomPos = rectTransform.position.y - (Vector3.Scale(rectTransform.sizeDelta * m_canvasScale, rectTransform.pivot)).y; var draggedRectWidth = draggedItemRect.sizeDelta.x * m_canvasScale; if (m_allowDeleting) { bool readyToBeDeleted = Mathf.Abs(draggedItemRect.anchoredPosition.x) > draggedRectWidth * .5f; if(readyToBeDeleted != draggedHolder.isRedyToBeDeleted) { draggedHolder.isRedyToBeDeleted = readyToBeDeleted; draggedHolder.OnReadyToBeDeleted(readyToBeDeleted); } } var draggedIndex = draggedHolder.index; var prevItem = draggedIndex > 0 ? itemHolders[draggedIndex - 1] : null; var nextItem = draggedIndex < itemHolders.Count - 1 ? itemHolders[draggedIndex + 1] : null; var topDistanceToContainer = (draggedItemRect.position.y - viewPortTopPos) + (draggedRectHeight * .5f); var bottomDistanceToContainer = (draggedItemRect.position.y - viewPortBottomPos) - (draggedRectHeight * .5f); if (topDistanceToContainer > 0) { var scrollSpeed = Helper.Remap(topDistanceToContainer, 0, draggedRectHeight, 0, m_maxScrollSpeed * .5f); if (scrollRect.normalizedPosition.y < 1) { scrollRect.normalizedPosition += Vector2.up * Time.unscaledDeltaTime * scrollSpeed; } } if (bottomDistanceToContainer < 0) { var scrollSpeed = Helper.Remap(bottomDistanceToContainer, 0, -draggedRectHeight, 0, m_maxScrollSpeed * .5f); if (scrollRect.normalizedPosition.y > 0) { scrollRect.normalizedPosition -= Vector2.up * Time.unscaledDeltaTime * scrollSpeed; } } if (prevItem && !prevItem.isMoving) { var prevItemHeight = prevItem.rectTransform.sizeDelta.y * m_canvasScale; var prevItemPos = prevItem.rectTransform.anchoredPosition.y - (prevItemHeight * prevItem.rectTransform.pivot.y); var distanceToPrevItem = draggedPos - prevItemPos; var swapThreshold = prevItemHeight * .25f; if (distanceToPrevItem > (draggedRectHeight * .5f) + swapThreshold) { draggedHolder.index = draggedIndex - 1; prevItem.index = draggedIndex; itemHolders[draggedIndex - 1] = draggedHolder; itemHolders[draggedIndex] = prevItem; SetHoldersTargetPosition(); } } if (nextItem && !nextItem.isMoving) { var nextItemHeight = nextItem.rectTransform.sizeDelta.y * m_canvasScale; var nextItemPos = nextItem.rectTransform.anchoredPosition.y + (nextItemHeight * nextItem.rectTransform.pivot.y); var distanceToNextItem = draggedPos - nextItemPos; var swapThreshold = nextItemHeight * .25f; if (distanceToNextItem < (draggedRectHeight * .5f) - swapThreshold) { draggedHolder.index = draggedIndex + 1; nextItem.index = draggedIndex; itemHolders[draggedIndex + 1] = draggedHolder; itemHolders[draggedIndex] = nextItem; SetHoldersTargetPosition(); } } } void SetHoldersTargetPosition() { var h = 0f; var p = 0f; for (int i = 0; i < itemHolders.Count; i++) { var holder = itemHolders[i]; var newH = holder.rectTransform.sizeDelta.y; p = (p - h * .5f) - (newH * holder.rectTransform.pivot.y); h = newH; holder.positionInList = new Vector2(0, p); } } void MoveHolderToPosition() { if (m_moveingHoldersToPos == false) return; bool hasMovingHolders = false; for (int i = 0; i < itemHolders.Count; i++) { var holder = itemHolders[i]; if (holder == draggedHolder) continue; if (!hasMovingHolders) { var d = holder.rectTransform.anchoredPosition.y - holder.positionInList.y; if (d != 0) hasMovingHolders = true; } holder.rectTransform.anchoredPosition = Vector2.Lerp(holder.rectTransform.anchoredPosition, holder.positionInList, Time.deltaTime * 10); } if (hasMovingHolders == false && isDraggingItem == false) m_moveingHoldersToPos = false; } protected virtual void OnItemDeleted(Holder holder) { } void DeleteItem(Holder holder) { holder.OnDelete(); itemHolders.Remove(holder); System.Array.Resize(ref m_items, items.Length - 1); OnListChanged(); OnItemDeleted(holder); ResizeContainer(); } void ResizeContainer() { var h = 0f; for (int i = 0; i < itemHolders.Count; i++) { h += itemHolders[i].rectTransform.sizeDelta.y; } m_container.sizeDelta = new Vector2(m_container.sizeDelta.x, h); } void OnDraggingEnd() { if(m_allowDeleting) { if(draggedHolder.isRedyToBeDeleted) { DeleteItem(draggedHolder); } draggedHolder.isRedyToBeDeleted = false; draggedHolder.OnReadyToBeDeleted(false); } isDraggingItem = false; scrollRect.enabled = true; draggedHolder.rectTransform.SetParent(m_container); draggedHolder = null; SetHoldersTargetPosition(); } void Update() { if(m_isHoldingItem) { m_dragTimer += Time.unscaledDeltaTime; if(m_dragTimer > m_dragDuration) { OnStartDragging(draggedHolder); } } if(isDraggingItem) { OnDraggingItem(draggedHolder); if(Input.GetMouseButtonUp(0)) { OnDraggingEnd(); } } if (Input.GetKeyDown(KeyCode.Z)) UndoDeletedItems(); MoveHolderToPosition(); } public virtual void OnItemPointerDown(object item) { if(isDraggingItem == false) { m_isHoldingItem = true; m_dragTimer = 0; draggedHolder = item as Holder; } } public virtual void OnItemPointerUp(object item) { if (isDraggingItem == false) { m_isHoldingItem = false; draggedHolder = null; } } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Conn.Scheme.cs // // 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. #pragma warning disable 1717 namespace Org.Apache.Http.Conn.Scheme { /// <summary> /// <para>A set of supported protocol schemes. Schemes are identified by lowercase names.</para><para><para></para><para></para><title>Revision:</title><para>648356 </para><title>Date:</title><para>2008-04-15 10:57:53 -0700 (Tue, 15 Apr 2008) </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/SchemeRegistry /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/SchemeRegistry", AccessFlags = 49)] public sealed partial class SchemeRegistry /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new, empty scheme registry. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public SchemeRegistry() /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the scheme for a host. Convenience method for <code>getScheme(host.getSchemeName())</code></para><para><code> </code></para> /// </summary> /// <returns> /// <para>the scheme for the given host, never <code>null</code></para> /// </returns> /// <java-name> /// getScheme /// </java-name> [Dot42.DexImport("getScheme", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme GetScheme(string host) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Obtains the scheme for a host. Convenience method for <code>getScheme(host.getSchemeName())</code></para><para><code> </code></para> /// </summary> /// <returns> /// <para>the scheme for the given host, never <code>null</code></para> /// </returns> /// <java-name> /// getScheme /// </java-name> [Dot42.DexImport("getScheme", "(Lorg/apache/http/HttpHost;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme GetScheme(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Obtains a scheme by name, if registered.</para><para></para> /// </summary> /// <returns> /// <para>the scheme, or <code>null</code> if there is none by this name </para> /// </returns> /// <java-name> /// get /// </java-name> [Dot42.DexImport("get", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme Get(string name) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Registers a scheme. The scheme can later be retrieved by its name using getScheme or get.</para><para></para> /// </summary> /// <returns> /// <para>the scheme previously registered with that name, or <code>null</code> if none was registered </para> /// </returns> /// <java-name> /// register /// </java-name> [Dot42.DexImport("register", "(Lorg/apache/http/conn/scheme/Scheme;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme Register(global::Org.Apache.Http.Conn.Scheme.Scheme sch) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Unregisters a scheme.</para><para></para> /// </summary> /// <returns> /// <para>the unregistered scheme, or <code>null</code> if there was none </para> /// </returns> /// <java-name> /// unregister /// </java-name> [Dot42.DexImport("unregister", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme Unregister(string name) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Obtains the names of the registered schemes in their default order.</para><para></para> /// </summary> /// <returns> /// <para>List containing registered scheme names. </para> /// </returns> /// <java-name> /// getSchemeNames /// </java-name> [Dot42.DexImport("getSchemeNames", "()Ljava/util/List;", AccessFlags = 49, Signature = "()Ljava/util/List<Ljava/lang/String;>;")] public global::Java.Util.IList<string> GetSchemeNames() /* MethodBuilder.Create */ { return default(global::Java.Util.IList<string>); } /// <summary> /// <para>Populates the internal collection of registered protocol schemes with the content of the map passed as a parameter.</para><para></para> /// </summary> /// <java-name> /// setItems /// </java-name> [Dot42.DexImport("setItems", "(Ljava/util/Map;)V", AccessFlags = 33, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/conn/scheme/Scheme;>;)V")] public void SetItems(global::Java.Util.IMap<string, global::Org.Apache.Http.Conn.Scheme.Scheme> map) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the names of the registered schemes in their default order.</para><para></para> /// </summary> /// <returns> /// <para>List containing registered scheme names. </para> /// </returns> /// <java-name> /// getSchemeNames /// </java-name> public global::Java.Util.IList<string> SchemeNames { [Dot42.DexImport("getSchemeNames", "()Ljava/util/List;", AccessFlags = 49, Signature = "()Ljava/util/List<Ljava/lang/String;>;")] get{ return GetSchemeNames(); } } } /// <summary> /// <para>A SocketFactory for layered sockets (SSL/TLS). See there for things to consider when implementing a socket factory.</para><para><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/LayeredSocketFactory /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/LayeredSocketFactory", AccessFlags = 1537)] public partial interface ILayeredSocketFactory : global::Org.Apache.Http.Conn.Scheme.ISocketFactory /* scope: __dot42__ */ { /// <summary> /// <para>Returns a socket connected to the given host that is layered over an existing socket. Used primarily for creating secure sockets through proxies.</para><para></para> /// </summary> /// <returns> /// <para>Socket a new socket</para> /// </returns> /// <java-name> /// createSocket /// </java-name> [Dot42.DexImport("createSocket", "(Ljava/net/Socket;Ljava/lang/String;IZ)Ljava/net/Socket;", AccessFlags = 1025)] global::Java.Net.Socket CreateSocket(global::Java.Net.Socket socket, string host, int port, bool autoClose) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Encapsulates specifics of a protocol scheme such as "http" or "https". Schemes are identified by lowercase names. Supported schemes are typically collected in a SchemeRegistry.</para><para>For example, to configure support for "https://" URLs, you could write code like the following: </para><para><pre> /// Scheme https = new Scheme("https", new MySecureSocketFactory(), 443); /// SchemeRegistry.DEFAULT.register(https); /// </pre></para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para><simplesectsep></simplesectsep><para>Jeff Dever </para><simplesectsep></simplesectsep><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/Scheme /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/Scheme", AccessFlags = 49)] public sealed partial class Scheme /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new scheme. Whether the created scheme allows for layered connections depends on the class of <code>factory</code>.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Lorg/apache/http/conn/scheme/SocketFactory;I)V", AccessFlags = 1)] public Scheme(string name, global::Org.Apache.Http.Conn.Scheme.ISocketFactory factory, int port) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the default port.</para><para></para> /// </summary> /// <returns> /// <para>the default port for this scheme </para> /// </returns> /// <java-name> /// getDefaultPort /// </java-name> [Dot42.DexImport("getDefaultPort", "()I", AccessFlags = 17)] public int GetDefaultPort() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Obtains the socket factory. If this scheme is layered, the factory implements LayeredSocketFactory.</para><para></para> /// </summary> /// <returns> /// <para>the socket factory for this scheme </para> /// </returns> /// <java-name> /// getSocketFactory /// </java-name> [Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/SocketFactory;", AccessFlags = 17)] public global::Org.Apache.Http.Conn.Scheme.ISocketFactory GetSocketFactory() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.ISocketFactory); } /// <summary> /// <para>Obtains the scheme name.</para><para></para> /// </summary> /// <returns> /// <para>the name of this scheme, in lowercase </para> /// </returns> /// <java-name> /// getName /// </java-name> [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 17)] public string GetName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Indicates whether this scheme allows for layered connections.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if layered connections are possible, <code>false</code> otherwise </para> /// </returns> /// <java-name> /// isLayered /// </java-name> [Dot42.DexImport("isLayered", "()Z", AccessFlags = 17)] public bool IsLayered() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Resolves the correct port for this scheme. Returns the given port if it is valid, the default port otherwise.</para><para></para> /// </summary> /// <returns> /// <para>the given port or the defaultPort </para> /// </returns> /// <java-name> /// resolvePort /// </java-name> [Dot42.DexImport("resolvePort", "(I)I", AccessFlags = 17)] public int ResolvePort(int port) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Return a string representation of this object.</para><para></para> /// </summary> /// <returns> /// <para>a human-readable string description of this scheme </para> /// </returns> /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 17)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Compares this scheme to an object.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> iff the argument is equal to this scheme </para> /// </returns> /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 17)] public override bool Equals(object obj) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Obtains a hash code for this scheme.</para><para></para> /// </summary> /// <returns> /// <para>the hash code </para> /// </returns> /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal Scheme() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Obtains the default port.</para><para></para> /// </summary> /// <returns> /// <para>the default port for this scheme </para> /// </returns> /// <java-name> /// getDefaultPort /// </java-name> public int DefaultPort { [Dot42.DexImport("getDefaultPort", "()I", AccessFlags = 17)] get{ return GetDefaultPort(); } } /// <summary> /// <para>Obtains the socket factory. If this scheme is layered, the factory implements LayeredSocketFactory.</para><para></para> /// </summary> /// <returns> /// <para>the socket factory for this scheme </para> /// </returns> /// <java-name> /// getSocketFactory /// </java-name> public global::Org.Apache.Http.Conn.Scheme.ISocketFactory SocketFactory { [Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/SocketFactory;", AccessFlags = 17)] get{ return GetSocketFactory(); } } /// <summary> /// <para>Obtains the scheme name.</para><para></para> /// </summary> /// <returns> /// <para>the name of this scheme, in lowercase </para> /// </returns> /// <java-name> /// getName /// </java-name> public string Name { [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 17)] get{ return GetName(); } } } /// <java-name> /// org/apache/http/conn/scheme/HostNameResolver /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/HostNameResolver", AccessFlags = 1537)] public partial interface IHostNameResolver /* scope: __dot42__ */ { /// <java-name> /// resolve /// </java-name> [Dot42.DexImport("resolve", "(Ljava/lang/String;)Ljava/net/InetAddress;", AccessFlags = 1025)] global::Java.Net.InetAddress Resolve(string hostname) /* MethodBuilder.Create */ ; } /// <summary> /// <para>The default class for creating sockets.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/PlainSocketFactory /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/PlainSocketFactory", AccessFlags = 49)] public sealed partial class PlainSocketFactory : global::Org.Apache.Http.Conn.Scheme.ISocketFactory /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/conn/scheme/HostNameResolver;)V", AccessFlags = 1)] public PlainSocketFactory(global::Org.Apache.Http.Conn.Scheme.IHostNameResolver nameResolver) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public PlainSocketFactory() /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the singleton instance of this class. </para> /// </summary> /// <returns> /// <para>the one and only plain socket factory </para> /// </returns> /// <java-name> /// getSocketFactory /// </java-name> [Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/PlainSocketFactory;", AccessFlags = 9)] public static global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory GetSocketFactory() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory); } /// <summary> /// <para>Creates a new, unconnected socket. The socket should subsequently be passed to connectSocket.</para><para></para> /// </summary> /// <returns> /// <para>a new socket</para> /// </returns> /// <java-name> /// createSocket /// </java-name> [Dot42.DexImport("createSocket", "()Ljava/net/Socket;", AccessFlags = 1)] public global::Java.Net.Socket CreateSocket() /* MethodBuilder.Create */ { return default(global::Java.Net.Socket); } /// <summary> /// <para>Connects a socket to the given host.</para><para></para> /// </summary> /// <returns> /// <para>the connected socket. The returned object may be different from the <code>sock</code> argument if this factory supports a layered protocol.</para> /// </returns> /// <java-name> /// connectSocket /// </java-name> [Dot42.DexImport("connectSocket", "(Ljava/net/Socket;Ljava/lang/String;ILjava/net/InetAddress;ILorg/apache/http/para" + "ms/HttpParams;)Ljava/net/Socket;", AccessFlags = 1)] public global::Java.Net.Socket ConnectSocket(global::Java.Net.Socket sock, string host, int port, global::Java.Net.InetAddress localAddress, int localPort, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Java.Net.Socket); } /// <summary> /// <para>Checks whether a socket connection is secure. This factory creates plain socket connections which are not considered secure.</para><para></para> /// </summary> /// <returns> /// <para><code>false</code></para> /// </returns> /// <java-name> /// isSecure /// </java-name> [Dot42.DexImport("isSecure", "(Ljava/net/Socket;)Z", AccessFlags = 17)] public bool IsSecure(global::Java.Net.Socket sock) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Compares this factory with an object. There is only one instance of this class.</para><para></para> /// </summary> /// <returns> /// <para>iff the argument is this object </para> /// </returns> /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)] public override bool Equals(object obj) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Obtains a hash code for this object. All instances of this class have the same hash code. There is only one instance of this class. </para> /// </summary> /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Gets the singleton instance of this class. </para> /// </summary> /// <returns> /// <para>the one and only plain socket factory </para> /// </returns> /// <java-name> /// getSocketFactory /// </java-name> public static global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory SocketFactory { [Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/PlainSocketFactory;", AccessFlags = 9)] get{ return GetSocketFactory(); } } } /// <summary> /// <para>A factory for creating and connecting sockets. The factory encapsulates the logic for establishing a socket connection. <br></br> Both Object.equals() and Object.hashCode() must be overridden for the correct operation of some connection managers.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/SocketFactory /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/SocketFactory", AccessFlags = 1537)] public partial interface ISocketFactory /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new, unconnected socket. The socket should subsequently be passed to connectSocket.</para><para></para> /// </summary> /// <returns> /// <para>a new socket</para> /// </returns> /// <java-name> /// createSocket /// </java-name> [Dot42.DexImport("createSocket", "()Ljava/net/Socket;", AccessFlags = 1025)] global::Java.Net.Socket CreateSocket() /* MethodBuilder.Create */ ; /// <summary> /// <para>Connects a socket to the given host.</para><para></para> /// </summary> /// <returns> /// <para>the connected socket. The returned object may be different from the <code>sock</code> argument if this factory supports a layered protocol.</para> /// </returns> /// <java-name> /// connectSocket /// </java-name> [Dot42.DexImport("connectSocket", "(Ljava/net/Socket;Ljava/lang/String;ILjava/net/InetAddress;ILorg/apache/http/para" + "ms/HttpParams;)Ljava/net/Socket;", AccessFlags = 1025)] global::Java.Net.Socket ConnectSocket(global::Java.Net.Socket sock, string host, int port, global::Java.Net.InetAddress localAddress, int localPort, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ ; /// <summary> /// <para>Checks whether a socket provides a secure connection. The socket must be connected by this factory. The factory will <b>not</b> perform I/O operations in this method. <br></br> As a rule of thumb, plain sockets are not secure and TLS/SSL sockets are secure. However, there may be application specific deviations. For example, a plain socket to a host in the same intranet ("trusted zone") could be considered secure. On the other hand, a TLS/SSL socket could be considered insecure based on the cypher suite chosen for the connection.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the connection of the socket should be considered secure, or <code>false</code> if it should not</para> /// </returns> /// <java-name> /// isSecure /// </java-name> [Dot42.DexImport("isSecure", "(Ljava/net/Socket;)Z", AccessFlags = 1025)] bool IsSecure(global::Java.Net.Socket sock) /* MethodBuilder.Create */ ; } }
// 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.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { [ComVisible(true)] public class AutomationObject { private readonly IOptionService _optionService; internal AutomationObject(IOptionService optionService) { _optionService = optionService; } public int AutoComment { get { return GetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration); } set { SetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration, value); } } public int BringUpOnIdentifier { get { return GetBooleanOption(CompletionOptions.TriggerOnTypingLetters); } set { SetBooleanOption(CompletionOptions.TriggerOnTypingLetters, value); } } public int ClosedFileDiagnostics { get { return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic); } set { SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value); } } public int DisplayLineSeparators { get { return GetBooleanOption(FeatureOnOffOptions.LineSeparator); } set { SetBooleanOption(FeatureOnOffOptions.LineSeparator, value); } } public int EnableHighlightRelatedKeywords { get { return GetBooleanOption(FeatureOnOffOptions.KeywordHighlighting); } set { SetBooleanOption(FeatureOnOffOptions.KeywordHighlighting, value); } } public int EnterOutliningModeOnOpen { get { return GetBooleanOption(FeatureOnOffOptions.Outlining); } set { SetBooleanOption(FeatureOnOffOptions.Outlining, value); } } public int ExtractMethod_AllowMovingDeclaration { get { return GetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration); } set { SetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration, value); } } public int ExtractMethod_DoNotPutOutOrRefOnStruct { get { return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct); } set { SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, value); } } public int Formatting_TriggerOnBlockCompletion { get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace); } set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace, value); } } public int Formatting_TriggerOnPaste { get { return GetBooleanOption(FeatureOnOffOptions.FormatOnPaste); } set { SetBooleanOption(FeatureOnOffOptions.FormatOnPaste, value); } } public int Formatting_TriggerOnStatementCompletion { get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon); } set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon, value); } } public int HighlightReferences { get { return GetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting); } set { SetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting, value); } } public int Indent_BlockContents { get { return GetBooleanOption(CSharpFormattingOptions.IndentBlock); } set { SetBooleanOption(CSharpFormattingOptions.IndentBlock, value); } } public int Indent_Braces { get { return GetBooleanOption(CSharpFormattingOptions.IndentBraces); } set { SetBooleanOption(CSharpFormattingOptions.IndentBraces, value); } } public int Indent_CaseContents { get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection); } set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection, value); } } public int Indent_CaseLabels { get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchSection); } set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchSection, value); } } public int Indent_FlushLabelsLeft { get { var option = _optionService.GetOption(CSharpFormattingOptions.LabelPositioning); return option == LabelPositionOptions.LeftMost ? 1 : 0; } set { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value == 1 ? LabelPositionOptions.LeftMost : LabelPositionOptions.NoIndent); _optionService.SetOptions(optionSet); } } public int Indent_UnindentLabels { get { var option = _optionService.GetOption(CSharpFormattingOptions.LabelPositioning); return (int)option; } set { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value); _optionService.SetOptions(optionSet); } } public int InsertNewlineOnEnterWithWholeWord { get { return GetBooleanOption(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord); } set { SetBooleanOption(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord, value); } } public int NewLines_AnonymousTypeInitializer_EachMember { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes, value); } } public int NewLines_Braces_AnonymousMethod { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods, value); } } public int NewLines_Braces_AnonymousTypeInitializer { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes, value); } } public int NewLines_Braces_ControlFlow { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, value); } } public int NewLines_Braces_LambdaExpressionBody { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody, value); } } public int NewLines_Braces_Method { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods, value); } } public int NewLines_Braces_Property { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties, value); } } public int NewLines_Braces_Accessor { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors, value); } } public int NewLines_Braces_ObjectInitializer { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, value); } } public int NewLines_Braces_Type { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes, value); } } public int NewLines_Keywords_Catch { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForCatch); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForCatch, value); } } public int NewLines_Keywords_Else { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForElse); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForElse, value); } } public int NewLines_Keywords_Finally { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForFinally); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForFinally, value); } } public int NewLines_ObjectInitializer_EachMember { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit, value); } } public int NewLines_QueryExpression_EachClause { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery, value); } } public int Refactoring_Verification_Enabled { get { return GetBooleanOption(FeatureOnOffOptions.RefactoringVerification); } set { SetBooleanOption(FeatureOnOffOptions.RefactoringVerification, value); } } public int RenameSmartTagEnabled { get { return GetBooleanOption(FeatureOnOffOptions.RenameTracking); } set { SetBooleanOption(FeatureOnOffOptions.RenameTracking, value); } } public int RenameTrackingPreview { get { return GetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview); } set { SetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview, value); } } public int ShowKeywords { get { return GetBooleanOption(CompletionOptions.IncludeKeywords); } set { SetBooleanOption(CompletionOptions.IncludeKeywords, value); } } public int ShowSnippets { get { return GetBooleanOption(CSharpCompletionOptions.IncludeSnippets); } set { SetBooleanOption(CSharpCompletionOptions.IncludeSnippets, value); } } public int SortUsings_PlaceSystemFirst { get { return GetBooleanOption(OrganizerOptions.PlaceSystemNamespaceFirst); } set { SetBooleanOption(OrganizerOptions.PlaceSystemNamespaceFirst, value); } } public int Space_AfterBasesColon { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration, value); } } public int Space_AfterCast { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterCast); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterCast, value); } } public int Space_AfterComma { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterComma); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterComma, value); } } public int Space_AfterDot { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterDot); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterDot, value); } } public int Space_AfterMethodCallName { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName, value); } } public int Space_AfterMethodDeclarationName { get { return GetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName); } set { SetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, value); } } public int Space_AfterSemicolonsInForStatement { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement, value); } } public int Space_AroundBinaryOperator { get { var option = _optionService.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); return option == BinaryOperatorSpacingOptions.Single ? 1 : 0; } set { var option = value == 1 ? BinaryOperatorSpacingOptions.Single : BinaryOperatorSpacingOptions.Ignore; var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, option); _optionService.SetOptions(optionSet); } } public int Space_BeforeBasesColon { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration, value); } } public int Space_BeforeComma { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma, value); } } public int Space_BeforeDot { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot, value); } } public int Space_BeforeOpenSquare { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket, value); } } public int Space_BeforeSemicolonsInForStatement { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement, value); } } public int Space_BetweenEmptyMethodCallParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses, value); } } public int Space_BetweenEmptyMethodDeclarationParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses, value); } } public int Space_BetweenEmptySquares { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets, value); } } public int Space_InControlFlowConstruct { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword, value); } } public int Space_WithinCastParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses, value); } } public int Space_WithinExpressionParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses, value); } } public int Space_WithinMethodCallParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses, value); } } public int Space_WithinMethodDeclarationParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis, value); } } public int Space_WithinOtherParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses, value); } } public int Space_WithinSquares { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets, value); } } public int Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration { get { return GetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration); } set { SetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, value); } } public int Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess { get { return GetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); } set { SetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, value); } } public int Style_QualifyMemberAccessWithThisOrMe { get { return GetBooleanOption(SimplificationOptions.QualifyMemberAccessWithThisOrMe); } set { SetBooleanOption(SimplificationOptions.QualifyMemberAccessWithThisOrMe, value); } } public int Style_UseVarWhenDeclaringLocals { get { return GetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals); } set { SetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals, value); } } public int WarnOnBuildErrors { get { return GetBooleanOption(OrganizerOptions.WarnOnBuildErrors); } set { SetBooleanOption(OrganizerOptions.WarnOnBuildErrors, value); } } public int Wrapping_IgnoreSpacesAroundBinaryOperators { get { var option = _optionService.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); return (int)option; } set { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, value); _optionService.SetOptions(optionSet); } } public int Wrapping_IgnoreSpacesAroundVariableDeclaration { get { return GetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration); } set { SetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration, value); } } public int Wrapping_KeepStatementsOnSingleLine { get { return GetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine); } set { SetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, value); } } public int Wrapping_PreserveSingleLine { get { return GetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine); } set { SetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine, value); } } private int GetBooleanOption(Option<bool> key) { return _optionService.GetOption(key) ? 1 : 0; } private int GetBooleanOption(PerLanguageOption<bool> key) { return _optionService.GetOption(key, LanguageNames.CSharp) ? 1 : 0; } private void SetBooleanOption(Option<bool> key, int value) { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(key, value != 0); _optionService.SetOptions(optionSet); } private void SetBooleanOption(PerLanguageOption<bool> key, int value) { var optionSet = _optionService.GetOptions(); optionSet = optionSet.WithChangedOption(key, LanguageNames.CSharp, value != 0); _optionService.SetOptions(optionSet); } } }
// // MultilineEntryElement.cs: multi-line element entry for MonoTouch.Dialog // // Author: // Aleksander Heintz (alxandr@alxandr.me) // Based on the code for the EntryElement by Miguel de Icaza // using System; #if XAMCORE_2_0 using UIKit; using CoreGraphics; using Foundation; #else using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using MonoTouch.Foundation; #endif using System.Drawing; using MonoTouch.Dialog; #if !XAMCORE_2_0 using nint = global::System.Int32; using nuint = global::System.UInt32; using nfloat = global::System.Single; using CGSize = global::System.Drawing.SizeF; using CGPoint = global::System.Drawing.PointF; using CGRect = global::System.Drawing.RectangleF; #endif namespace ElementPack { /// <summary> /// An element that can be used to enter text. /// </summary> /// <remarks> /// This element can be used to enter text both regular and password protected entries. /// /// The Text fields in a given section are aligned with each other. /// </remarks> public class SimpleMultilineEntryElement : Element, IElementSizing { /// <summary> /// The value of the EntryElement /// </summary> public string Value { get { return val; } set { val = value; if (entry != null) entry.Text = value; } } public string Placeholder{ get; set; } protected string val; public bool Editable { get { return editable; } set { editable = value; if (entry != null) entry.Editable = editable; } } protected bool editable; /// <summary> /// The key used for reusable UITableViewCells. /// </summary> static NSString entryKey = new NSString ("MultilineEntryElement"); protected virtual NSString EntryKey { get { return entryKey; } } /// <summary> /// The type of keyboard used for input, you can change /// this to use this for numeric input, email addressed, /// urls, phones. /// </summary> public UIKeyboardType KeyboardType { get { return keyboardType; } set { keyboardType = value; if (entry != null) entry.KeyboardType = value; } } public UITextAutocapitalizationType AutocapitalizationType { get { return autocapitalizationType; } set { autocapitalizationType = value; if (entry != null) entry.AutocapitalizationType = value; } } public UITextAutocorrectionType AutocorrectionType { get { return autocorrectionType; } set { autocorrectionType = value; if (entry != null) this.autocorrectionType = value; } } private float height = 112; public float Height { get { return height; } set { height = value; } } private UIFont inputFont = UIFont.SystemFontOfSize(17); public UIFont Font { get { return inputFont; } set { inputFont = value; if (entry != null) entry.Font = value; } } UIKeyboardType keyboardType = UIKeyboardType.Default; UITextAutocapitalizationType autocapitalizationType = UITextAutocapitalizationType.Sentences; UITextAutocorrectionType autocorrectionType = UITextAutocorrectionType.Default; bool becomeResponder; UITextView entry; static UIFont font = UIFont.BoldSystemFontOfSize (17); public event EventHandler Changed; public event Func<bool> ShouldReturn; /// <summary> /// Constructs an MultilineEntryElement with the given caption, placeholder and initial value. /// </summary> /// <param name="caption"> /// The caption to use /// </param> /// <param name="placeholder"> /// Placeholder to display when no value is set. /// </param> /// <param name="value"> /// Initial value. /// </param> public SimpleMultilineEntryElement (string caption, string value) : this (caption, "", value) { } public SimpleMultilineEntryElement (string caption, string placeholder, string value): base(caption) { Placeholder = placeholder; Value = value; } public override string Summary () { return Value; } // // Computes the X position for the entry by aligning all the entries in the Section // CGSize ComputeEntryPosition (UITableView tv, UITableViewCell cell) { Section s = Parent as Section; if (s.EntryAlignment.Width != 0) return s.EntryAlignment; // If all EntryElements have a null Caption, align UITextField with the Caption // offset of normal cells (at 10px). CGSize max = new CGSize(-15, "M".StringSize(font).Height); foreach (var e in s.Elements) { if (e == null) continue; if (e.Caption != null) { var size = e.Caption.StringSize (font); if (size.Width > max.Width) max = size; } } s.EntryAlignment = new CGSize(25 + Math.Min(max.Width, 160), max.Height); return s.EntryAlignment; } protected virtual UITextView CreateTextField (CGRect frame) { return new UITextView (frame) { AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleLeftMargin, Text = Value ?? "", Tag = 1, BackgroundColor = UIColor.Clear, Editable = editable }; } static NSString cellkey = new NSString ("MultilineEntryElement"); protected override NSString CellKey { get { return cellkey; } } protected override UITableViewCellStyle CellStyle => UITableViewCellStyle.Default; public override UITableViewCell GetCell (UITableView tv) { //var cell = tv.DequeueReusableCell (CellKey); var cell = base.GetCell(tv); // if (cell == null) { // cell = new UITableViewCell (UITableViewCellStyle.Default, CellKey); cell.SelectionStyle = UITableViewCellSelectionStyle.None; //} else RemoveTag (cell, 1); if (entry == null) { CGSize size = ComputeEntryPosition(tv, cell); nfloat yOffset = (cell.ContentView.Bounds.Height - size.Height) / 2 - 1; nfloat width = cell.ContentView.Bounds.Width - size.Width; entry = CreateTextField (new CGRect (size.Width, yOffset, width, size.Height + (height - 44))); entry.Font = inputFont; entry.Changed += delegate { FetchValue (); }; entry.Ended += delegate { FetchValue (); }; entry.Started += delegate { entry.ReturnKeyType = UIReturnKeyType.Default; tv.ScrollToRow (IndexPath, UITableViewScrollPosition.Middle, true); }; } if (becomeResponder) { entry.BecomeFirstResponder (); becomeResponder = false; } entry.KeyboardType = KeyboardType; entry.AutocapitalizationType = AutocapitalizationType; entry.AutocorrectionType = AutocorrectionType; cell.ContentView.AddSubview(entry); cell.TextLabel.Text = Caption; //cell.TextLabel.Font = UIFont.BoldSystemFontOfSize(17); return cell; } /// <summary> /// Copies the value from the UITextField in the EntryElement to the // Value property and raises the Changed event if necessary. /// </summary> public void FetchValue () { if (entry == null) return; var newValue = entry.Text; if (newValue == Value) return; var currentPos = entry.SelectedRange.Location; Value = newValue; if (Changed != null) Changed (this, EventArgs.Empty); if (currentPos > 0) entry.SelectedRange = new NSRange(currentPos, 0); } protected override void Dispose (bool disposing) { if (disposing) { if (entry != null) { entry.Dispose (); entry = null; } } } public override void Selected (DialogViewController dvc, UITableView tableView, NSIndexPath indexPath) { BecomeFirstResponder (true); tableView.DeselectRow (indexPath, true); } public override bool Matches (string text) { return (Value != null ? Value.IndexOf (text, StringComparison.CurrentCultureIgnoreCase) != -1 : false) || base.Matches (text); } /// <summary> /// Makes this cell the first responder (get the focus) /// </summary> /// <param name="animated"> /// Whether scrolling to the location of this cell should be animated /// </param> public void BecomeFirstResponder (bool animated) { becomeResponder = true; var tv = GetContainerTableView (); if (tv == null) return; tv.ScrollToRow (IndexPath, UITableViewScrollPosition.Middle, animated); if (entry != null) { entry.BecomeFirstResponder (); becomeResponder = false; } } public void ResignFirstResponder (bool animated) { becomeResponder = false; var tv = GetContainerTableView (); if (tv == null) return; tv.ScrollToRow (IndexPath, UITableViewScrollPosition.Middle, animated); if (entry != null) entry.ResignFirstResponder (); } public override void Deselected (DialogViewController dvc, UITableView tableView, NSIndexPath path) { // viewController.View.EndEditing (true); base.Deselected (dvc, tableView, path); var tap = new UITapGestureRecognizer (); tap.AddTarget (() => dvc.View.EndEditing (true)); dvc.View.AddGestureRecognizer (tap); tap.CancelsTouchesInView = false; } #region IElementSizing implementation public virtual nfloat GetHeight (UITableView tableView, NSIndexPath indexPath) { return height; } #endregion } }
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 Mithril_Kendo_WebApp.Areas.HelpPage.ModelDescriptions; using Mithril_Kendo_WebApp.Areas.HelpPage.Models; namespace Mithril_Kendo_WebApp.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); } } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // namespace Encog.ML.Data.Market.Loader { partial class CSVFormLoader { /// <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(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.button1 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.CSVFormatsCombo = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.label4 = new System.Windows.Forms.Label(); this.MarketDataTypesListBox = new System.Windows.Forms.ListBox(); this.DateTimeFormatTextBox = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.FileColumnsLabel = new System.Windows.Forms.Label(); this.ColumnsInCSVTextBox = new System.Windows.Forms.TextBox(); this.statusStrip1.SuspendLayout(); this.SuspendLayout(); // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel1}); this.statusStrip1.Location = new System.Drawing.Point(0, 437); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(391, 22); this.statusStrip1.TabIndex = 0; this.statusStrip1.Text = "statusStrip1"; // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(44, 17); this.toolStripStatusLabel1.Text = "Nothing"; // // button1 // this.button1.DialogResult = System.Windows.Forms.DialogResult.Yes; this.button1.Location = new System.Drawing.Point(100, 335); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(121, 37); this.button1.TabIndex = 1; this.button1.Text = "Load CSV"; this.toolTip1.SetToolTip(this.button1, "Load your CSV"); this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(66, 403); this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.Size = new System.Drawing.Size(267, 20); this.textBox1.TabIndex = 2; this.toolTip1.SetToolTip(this.textBox1, "Path to your file"); // // CSVFormatsCombo // this.CSVFormatsCombo.FormattingEnabled = true; this.CSVFormatsCombo.Location = new System.Drawing.Point(100, 6); this.CSVFormatsCombo.Name = "CSVFormatsCombo"; this.CSVFormatsCombo.Size = new System.Drawing.Size(121, 21); this.CSVFormatsCombo.TabIndex = 3; this.toolTip1.SetToolTip(this.CSVFormatsCombo, "CSVFormat to use"); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(4, 410); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(59, 13); this.label1.TabIndex = 4; this.label1.Text = "Loaded file"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(4, 14); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(63, 13); this.label2.TabIndex = 5; this.label2.Text = "CSV Format"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(4, 359); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(55, 13); this.label3.TabIndex = 6; this.label3.Text = "Load CSV"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(4, 68); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(87, 13); this.label4.TabIndex = 7; this.label4.Text = "MarketDataType"; this.toolTip1.SetToolTip(this.label4, "Choose which data type will be loaded"); // // MarketDataTypesListBox // this.MarketDataTypesListBox.FormattingEnabled = true; this.MarketDataTypesListBox.Location = new System.Drawing.Point(100, 52); this.MarketDataTypesListBox.Name = "MarketDataTypesListBox"; this.MarketDataTypesListBox.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended; this.MarketDataTypesListBox.Size = new System.Drawing.Size(120, 95); this.MarketDataTypesListBox.TabIndex = 8; this.toolTip1.SetToolTip(this.MarketDataTypesListBox, "Market data types to use in your csv"); // // DateTimeFormatTextBox // this.DateTimeFormatTextBox.Location = new System.Drawing.Point(100, 231); this.DateTimeFormatTextBox.Name = "DateTimeFormatTextBox"; this.DateTimeFormatTextBox.Size = new System.Drawing.Size(229, 20); this.DateTimeFormatTextBox.TabIndex = 11; this.DateTimeFormatTextBox.Text = "yyyy.MM.dd HH:mm:ss"; this.toolTip1.SetToolTip(this.DateTimeFormatTextBox, "the datetime format used in the file"); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(7, 237); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(85, 13); this.label5.TabIndex = 12; this.label5.Text = "DateTime format"; this.toolTip1.SetToolTip(this.label5, "change the datetime format"); // // FileColumnsLabel // this.FileColumnsLabel.AutoSize = true; this.FileColumnsLabel.Location = new System.Drawing.Point(4, 170); this.FileColumnsLabel.Name = "FileColumnsLabel"; this.FileColumnsLabel.Size = new System.Drawing.Size(78, 13); this.FileColumnsLabel.TabIndex = 9; this.FileColumnsLabel.Text = "Columns Setup"; // // ColumnsInCSVTextBox // this.ColumnsInCSVTextBox.Location = new System.Drawing.Point(100, 170); this.ColumnsInCSVTextBox.Name = "ColumnsInCSVTextBox"; this.ColumnsInCSVTextBox.Size = new System.Drawing.Size(229, 20); this.ColumnsInCSVTextBox.TabIndex = 10; // // CSVFormLoader // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(391, 459); this.Controls.Add(this.label5); this.Controls.Add(this.DateTimeFormatTextBox); this.Controls.Add(this.ColumnsInCSVTextBox); this.Controls.Add(this.FileColumnsLabel); this.Controls.Add(this.MarketDataTypesListBox); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.CSVFormatsCombo); this.Controls.Add(this.textBox1); this.Controls.Add(this.button1); this.Controls.Add(this.statusStrip1); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "CSVFormLoader"; this.ShowIcon = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "CSVFormLoader"; this.Load += new System.EventHandler(this.CSVFormLoader_Load); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.ComboBox CSVFormatsCombo; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.Label label4; private System.Windows.Forms.ListBox MarketDataTypesListBox; private System.Windows.Forms.Label FileColumnsLabel; private System.Windows.Forms.TextBox ColumnsInCSVTextBox; private System.Windows.Forms.Label label5; public System.Windows.Forms.TextBox DateTimeFormatTextBox; } }
/* * 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 CSJ2K; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Reflection; using System.Text; namespace OpenSim.Region.CoreModules.Agent.TextureSender { public delegate void J2KDecodeDelegate(UUID assetID); [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "J2KDecoderModule")] public class J2KDecoderModule : ISharedRegionModule, IJ2KDecoder { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary>Temporarily holds deserialized layer data information in memory</summary> private readonly ExpiringCache<UUID, OpenJPEG.J2KLayerInfo[]> m_decodedCache = new ExpiringCache<UUID, OpenJPEG.J2KLayerInfo[]>(); /// <summary>List of client methods to notify of results of decode</summary> private readonly Dictionary<UUID, List<DecodedCallback>> m_notifyList = new Dictionary<UUID, List<DecodedCallback>>(); /// <summary>Cache that will store decoded JPEG2000 layer boundary data</summary> private IImprovedAssetCache m_cache; /// <summary>Reference to a scene (doesn't matter which one as long as it can load the cache module)</summary> private UUID m_CreatorID = UUID.Zero; private Scene m_scene; private IImprovedAssetCache Cache { get { if (m_cache == null) m_cache = m_scene.RequestModuleInterface<IImprovedAssetCache>(); return m_cache; } } #region ISharedRegionModule private bool m_useCSJ2K = true; public J2KDecoderModule() { } public string Name { get { return "J2KDecoderModule"; } } public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene scene) { if (m_scene == null) { m_scene = scene; m_CreatorID = scene.RegionInfo.RegionID; } scene.RegisterModuleInterface<IJ2KDecoder>(this); } public void Close() { } public void Initialise(IConfigSource source) { IConfig startupConfig = source.Configs["Startup"]; if (startupConfig != null) { m_useCSJ2K = startupConfig.GetBoolean("UseCSJ2K", m_useCSJ2K); } } public void PostInitialise() { } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { if (m_scene == scene) m_scene = null; } #endregion ISharedRegionModule #region IJ2KDecoder public void BeginDecode(UUID assetID, byte[] j2kData, DecodedCallback callback) { OpenJPEG.J2KLayerInfo[] result; // If it's cached, return the cached results if (m_decodedCache.TryGetValue(assetID, out result)) { // m_log.DebugFormat( // "[J2KDecoderModule]: Returning existing cached {0} layers j2k decode for {1}", // result.Length, assetID); callback(assetID, result); } else { // Not cached, we need to decode it. // Add to notify list and start decoding. // Next request for this asset while it's decoding will only be added to the notify list // once this is decoded, requests will be served from the cache and all clients in the notifylist will be updated bool decode = false; lock (m_notifyList) { if (m_notifyList.ContainsKey(assetID)) { m_notifyList[assetID].Add(callback); } else { List<DecodedCallback> notifylist = new List<DecodedCallback>(); notifylist.Add(callback); m_notifyList.Add(assetID, notifylist); decode = true; } } // Do Decode! if (decode) Util.FireAndForget(delegate { Decode(assetID, j2kData); }); } } public bool Decode(UUID assetID, byte[] j2kData) { OpenJPEG.J2KLayerInfo[] layers; int components; return Decode(assetID, j2kData, out layers, out components); } public bool Decode(UUID assetID, byte[] j2kData, out OpenJPEG.J2KLayerInfo[] layers, out int components) { return DoJ2KDecode(assetID, j2kData, out layers, out components); } public Image DecodeToImage(byte[] j2kData) { if (m_useCSJ2K) return J2kImage.FromBytes(j2kData); else { ManagedImage mimage; Image image; if (OpenJPEG.DecodeToImage(j2kData, out mimage, out image)) { mimage = null; return image; } else return null; } } #endregion IJ2KDecoder private OpenJPEG.J2KLayerInfo[] CreateDefaultLayers(int j2kLength) { OpenJPEG.J2KLayerInfo[] layers = new OpenJPEG.J2KLayerInfo[5]; for (int i = 0; i < layers.Length; i++) layers[i] = new OpenJPEG.J2KLayerInfo(); // These default layer sizes are based on a small sampling of real-world texture data // with extra padding thrown in for good measure. This is a worst case fallback plan // and may not gracefully handle all real world data layers[0].Start = 0; layers[1].Start = (int)((float)j2kLength * 0.02f); layers[2].Start = (int)((float)j2kLength * 0.05f); layers[3].Start = (int)((float)j2kLength * 0.20f); layers[4].Start = (int)((float)j2kLength * 0.50f); layers[0].End = layers[1].Start - 1; layers[1].End = layers[2].Start - 1; layers[2].End = layers[3].Start - 1; layers[3].End = layers[4].Start - 1; layers[4].End = j2kLength; return layers; } /// <summary> /// Decode Jpeg2000 Asset Data /// </summary> /// <param name="assetID">UUID of Asset</param> /// <param name="j2kData">JPEG2000 data</param> /// <param name="layers">layer data</param> /// <param name="components">number of components</param> /// <returns>true if decode was successful. false otherwise.</returns> private bool DoJ2KDecode(UUID assetID, byte[] j2kData, out OpenJPEG.J2KLayerInfo[] layers, out int components) { // m_log.DebugFormat( // "[J2KDecoderModule]: Doing J2K decoding of {0} bytes for asset {1}", j2kData.Length, assetID); bool decodedSuccessfully = true; //int DecodeTime = 0; //DecodeTime = Environment.TickCount; // We don't get this from CSJ2K. Is it relevant? components = 0; if (!TryLoadCacheForAsset(assetID, out layers)) { if (m_useCSJ2K) { try { List<int> layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(new MemoryStream(j2kData)); if (layerStarts != null && layerStarts.Count > 0) { layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count]; for (int i = 0; i < layerStarts.Count; i++) { OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo(); if (i == 0) layer.Start = 0; else layer.Start = layerStarts[i]; if (i == layerStarts.Count - 1) layer.End = j2kData.Length; else layer.End = layerStarts[i + 1] - 1; layers[i] = layer; } } } catch (Exception ex) { m_log.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " + assetID + ": " + ex.Message); decodedSuccessfully = false; } } else { if (!OpenJPEG.DecodeLayerBoundaries(j2kData, out layers, out components)) { m_log.Warn("[J2KDecoderModule]: OpenJPEG failed to decode texture " + assetID); decodedSuccessfully = false; } } if (layers == null || layers.Length == 0) { m_log.Warn("[J2KDecoderModule]: Failed to decode layer data for texture " + assetID + ", guessing sane defaults"); // Layer decoding completely failed. Guess at sane defaults for the layer boundaries layers = CreateDefaultLayers(j2kData.Length); decodedSuccessfully = false; } // Cache Decoded layers SaveFileCacheForAsset(assetID, layers); } // Notify Interested Parties lock (m_notifyList) { if (m_notifyList.ContainsKey(assetID)) { foreach (DecodedCallback d in m_notifyList[assetID]) { if (d != null) d.DynamicInvoke(assetID, layers); } m_notifyList.Remove(assetID); } } return decodedSuccessfully; } private void SaveFileCacheForAsset(UUID AssetId, OpenJPEG.J2KLayerInfo[] Layers) { m_decodedCache.AddOrUpdate(AssetId, Layers, TimeSpan.FromMinutes(10)); if (Cache != null) { string assetID = "j2kCache_" + AssetId.ToString(); AssetBase layerDecodeAsset = new AssetBase(assetID, assetID, (sbyte)AssetType.Notecard, m_CreatorID.ToString()); layerDecodeAsset.Local = true; layerDecodeAsset.Temporary = true; #region Serialize Layer Data StringBuilder stringResult = new StringBuilder(); string strEnd = "\n"; for (int i = 0; i < Layers.Length; i++) { if (i == Layers.Length - 1) strEnd = String.Empty; stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd); } layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString()); #endregion Serialize Layer Data Cache.Cache(layerDecodeAsset); } } private bool TryLoadCacheForAsset(UUID AssetId, out OpenJPEG.J2KLayerInfo[] Layers) { if (m_decodedCache.TryGetValue(AssetId, out Layers)) { return true; } else if (Cache != null) { string assetName = "j2kCache_" + AssetId.ToString(); AssetBase layerDecodeAsset = Cache.Get(assetName); if (layerDecodeAsset != null) { #region Deserialize Layer Data string readResult = Util.UTF8.GetString(layerDecodeAsset.Data); string[] lines = readResult.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); if (lines.Length == 0) { m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (empty) " + assetName); Cache.Expire(assetName); return false; } Layers = new OpenJPEG.J2KLayerInfo[lines.Length]; for (int i = 0; i < lines.Length; i++) { string[] elements = lines[i].Split('|'); if (elements.Length == 3) { int element1, element2; try { element1 = Convert.ToInt32(elements[0]); element2 = Convert.ToInt32(elements[1]); } catch (FormatException) { m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (format) " + assetName); Cache.Expire(assetName); return false; } Layers[i] = new OpenJPEG.J2KLayerInfo(); Layers[i].Start = element1; Layers[i].End = element2; } else { m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (layout) " + assetName); Cache.Expire(assetName); return false; } } #endregion Deserialize Layer Data return true; } } return false; } } }
using System; using System.Runtime.InteropServices; namespace Torshify.Core.Native { internal partial class Spotify { internal delegate void ArtistBrowseCompleteCallback(IntPtr browsePtr, IntPtr userDataPtr); /// <summary> /// Check if the artist object is populated with data. /// </summary> /// <param name="artistPtr">The artist object.</param> /// <returns>True if metadata is present, false if not.</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool sp_artist_is_loaded(IntPtr artistPtr); /// <summary> /// Return name of artist. /// </summary> /// <param name="artistPtr">Artist object.</param> /// <returns>Name of artist. Returned string is valid as long as the artist object stays allocated /// and no longer than the next call to <c>sp_session_process_events()</c>.</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MarshalPtrToUtf8))] internal static extern string sp_artist_name(IntPtr artistPtr); /// <summary> /// Increase the reference count of an artist. /// </summary> /// <param name="artistPtr">The artist.</param> [DllImport("libspotify")] internal static extern Error sp_artist_add_ref(IntPtr artistPtr); /// <summary> /// Decrease the reference count of an artist. /// </summary> /// <param name="artistPtr">The artist.</param> [DllImport("libspotify")] internal static extern Error sp_artist_release(IntPtr artistPtr); /// <summary> /// Return portrait for artist /// </summary> /// <param name="artistPtr"></param> /// <returns> ID byte sequence that can be passed to sp_image_create() /// If the album has no image or the metadata for the album is not /// loaded yet, this function returns NULL. /// </returns> [DllImport("libspotify")] internal static extern IntPtr sp_artist_portrait(IntPtr artistPtr, ImageSize imageSize); /// <summary> /// Initiate a request for browsing an artist /// /// The user is responsible for freeing the returned artist browse using sp_artistbrowse_release(). This can be done in the callback. /// </summary> /// <param name="sessionPtr">Session object</param> /// <param name="artistPtr">Artist to be browsed. The artist metadata does not have to be loaded</param> /// <param name="type">Type of data requested, see the sp_artistbrowse_type enum for details</param> /// <param name="callback">Callback to be invoked when browsing has been completed. Pass NULL if you are not interested in this event.</param> /// <param name="userDataPtr">Userdata passed to callback.</param> /// <returns>Artist browse object</returns> [DllImport("libspotify")] internal static extern IntPtr sp_artistbrowse_create(IntPtr sessionPtr, IntPtr artistPtr, ArtistBrowseType type, ArtistBrowseCompleteCallback callback, IntPtr userDataPtr); /// <summary> /// Check if an artist browse request is completed /// </summary> /// <param name="artistBrowsePtr"Artist browse object</param> /// <returns>True if browsing is completed, false if not</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool sp_artistbrowse_is_loaded(IntPtr artistBrowsePtr); /// <summary> /// Check if browsing returned an error code. /// </summary> /// <param name="artistBrowsePtr">Artist browse object</param> /// <returns></returns> [DllImport("libspotify")] internal static extern Error sp_artistbrowse_error(IntPtr artistBrowsePtr); /// <summary> /// Given an artist browse object, return a pointer to its artist object /// </summary> /// <param name="artistBrowsePtr">Artist browse object</param> /// <returns>Artist object</returns> [DllImport("libspotify")] internal static extern IntPtr sp_artistbrowse_artist(IntPtr artistBrowsePtr); /// <summary> /// Given an artist browse object, return number of portraits available /// </summary> /// <param name="artistBrowsePtr">Artist browse object</param> /// <returns>Number of portraits for given artist</returns> [DllImport("libspotify")] internal static extern int sp_artistbrowse_num_portraits(IntPtr artistBrowsePtr); /// <summary> /// Return image ID representing a portrait of the artist /// </summary> /// <param name="browsePtr">Artist object</param> /// <param name="index">The index of the portrait. Should be in the interval [0, sp_artistbrowse_num_portraits() - 1]</param> /// <returns>ID byte sequence that can be passed to sp_image_create()</returns> //[DllImport("libspotify")] //internal static extern byte[] sp_artistbrowse_portrait(IntPtr browsePtr, int index); [DllImport("libspotify")] internal static extern IntPtr sp_artistbrowse_portrait(IntPtr browsePtr, int index); /// <summary> /// Given an artist browse object, return number of tracks /// </summary> /// <param name="artistBrowsePtr">Artist browse object</param> /// <returns>Number of tracks for given artist</returns> [DllImport("libspotify")] internal static extern int sp_artistbrowse_num_tracks(IntPtr artistBrowsePtr); /// <summary> /// Given an artist browse object, return one of its tracks /// </summary> /// <param name="browsePtr">Album browse object</param> /// <param name="index">The index for the track. Should be in the interval [0, sp_artistbrowse_num_tracks() - 1]</param> /// <returns>A track object, or NULL if the index is out of range.</returns> [DllImport("libspotify")] internal static extern IntPtr sp_artistbrowse_track(IntPtr browsePtr, int index); /// <summary> /// Given an artist browse object, return number of albums /// </summary> /// <param name="artistBrowsePtr">Artist browse object</param> /// <returns>Number of albums for given artist</returns> [DllImport("libspotify")] internal static extern int sp_artistbrowse_num_albums(IntPtr artistBrowsePtr); /// <summary> /// Given an artist browse object, return one of its albums /// </summary> /// <param name="browsePtr">Album browse object</param> /// <param name="index">The index for the album. Should be in the interval [0, sp_artistbrowse_num_albums() - 1]</param> /// <returns>A track object, or NULL if the index is out of range.</returns> [DllImport("libspotify")] internal static extern IntPtr sp_artistbrowse_album(IntPtr browsePtr, int index); /// <summary> /// Given an artist browse object, return number of similar artists /// </summary> /// <param name="artistBrowsePtr">Artist browse object</param> /// <returns>Number of similar artists for given artist</returns> [DllImport("libspotify")] internal static extern int sp_artistbrowse_num_similar_artists(IntPtr artistBrowsePtr); /// <summary> /// Given an artist browse object, return a similar artist by index /// </summary> /// <param name="browsePtr">Album browse object</param> /// <param name="index"> The index for the artist. Should be in the interval [0, sp_artistbrowse_num_similar_artists() - 1]</param> /// <returns>A pointer to an artist object.</returns> [DllImport("libspotify")] internal static extern IntPtr sp_artistbrowse_similar_artist(IntPtr browsePtr, int index); /// <summary> /// Given an artist browse object, return the artists biography /// /// This function must be called from the same thread that did sp_session_create() /// </summary> /// <param name="browsePtr">Artist browse object</param> /// <returns>Biography string in UTF-8 format. Returned string is valid as long as the album object stays allocated and no longer than the next call to sp_session_process_events()</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MarshalPtrToUtf8))] internal static extern string sp_artistbrowse_biography(IntPtr browsePtr); /// <summary> /// Increase the reference count of an artist browse result /// </summary> /// <param name="browsePtr"> Album artist object.</param> [DllImport("libspotify")] internal static extern Error sp_artistbrowse_add_ref(IntPtr browsePtr); /// <summary> /// Decrease the reference count of an artist browse result /// </summary> /// <param name="browsePtr"> artist browse object.</param> [DllImport("libspotify")] internal static extern Error sp_artistbrowse_release(IntPtr browsePtr); /// <summary> /// Return the time (in ms) that was spent waiting for the Spotify backend to serve the request /// /// -1 if the request was served from the local cache /// If the result is not yet loaded the return value is undefined /// </summary> /// <param name="browsePtr"> artist browse object.</param> [DllImport("libspotify")] internal static extern int sp_artistbrowse_backend_request_duration(IntPtr browsePtr); /// <summary> /// Given an artist browse object, return number of tophit tracks /// This is a set of tracks for the artist with highest popularity /// </summary> /// <param name="browsePtr"></param> /// <returns></returns> [DllImport("libspotify")] internal static extern int sp_artistbrowse_num_tophit_tracks(IntPtr browsePtr); /// <summary> /// Given an artist browse object, return one of its tophit tracks /// This is a set of tracks for the artist with highest popularity /// </summary> /// <param name="browsePtr"></param> /// <param name="index"></param> /// <returns></returns> [DllImport("libspotify")] internal static extern IntPtr sp_artistbrowse_tophit_track(IntPtr browsePtr, int index); } }
using System; using System.Diagnostics; using System.Threading.Tasks; namespace Lski.Fn { public static partial class ResultExtensionsAsync { /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result> OnFailure(this Task<Result> task, Func<Error, Result> func) { var result = await task.ConfigureAwait(false); return result.OnFailure(func); } /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result> OnFailure(this Task<Result> task, Func<Error, Error> func) { var result = await task.ConfigureAwait(false); return result.IsFailure ? Result.Fail(func(result.Error)) : result; } /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result> OnFailure(this Task<Result> task, Func<Error, string> func) { var result = await task.ConfigureAwait(false); return result.IsFailure ? Result.Fail(func(result.Error)) : result; } /// <summary> /// If an unsuccessful result (a failure) the function is run and the original result is returned. /// </summary> [DebuggerStepThrough] public static async Task<Result> OnFailure(this Task<Result> task, Action<Error> action) { var result = await task.ConfigureAwait(false); return result.OnFailure(action); } /// <summary> /// If an unsuccessful result (a failure) the function is run and the original result is returned. /// </summary> [DebuggerStepThrough] public static async Task<Result> OnFailure(this Task<Result> task, Action action) { var result = await task.ConfigureAwait(false); return result.OnFailure(action); } /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result<T>> OnFailure<T>(this Task<Result<T>> task, Func<Error, Result<T>> func) { var result = await task.ConfigureAwait(false); return result.OnFailure(func); } /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result<T>> OnFailure<T>(this Task<Result<T>> task, Func<Error, Error> func) { var result = await task.ConfigureAwait(false); return result.OnFailure(func); } /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result<T>> OnFailure<T>(this Task<Result<T>> task, Func<Error, string> func) { var result = await task.ConfigureAwait(false); return result.OnFailure(func); } /// <summary> /// If an unsuccessful result (a failure) the function is run and the original result is returned. /// </summary> [DebuggerStepThrough] public static async Task<Result<T>> OnFailure<T>(this Task<Result<T>> task, Action<string> action) { var result = await task.ConfigureAwait(false); return result.OnFailure(action); } /// <summary> /// If an unsuccessful result (a failure) the function is run and the original result is returned. /// </summary> [DebuggerStepThrough] public static async Task<Result<T>> OnFailure<T>(this Task<Result<T>> task, Action action) { var result = await task.ConfigureAwait(false); return result.OnFailure(action); } /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result> OnFailure(this Result result, Func<Error, Task<Result>> func) { if (result.IsFailure) { return result; } return await func(result.Error).ConfigureAwait(false); } /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result<T>> OnFailure<T>(this Result<T> result, Func<Error, Task<Result<T>>> func) { if (result.IsFailure) { return result; } return await func(result.Error).ConfigureAwait(false); } /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result<T>> OnFailure<T>(this Result<T> result, Func<Error, Task<Error>> func) { if (result.IsFailure) { return result; } var err = await func(result.Error).ConfigureAwait(false); return Result.Fail<T>(err); } /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result<T>> OnFailure<T>(this Result<T> result, Func<Error, Task<string>> func) { if (result.IsFailure) { return result; } var err = await func(result.Error).ConfigureAwait(false); return Result.Fail<T>(err); } /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result> OnFailure(this Task<Result> task, Func<Error, Task<Result>> func) { var result = await task.ConfigureAwait(false); if (result.IsFailure) { return result; } return await func(result.Error).ConfigureAwait(false); } /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result<T>> OnFailure<T>(this Task<Result<T>> task, Func<Error, Task<Result<T>>> func) { var result = await task.ConfigureAwait(false); if (result.IsFailure) { return result; } return await func(result.Error).ConfigureAwait(false); } /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result<T>> OnFailure<T>(this Task<Result<T>> task, Func<Error, Task<Error>> func) { var result = await task.ConfigureAwait(false); if (result.IsFailure) { return result; } var err = await func(result.Error).ConfigureAwait(false); return Result.Fail<T>(err); } /// <summary> /// If an unsuccessful result (a failure) the function is run and a new Result returned. Returns the original result if successful. /// </summary> [DebuggerStepThrough] public static async Task<Result<T>> OnFailure<T>(this Task<Result<T>> task, Func<Error, Task<string>> func) { var result = await task.ConfigureAwait(false); if (result.IsFailure) { return result; } var err = await func(result.Error).ConfigureAwait(false); return Result.Fail<T>(err); } /// <summary> /// If a failure result throws the exception created by the func /// </summary> [DebuggerStepThrough] public static async Task<Result> OnFailThrow(this Task<Result> task, Func<Error, Exception> func) { var result = await task.ConfigureAwait(false); if (result.IsSuccess) { return result; } throw func(result.Error); } /// <summary> /// If a failure result throws the exception created by the func /// </summary> [DebuggerStepThrough] public static async Task<Result<T>> OnFailThrow<T>(this Task<Result<T>> task, Func<Error, Exception> func) { var result = await task.ConfigureAwait(false); if (result.IsSuccess) { return result; } throw func(result.Error); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.RecoveryServices.Backup; using Microsoft.Azure.Management.RecoveryServices.Backup.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.RecoveryServices.Backup { /// <summary> /// The Resource Manager API includes operations for triggering and /// managing restore actions of the items protected by your Recovery /// Services Vault. /// </summary> internal partial class RestoreOperations : IServiceOperations<RecoveryServicesBackupManagementClient>, IRestoreOperations { /// <summary> /// Initializes a new instance of the RestoreOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal RestoreOperations(RecoveryServicesBackupManagementClient client) { this._client = client; } private RecoveryServicesBackupManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.RecoveryServices.Backup.RecoveryServicesBackupManagementClient. /// </summary> public RecoveryServicesBackupManagementClient Client { get { return this._client; } } /// <summary> /// The Trigger Restore Operation starts an operation in the service /// which triggers the restore of the specified item in the specified /// container in your Recovery Services Vault based on the specified /// recovery point ID. This is an asynchronous operation. To determine /// whether the backend service has finished processing the request, /// call Get Protected Item Operation Result API. /// </summary> /// <param name='resourceGroupName'> /// Required. Resource group name of your recovery services vault. /// </param> /// <param name='resourceName'> /// Required. Name of your recovery services vault. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='fabricName'> /// Optional. Fabric name of the protected item. /// </param> /// <param name='containerName'> /// Optional. Name of the container where the protected item belongs to. /// </param> /// <param name='protectedItemName'> /// Optional. Name of the protected item whose recovery points are to /// be fetched. /// </param> /// <param name='recoveryPointId'> /// Optional. ID of the recovery point whose details are to be fetched. /// </param> /// <param name='request'> /// Optional. Restore request for the backup item. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Base recovery job response for all the asynchronous operations. /// </returns> public async Task<BaseRecoveryServicesJobResponse> TriggerRestoreAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName, string containerName, string protectedItemName, string recoveryPointId, TriggerRestoreRequest request, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (request != null) { if (request.Item != null) { if (request.Item.Properties == null) { throw new ArgumentNullException("request.Item.Properties"); } } } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("protectedItemName", protectedItemName); tracingParameters.Add("recoveryPointId", recoveryPointId); tracingParameters.Add("request", request); TracingAdapter.Enter(invocationId, this, "TriggerRestoreAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/"; url = url + "vaults"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/backupFabrics/"; if (fabricName != null) { url = url + Uri.EscapeDataString(fabricName); } url = url + "/protectionContainers/"; if (containerName != null) { url = url + Uri.EscapeDataString(containerName); } url = url + "/protectedItems/"; if (protectedItemName != null) { url = url + Uri.EscapeDataString(protectedItemName); } url = url + "/recoveryPoints/"; if (recoveryPointId != null) { url = url + Uri.EscapeDataString(recoveryPointId); } url = url + "/restore"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-05-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; if (request != null) { if (request.Item != null) { JObject itemValue = new JObject(); requestDoc = itemValue; JObject propertiesValue = new JObject(); itemValue["properties"] = propertiesValue; if (request.Item.Properties is IaasVMRestoreRequest) { propertiesValue["objectType"] = "IaasVMRestoreRequest"; IaasVMRestoreRequest derived = ((IaasVMRestoreRequest)request.Item.Properties); if (derived.RecoveryPointId != null) { propertiesValue["recoveryPointId"] = derived.RecoveryPointId; } if (derived.RecoveryType != null) { propertiesValue["recoveryType"] = derived.RecoveryType; } if (derived.StorageAccountId != null) { propertiesValue["storageAccountId"] = derived.StorageAccountId; } if (derived.VirtualMachineName != null) { propertiesValue["virtualMachineName"] = derived.VirtualMachineName; } propertiesValue["createNewCloudService"] = derived.CreateNewCloudService; if (derived.CloudServiceOrResourceGroup != null) { propertiesValue["cloudServiceOrResourceGroup"] = derived.CloudServiceOrResourceGroup; } if (derived.CloudServiceOrResourceGroupId != null) { propertiesValue["cloudServiceOrResourceGroupId"] = derived.CloudServiceOrResourceGroupId; } if (derived.VirtualNetworkId != null) { propertiesValue["virtualNetworkId"] = derived.VirtualNetworkId; } if (derived.Region != null) { propertiesValue["region"] = derived.Region; } if (derived.AffinityGroup != null) { propertiesValue["affinityGroup"] = derived.AffinityGroup; } if (derived.SubnetId != null) { propertiesValue["subnetId"] = derived.SubnetId; } } } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result BaseRecoveryServicesJobResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new BaseRecoveryServicesJobResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); result.Location = locationInstance; } JToken azureAsyncOperationValue = responseDoc["azureAsyncOperation"]; if (azureAsyncOperationValue != null && azureAsyncOperationValue.Type != JTokenType.Null) { string azureAsyncOperationInstance = ((string)azureAsyncOperationValue); result.AzureAsyncOperation = azureAsyncOperationInstance; } JToken retryAfterValue = responseDoc["retryAfter"]; if (retryAfterValue != null && retryAfterValue.Type != JTokenType.Null) { string retryAfterInstance = ((string)retryAfterValue); result.RetryAfter = retryAfterInstance; } JToken statusValue = responseDoc["Status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)statusValue), true)); result.Status = statusInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Headers.Contains("Location")) { result.Location = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace Thrift.Transport.Client { // ReSharper disable once InconsistentNaming public class THttpTransport : TTransport { private readonly X509Certificate[] _certificates; private readonly Uri _uri; private int _connectTimeout = 30000; // Timeouts in milliseconds private HttpClient _httpClient; private Stream _inputStream; private MemoryStream _outputStream = new MemoryStream(); private bool _isDisposed; public THttpTransport(Uri uri, IDictionary<string, string> customRequestHeaders = null, string userAgent = null) : this(uri, Enumerable.Empty<X509Certificate>(), customRequestHeaders, userAgent) { } public THttpTransport(Uri uri, IEnumerable<X509Certificate> certificates, IDictionary<string, string> customRequestHeaders, string userAgent = null) { _uri = uri; _certificates = (certificates ?? Enumerable.Empty<X509Certificate>()).ToArray(); if (!string.IsNullOrEmpty(userAgent)) UserAgent = userAgent; // due to current bug with performance of Dispose in netcore https://github.com/dotnet/corefx/issues/8809 // this can be switched to default way (create client->use->dispose per flush) later _httpClient = CreateClient(customRequestHeaders); } // According to RFC 2616 section 3.8, the "User-Agent" header may not carry a version number public readonly string UserAgent = "Thrift netstd THttpClient"; public override bool IsOpen => true; public HttpRequestHeaders RequestHeaders => _httpClient.DefaultRequestHeaders; public MediaTypeHeaderValue ContentType { get; set; } public override async Task OpenAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override void Close() { if (_inputStream != null) { _inputStream.Dispose(); _inputStream = null; } if (_outputStream != null) { _outputStream.Dispose(); _outputStream = null; } if (_httpClient != null) { _httpClient.Dispose(); _httpClient = null; } } public override async ValueTask<int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<int>(cancellationToken); } if (_inputStream == null) { throw new TTransportException(TTransportException.ExceptionType.NotOpen, "No request has been sent"); } try { var ret = await _inputStream.ReadAsync(buffer, offset, length, cancellationToken); if (ret == -1) { throw new TTransportException(TTransportException.ExceptionType.EndOfFile, "No more data available"); } return ret; } catch (IOException iox) { throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString()); } } public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } await _outputStream.WriteAsync(buffer, offset, length, cancellationToken); } private HttpClient CreateClient(IDictionary<string, string> customRequestHeaders) { var handler = new HttpClientHandler(); handler.ClientCertificates.AddRange(_certificates); handler.AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip; var httpClient = new HttpClient(handler); if (_connectTimeout > 0) { httpClient.Timeout = TimeSpan.FromMilliseconds(_connectTimeout); } httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-thrift")); httpClient.DefaultRequestHeaders.UserAgent.TryParseAdd(UserAgent); httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate")); httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); if (customRequestHeaders != null) { foreach (var item in customRequestHeaders) { httpClient.DefaultRequestHeaders.Add(item.Key, item.Value); } } return httpClient; } public override async Task FlushAsync(CancellationToken cancellationToken) { try { _outputStream.Seek(0, SeekOrigin.Begin); using (var contentStream = new StreamContent(_outputStream)) { contentStream.Headers.ContentType = ContentType ?? new MediaTypeHeaderValue(@"application/x-thrift"); var response = (await _httpClient.PostAsync(_uri, contentStream, cancellationToken)).EnsureSuccessStatusCode(); _inputStream?.Dispose(); _inputStream = await response.Content.ReadAsStreamAsync(); if (_inputStream.CanSeek) { _inputStream.Seek(0, SeekOrigin.Begin); } } } catch (IOException iox) { throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString()); } catch (HttpRequestException wx) { throw new TTransportException(TTransportException.ExceptionType.Unknown, "Couldn't connect to server: " + wx); } catch (Exception ex) { throw new TTransportException(TTransportException.ExceptionType.Unknown, ex.Message); } finally { _outputStream = new MemoryStream(); } } // IDisposable protected override void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { _inputStream?.Dispose(); _outputStream?.Dispose(); _httpClient?.Dispose(); } } _isDisposed = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //----------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Runtime; using System.Runtime.Serialization; using System.Security; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using System.Xml; using System.Xml.Serialization; namespace System.ServiceModel.Description { public class XmlSerializerOperationBehavior : IOperationBehavior { private readonly Reflector.OperationReflector _reflector; private readonly bool _builtInOperationBehavior; public XmlSerializerOperationBehavior(OperationDescription operation) : this(operation, null) { } public XmlSerializerOperationBehavior(OperationDescription operation, XmlSerializerFormatAttribute attribute) { if (operation == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("operation"); Reflector parentReflector = new Reflector(operation.DeclaringContract.Namespace, operation.DeclaringContract.ContractType); _reflector = parentReflector.ReflectOperation(operation, attribute ?? new XmlSerializerFormatAttribute()); } internal XmlSerializerOperationBehavior(OperationDescription operation, XmlSerializerFormatAttribute attribute, Reflector parentReflector) : this(operation, attribute) { // used by System.ServiceModel.Web _reflector = parentReflector.ReflectOperation(operation, attribute ?? new XmlSerializerFormatAttribute()); } private XmlSerializerOperationBehavior(Reflector.OperationReflector reflector, bool builtInOperationBehavior) { Fx.Assert(reflector != null, ""); _reflector = reflector; _builtInOperationBehavior = builtInOperationBehavior; } internal Reflector.OperationReflector OperationReflector { get { return _reflector; } } internal bool IsBuiltInOperationBehavior { get { return _builtInOperationBehavior; } } public XmlSerializerFormatAttribute XmlSerializerFormatAttribute { get { return _reflector.Attribute; } } internal static XmlSerializerOperationFormatter CreateOperationFormatter(OperationDescription operation) { return new XmlSerializerOperationBehavior(operation).CreateFormatter(); } internal static XmlSerializerOperationFormatter CreateOperationFormatter(OperationDescription operation, XmlSerializerFormatAttribute attr) { return new XmlSerializerOperationBehavior(operation, attr).CreateFormatter(); } internal static void AddBehaviors(ContractDescription contract) { AddBehaviors(contract, false); } internal static void AddBuiltInBehaviors(ContractDescription contract) { AddBehaviors(contract, true); } private static void AddBehaviors(ContractDescription contract, bool builtInOperationBehavior) { Reflector reflector = new Reflector(contract.Namespace, contract.ContractType); foreach (OperationDescription operation in contract.Operations) { Reflector.OperationReflector operationReflector = reflector.ReflectOperation(operation); if (operationReflector != null) { bool isInherited = operation.DeclaringContract != contract; if (!isInherited) { operation.Behaviors.Add(new XmlSerializerOperationBehavior(operationReflector, builtInOperationBehavior)); } } } } internal XmlSerializerOperationFormatter CreateFormatter() { return new XmlSerializerOperationFormatter(_reflector.Operation, _reflector.Attribute, _reflector.Request, _reflector.Reply); } private XmlSerializerFaultFormatter CreateFaultFormatter(SynchronizedCollection<FaultContractInfo> faultContractInfos) { return new XmlSerializerFaultFormatter(faultContractInfos, _reflector.XmlSerializerFaultContractInfos); } void IOperationBehavior.Validate(OperationDescription description) { } void IOperationBehavior.AddBindingParameters(OperationDescription description, BindingParameterCollection parameters) { } void IOperationBehavior.ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch) { if (description == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description"); if (dispatch == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dispatch"); if (dispatch.Formatter == null) { dispatch.Formatter = (IDispatchMessageFormatter)CreateFormatter(); dispatch.DeserializeRequest = _reflector.RequestRequiresSerialization; dispatch.SerializeReply = _reflector.ReplyRequiresSerialization; } if (_reflector.Attribute.SupportFaults && !dispatch.IsFaultFormatterSetExplicit) { dispatch.FaultFormatter = (IDispatchFaultFormatter)CreateFaultFormatter(dispatch.FaultContractInfos); } } void IOperationBehavior.ApplyClientBehavior(OperationDescription description, ClientOperation proxy) { if (description == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description"); if (proxy == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("proxy"); if (proxy.Formatter == null) { proxy.Formatter = (IClientMessageFormatter)CreateFormatter(); proxy.SerializeRequest = _reflector.RequestRequiresSerialization; proxy.DeserializeReply = _reflector.ReplyRequiresSerialization; } if (_reflector.Attribute.SupportFaults && !proxy.IsFaultFormatterSetExplicit) proxy.FaultFormatter = (IClientFaultFormatter)CreateFaultFormatter(proxy.FaultContractInfos); } public Collection<XmlMapping> GetXmlMappings() { var mappings = new Collection<XmlMapping>(); if (OperationReflector.Request != null && OperationReflector.Request.HeadersMapping != null) mappings.Add(OperationReflector.Request.HeadersMapping); if (OperationReflector.Request != null && OperationReflector.Request.BodyMapping != null) mappings.Add(OperationReflector.Request.BodyMapping); if (OperationReflector.Reply != null && OperationReflector.Reply.HeadersMapping != null) mappings.Add(OperationReflector.Reply.HeadersMapping); if (OperationReflector.Reply != null && OperationReflector.Reply.BodyMapping != null) mappings.Add(OperationReflector.Reply.BodyMapping); return mappings; } // helper for reflecting operations internal class Reflector { private readonly XmlSerializerImporter _importer; private readonly SerializerGenerationContext _generation; private Collection<OperationReflector> _operationReflectors = new Collection<OperationReflector>(); private object _thisLock = new object(); internal Reflector(string defaultNs, Type type) { _importer = new XmlSerializerImporter(defaultNs); _generation = new SerializerGenerationContext(type); } internal void EnsureMessageInfos() { lock (_thisLock) { foreach (OperationReflector operationReflector in _operationReflectors) { operationReflector.EnsureMessageInfos(); } } } private static XmlSerializerFormatAttribute FindAttribute(OperationDescription operation) { Type contractType = operation.DeclaringContract != null ? operation.DeclaringContract.ContractType : null; XmlSerializerFormatAttribute contractFormatAttribute = contractType != null ? TypeLoader.GetFormattingAttribute(contractType, null) as XmlSerializerFormatAttribute : null; return TypeLoader.GetFormattingAttribute(operation.OperationMethod, contractFormatAttribute) as XmlSerializerFormatAttribute; } // auto-reflects the operation, returning null if no attribute was found or inherited internal OperationReflector ReflectOperation(OperationDescription operation) { XmlSerializerFormatAttribute attr = FindAttribute(operation); if (attr == null) return null; return ReflectOperation(operation, attr); } // overrides the auto-reflection with an attribute internal OperationReflector ReflectOperation(OperationDescription operation, XmlSerializerFormatAttribute attrOverride) { OperationReflector operationReflector = new OperationReflector(this, operation, attrOverride, true/*reflectOnDemand*/); _operationReflectors.Add(operationReflector); return operationReflector; } internal class OperationReflector { private readonly Reflector _parent; internal readonly OperationDescription Operation; internal readonly XmlSerializerFormatAttribute Attribute; internal readonly bool IsEncoded; internal readonly bool IsRpc; internal readonly bool IsOneWay; internal readonly bool RequestRequiresSerialization; internal readonly bool ReplyRequiresSerialization; private readonly string _keyBase; private MessageInfo _request; private MessageInfo _reply; private SynchronizedCollection<XmlSerializerFaultContractInfo> _xmlSerializerFaultContractInfos; internal OperationReflector(Reflector parent, OperationDescription operation, XmlSerializerFormatAttribute attr, bool reflectOnDemand) { Fx.Assert(parent != null, ""); Fx.Assert(operation != null, ""); Fx.Assert(attr != null, ""); OperationFormatter.Validate(operation, attr.Style == OperationFormatStyle.Rpc, attr.IsEncoded); _parent = parent; this.Operation = operation; this.Attribute = attr; IsEncoded = attr.IsEncoded; this.IsRpc = (attr.Style == OperationFormatStyle.Rpc); this.IsOneWay = operation.Messages.Count == 1; this.RequestRequiresSerialization = !operation.Messages[0].IsUntypedMessage; this.ReplyRequiresSerialization = !this.IsOneWay && !operation.Messages[1].IsUntypedMessage; MethodInfo methodInfo = operation.OperationMethod; if (methodInfo == null) { // keyBase needs to be unique within the scope of the parent reflector _keyBase = string.Empty; if (operation.DeclaringContract != null) { _keyBase = operation.DeclaringContract.Name + "," + operation.DeclaringContract.Namespace + ":"; } _keyBase = _keyBase + operation.Name; } else _keyBase = methodInfo.DeclaringType.FullName + ":" + methodInfo.ToString(); foreach (MessageDescription message in operation.Messages) foreach (MessageHeaderDescription header in message.Headers) SetUnknownHeaderInDescription(header); if (!reflectOnDemand) { this.EnsureMessageInfos(); } } private void SetUnknownHeaderInDescription(MessageHeaderDescription header) { if (header.AdditionalAttributesProvider != null) { object[] attrs = header.AdditionalAttributesProvider.GetCustomAttributes(false); foreach (var attr in attrs) { if (attr is XmlAnyElementAttribute) { if (String.IsNullOrEmpty(((XmlAnyElementAttribute)attr).Name)) { header.IsUnknownHeaderCollection = true; } } } } } private string ContractName { get { return this.Operation.DeclaringContract.Name; } } private string ContractNamespace { get { return this.Operation.DeclaringContract.Namespace; } } internal MessageInfo Request { get { _parent.EnsureMessageInfos(); return _request; } } internal MessageInfo Reply { get { _parent.EnsureMessageInfos(); return _reply; } } internal SynchronizedCollection<XmlSerializerFaultContractInfo> XmlSerializerFaultContractInfos { get { _parent.EnsureMessageInfos(); return _xmlSerializerFaultContractInfos; } } internal void EnsureMessageInfos() { if (_request == null) { foreach (Type knownType in Operation.KnownTypes) { if (knownType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxKnownTypeNull, Operation.Name))); _parent._importer.IncludeType(knownType, IsEncoded); } _request = CreateMessageInfo(this.Operation.Messages[0], ":Request"); // We don't do the following check at Net Native runtime because XmlMapping.XsdElementName // is not available at that time. bool skipVerifyXsdElementName = false; #if FEATURE_NETNATIVE skipVerifyXsdElementName = GeneratedXmlSerializers.IsInitialized; #endif if (_request != null && this.IsRpc && this.Operation.IsValidateRpcWrapperName && !skipVerifyXsdElementName && _request.BodyMapping.XsdElementName != this.Operation.Name) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxRpcMessageBodyPartNameInvalid, Operation.Name, this.Operation.Messages[0].MessageName, _request.BodyMapping.XsdElementName, this.Operation.Name))); if (!this.IsOneWay) { _reply = CreateMessageInfo(this.Operation.Messages[1], ":Response"); XmlName responseName = TypeLoader.GetBodyWrapperResponseName(this.Operation.Name); if (_reply != null && this.IsRpc && this.Operation.IsValidateRpcWrapperName && !skipVerifyXsdElementName && _reply.BodyMapping.XsdElementName != responseName.EncodedName) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxRpcMessageBodyPartNameInvalid, Operation.Name, this.Operation.Messages[1].MessageName, _reply.BodyMapping.XsdElementName, responseName.EncodedName))); } if (this.Attribute.SupportFaults) { GenerateXmlSerializerFaultContractInfos(); } } } private void GenerateXmlSerializerFaultContractInfos() { SynchronizedCollection<XmlSerializerFaultContractInfo> faultInfos = new SynchronizedCollection<XmlSerializerFaultContractInfo>(); for (int i = 0; i < this.Operation.Faults.Count; i++) { FaultDescription fault = this.Operation.Faults[i]; FaultContractInfo faultContractInfo = new FaultContractInfo(fault.Action, fault.DetailType, fault.ElementName, fault.Namespace, this.Operation.KnownTypes); XmlQualifiedName elementName; XmlMembersMapping xmlMembersMapping = this.ImportFaultElement(fault, out elementName); SerializerStub serializerStub = _parent._generation.AddSerializer(xmlMembersMapping); faultInfos.Add(new XmlSerializerFaultContractInfo(faultContractInfo, serializerStub, elementName)); } _xmlSerializerFaultContractInfos = faultInfos; } private MessageInfo CreateMessageInfo(MessageDescription message, string key) { if (message.IsUntypedMessage) return null; MessageInfo info = new MessageInfo(); if (message.IsTypedMessage) key = message.MessageType.FullName + ":" + IsEncoded + ":" + IsRpc; XmlMembersMapping headersMapping = LoadHeadersMapping(message, key + ":Headers"); info.SetHeaders(_parent._generation.AddSerializer(headersMapping)); MessagePartDescriptionCollection rpcEncodedTypedMessgeBodyParts; info.SetBody(_parent._generation.AddSerializer(LoadBodyMapping(message, key, out rpcEncodedTypedMessgeBodyParts)), rpcEncodedTypedMessgeBodyParts); CreateHeaderDescriptionTable(message, info, headersMapping); return info; } private void CreateHeaderDescriptionTable(MessageDescription message, MessageInfo info, XmlMembersMapping headersMapping) { int headerNameIndex = 0; OperationFormatter.MessageHeaderDescriptionTable headerDescriptionTable = new OperationFormatter.MessageHeaderDescriptionTable(); info.SetHeaderDescriptionTable(headerDescriptionTable); foreach (MessageHeaderDescription header in message.Headers) { if (header.IsUnknownHeaderCollection) info.SetUnknownHeaderDescription(header); else if (headersMapping != null) { XmlMemberMapping memberMapping = headersMapping[headerNameIndex++]; if (GeneratedXmlSerializers.IsInitialized) { // If GeneratedXmlSerializers has been initialized, we would use the // mappings generated by .Net Native tools. In that case, the mappings // we genrated at Runtime are just fake mapping instance which have // no valid name/namespace. Therefore we cannot do the checks in the // else block. Those checks should have been done during NET Native // precompilation. headerDescriptionTable.Add(header.Name, header.Namespace, header); } else { string headerName, headerNs; if (IsEncoded) { headerName = memberMapping.TypeName; headerNs = memberMapping.TypeNamespace; } else { headerName = memberMapping.XsdElementName; headerNs = memberMapping.Namespace; } if (headerName != header.Name) { if (message.MessageType != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNameMismatchInMessageContract, message.MessageType, header.MemberInfo.Name, header.Name, headerName))); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNameMismatchInOperation, this.Operation.Name, this.Operation.DeclaringContract.Name, this.Operation.DeclaringContract.Namespace, header.Name, headerName))); } if (headerNs != header.Namespace) { if (message.MessageType != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNamespaceMismatchInMessageContract, message.MessageType, header.MemberInfo.Name, header.Namespace, headerNs))); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNamespaceMismatchInOperation, this.Operation.Name, this.Operation.DeclaringContract.Name, this.Operation.DeclaringContract.Namespace, header.Namespace, headerNs))); } headerDescriptionTable.Add(headerName, headerNs, header); } } } } private XmlMembersMapping LoadBodyMapping(MessageDescription message, string mappingKey, out MessagePartDescriptionCollection rpcEncodedTypedMessageBodyParts) { MessagePartDescription returnPart; string wrapperName, wrapperNs; MessagePartDescriptionCollection bodyParts; if (IsEncoded && message.IsTypedMessage && message.Body.WrapperName == null) { MessagePartDescription wrapperPart = GetWrapperPart(message); returnPart = null; rpcEncodedTypedMessageBodyParts = bodyParts = GetWrappedParts(wrapperPart); wrapperName = wrapperPart.Name; wrapperNs = wrapperPart.Namespace; } else { rpcEncodedTypedMessageBodyParts = null; returnPart = OperationFormatter.IsValidReturnValue(message.Body.ReturnValue) ? message.Body.ReturnValue : null; bodyParts = message.Body.Parts; wrapperName = message.Body.WrapperName; wrapperNs = message.Body.WrapperNamespace; } bool isWrapped = (wrapperName != null); bool hasReturnValue = returnPart != null; int paramCount = bodyParts.Count + (hasReturnValue ? 1 : 0); if (paramCount == 0 && !isWrapped) // no need to create serializer { return null; } XmlReflectionMember[] members = new XmlReflectionMember[paramCount]; int paramIndex = 0; if (hasReturnValue) members[paramIndex++] = XmlSerializerHelper.GetXmlReflectionMember(returnPart, IsRpc, IsEncoded, isWrapped); for (int i = 0; i < bodyParts.Count; i++) members[paramIndex++] = XmlSerializerHelper.GetXmlReflectionMember(bodyParts[i], IsRpc, IsEncoded, isWrapped); if (!isWrapped) wrapperNs = ContractNamespace; return ImportMembersMapping(wrapperName, wrapperNs, members, isWrapped, IsRpc, mappingKey); } private MessagePartDescription GetWrapperPart(MessageDescription message) { if (message.Body.Parts.Count != 1) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxRpcMessageMustHaveASingleBody, Operation.Name, message.MessageName))); MessagePartDescription bodyPart = message.Body.Parts[0]; Type bodyObjectType = bodyPart.Type; if (bodyObjectType.BaseType != null && bodyObjectType.BaseType != typeof(object)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxBodyObjectTypeCannotBeInherited, bodyObjectType.FullName))); if (typeof(IEnumerable).IsAssignableFrom(bodyObjectType)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxBodyObjectTypeCannotBeInterface, bodyObjectType.FullName, typeof(IEnumerable).FullName))); if (typeof(IXmlSerializable).IsAssignableFrom(bodyObjectType)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxBodyObjectTypeCannotBeInterface, bodyObjectType.FullName, typeof(IXmlSerializable).FullName))); return bodyPart; } private MessagePartDescriptionCollection GetWrappedParts(MessagePartDescription bodyPart) { Type bodyObjectType = bodyPart.Type; MessagePartDescriptionCollection partList = new MessagePartDescriptionCollection(); foreach (MemberInfo member in bodyObjectType.GetMembers(BindingFlags.Instance | BindingFlags.Public)) { if ((member.MemberType & (MemberTypes.Field | MemberTypes.Property)) == 0) continue; if (member.IsDefined(typeof(SoapIgnoreAttribute), false/*inherit*/)) continue; XmlName xmlName = new XmlName(member.Name); MessagePartDescription part = new MessagePartDescription(xmlName.EncodedName, string.Empty); part.AdditionalAttributesProvider = part.MemberInfo = member; part.Index = part.SerializationPosition = partList.Count; part.Type = (member.MemberType == MemberTypes.Property) ? ((PropertyInfo)member).PropertyType : ((FieldInfo)member).FieldType; if (bodyPart.HasProtectionLevel) part.ProtectionLevel = bodyPart.ProtectionLevel; partList.Add(part); } return partList; } private XmlMembersMapping LoadHeadersMapping(MessageDescription message, string mappingKey) { int headerCount = message.Headers.Count; if (headerCount == 0) return null; if (IsEncoded) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeadersAreNotSupportedInEncoded, message.MessageName))); int unknownHeaderCount = 0, headerIndex = 0; XmlReflectionMember[] members = new XmlReflectionMember[headerCount]; for (int i = 0; i < headerCount; i++) { MessageHeaderDescription header = message.Headers[i]; if (!header.IsUnknownHeaderCollection) { members[headerIndex++] = XmlSerializerHelper.GetXmlReflectionMember(header, false/*isRpc*/, IsEncoded, false/*isWrapped*/); } else { unknownHeaderCount++; } } if (unknownHeaderCount == headerCount) { return null; } if (unknownHeaderCount > 0) { XmlReflectionMember[] newMembers = new XmlReflectionMember[headerCount - unknownHeaderCount]; Array.Copy(members, newMembers, newMembers.Length); members = newMembers; } return ImportMembersMapping(ContractName, ContractNamespace, members, false /*isWrapped*/, false /*isRpc*/, mappingKey); } internal XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, string mappingKey) { string key = mappingKey.StartsWith(":", StringComparison.Ordinal) ? _keyBase + mappingKey : mappingKey; return _parent._importer.ImportMembersMapping(new XmlName(elementName, true /*isEncoded*/), ns, members, hasWrapperElement, rpc, IsEncoded, key); } internal XmlMembersMapping ImportFaultElement(FaultDescription fault, out XmlQualifiedName elementName) { // the number of reflection members is always 1 because there is only one fault detail type XmlReflectionMember[] members = new XmlReflectionMember[1]; XmlName faultElementName = fault.ElementName; string faultNamespace = fault.Namespace; if (faultElementName == null) { XmlTypeMapping mapping = _parent._importer.ImportTypeMapping(fault.DetailType, IsEncoded); faultElementName = new XmlName(mapping.ElementName, IsEncoded); faultNamespace = mapping.Namespace; if (faultElementName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxFaultTypeAnonymous, Operation.Name, fault.DetailType.FullName))); } elementName = new XmlQualifiedName(faultElementName.DecodedName, faultNamespace); members[0] = XmlSerializerHelper.GetXmlReflectionMember(null /*memberName*/, faultElementName, faultNamespace, fault.DetailType, null /*additionalAttributesProvider*/, false /*isMultiple*/, IsEncoded, false /*isWrapped*/); string mappingKey = "fault:" + faultElementName.DecodedName + ":" + faultNamespace; return ImportMembersMapping(faultElementName.EncodedName, faultNamespace, members, false /*hasWrapperElement*/, IsRpc, mappingKey); } } private class XmlSerializerImporter { private readonly string _defaultNs; private XmlReflectionImporter _xmlImporter; private SoapReflectionImporter _soapImporter; private Dictionary<string, XmlMembersMapping> _xmlMappings; private HashSet<Type> _includedTypes; internal XmlSerializerImporter(string defaultNs) { _defaultNs = defaultNs; _xmlImporter = null; _soapImporter = null; } private SoapReflectionImporter SoapImporter { get { if (_soapImporter == null) { _soapImporter = new SoapReflectionImporter(NamingHelper.CombineUriStrings(_defaultNs, "encoded")); } return _soapImporter; } } private XmlReflectionImporter XmlImporter { get { if (_xmlImporter == null) { _xmlImporter = new XmlReflectionImporter(_defaultNs); } return _xmlImporter; } } private Dictionary<string, XmlMembersMapping> XmlMappings { get { if (_xmlMappings == null) { _xmlMappings = new Dictionary<string, XmlMembersMapping>(); } return _xmlMappings; } } private HashSet<Type> IncludedTypes { get { if (_includedTypes == null) { _includedTypes = new HashSet<Type>(); } return _includedTypes; } } internal XmlMembersMapping ImportMembersMapping(XmlName elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool isEncoded, string mappingKey) { XmlMembersMapping mapping; string mappingName = elementName.DecodedName; if (XmlMappings.TryGetValue(mappingKey, out mapping)) { return mapping; } if (isEncoded) mapping = SoapImporter.ImportMembersMapping(mappingName, ns, members, hasWrapperElement, rpc); else mapping = XmlImporter.ImportMembersMapping(mappingName, ns, members, hasWrapperElement, rpc); #if FEATURE_NETNATIVE mapping.SetKeyInternal(mappingKey); #else mapping.SetKey(mappingKey); #endif XmlMappings.Add(mappingKey, mapping); return mapping; } internal XmlTypeMapping ImportTypeMapping(Type type, bool isEncoded) { if (isEncoded) return SoapImporter.ImportTypeMapping(type); else return XmlImporter.ImportTypeMapping(type); } internal void IncludeType(Type knownType, bool isEncoded) { // XmlReflectionImporter.IncludeTypes calls XmlReflectionImporter.ImportTypeMapping to generate mappings // for types and store those mappings. // XmlReflectionImporter.ImportTypeMapping internally uses HashTables for caching imported mappings. // But it's still very costly to call XmlReflectionImporter.ImportTypeMapping because XmlReflectionImporter.ImportTypeMapping // method takes many params and the generated mapping can vary on all those params. XmlReflectionImporter // needs to do some work before it can use its caches. // // In this case, the mapping should only vary on the value of the knownType. // Including a type twice doesn't make any difference than including the type once. Therefore we use // IncludedTypes to store the types that have been included and skip them later. if (IncludedTypes.Contains(knownType)) return; if (isEncoded) SoapImporter.IncludeType(knownType); else XmlImporter.IncludeType(knownType); IncludedTypes.Add(knownType); } } internal class SerializerGenerationContext { private List<XmlMembersMapping> _mappings = new List<XmlMembersMapping>(); private XmlSerializer[] _serializers = null; private Type _type; private object _thisLock = new object(); internal SerializerGenerationContext(Type type) { _type = type; } // returns a stub to a serializer internal SerializerStub AddSerializer(XmlMembersMapping mapping) { int handle = -1; if (mapping != null) { handle = ((IList)_mappings).Add(mapping); } return new SerializerStub(this, mapping, handle); } internal XmlSerializer GetSerializer(int handle) { if (handle < 0) { return null; } if (_serializers == null) { lock (_thisLock) { if (_serializers == null) { _serializers = GenerateSerializers(); } } } return _serializers[handle]; } private XmlSerializer[] GenerateSerializers() { //this.Mappings may have duplicate mappings (for e.g. same message contract is used by more than one operation) //XmlSerializer.FromMappings require unique mappings. The following code uniquifies, calls FromMappings and deuniquifies List<XmlMembersMapping> uniqueMappings = new List<XmlMembersMapping>(); int[] uniqueIndexes = new int[_mappings.Count]; for (int srcIndex = 0; srcIndex < _mappings.Count; srcIndex++) { XmlMembersMapping mapping = _mappings[srcIndex]; int uniqueIndex = uniqueMappings.IndexOf(mapping); if (uniqueIndex < 0) { uniqueMappings.Add(mapping); uniqueIndex = uniqueMappings.Count - 1; } uniqueIndexes[srcIndex] = uniqueIndex; } XmlSerializer[] uniqueSerializers = CreateSerializersFromMappings(uniqueMappings.ToArray(), _type); if (uniqueMappings.Count == _mappings.Count) return uniqueSerializers; XmlSerializer[] serializers = new XmlSerializer[_mappings.Count]; for (int i = 0; i < _mappings.Count; i++) { serializers[i] = uniqueSerializers[uniqueIndexes[i]]; } return serializers; } [Fx.Tag.SecurityNote(Critical = "XmlSerializer.FromMappings has a LinkDemand.", Safe = "LinkDemand is spurious, not protecting anything in particular.")] [SecuritySafeCritical] private XmlSerializer[] CreateSerializersFromMappings(XmlMapping[] mappings, Type type) { return XmlSerializerHelper.FromMappings(mappings, type); } } internal struct SerializerStub { private readonly SerializerGenerationContext _context; internal readonly XmlMembersMapping Mapping; internal readonly int Handle; internal SerializerStub(SerializerGenerationContext context, XmlMembersMapping mapping, int handle) { _context = context; this.Mapping = mapping; this.Handle = handle; } internal XmlSerializer GetSerializer() { return _context.GetSerializer(Handle); } } internal class XmlSerializerFaultContractInfo { private FaultContractInfo _faultContractInfo; private SerializerStub _serializerStub; private XmlQualifiedName _faultContractElementName; private XmlSerializerObjectSerializer _serializer; internal XmlSerializerFaultContractInfo(FaultContractInfo faultContractInfo, SerializerStub serializerStub, XmlQualifiedName faultContractElementName) { if (faultContractInfo == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("faultContractInfo"); } if (faultContractElementName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("faultContractElementName"); } _faultContractInfo = faultContractInfo; _serializerStub = serializerStub; _faultContractElementName = faultContractElementName; } internal FaultContractInfo FaultContractInfo { get { return _faultContractInfo; } } internal XmlQualifiedName FaultContractElementName { get { return _faultContractElementName; } } internal XmlSerializerObjectSerializer Serializer { get { if (_serializer == null) _serializer = new XmlSerializerObjectSerializer(_faultContractInfo.Detail, _faultContractElementName, _serializerStub.GetSerializer()); return _serializer; } } } internal class MessageInfo : XmlSerializerOperationFormatter.MessageInfo { private SerializerStub _headers; private SerializerStub _body; private OperationFormatter.MessageHeaderDescriptionTable _headerDescriptionTable; private MessageHeaderDescription _unknownHeaderDescription; private MessagePartDescriptionCollection _rpcEncodedTypedMessageBodyParts; internal XmlMembersMapping BodyMapping { get { return _body.Mapping; } } internal override XmlSerializer BodySerializer { get { return _body.GetSerializer(); } } internal XmlMembersMapping HeadersMapping { get { return _headers.Mapping; } } internal override XmlSerializer HeaderSerializer { get { return _headers.GetSerializer(); } } internal override OperationFormatter.MessageHeaderDescriptionTable HeaderDescriptionTable { get { return _headerDescriptionTable; } } internal override MessageHeaderDescription UnknownHeaderDescription { get { return _unknownHeaderDescription; } } internal override MessagePartDescriptionCollection RpcEncodedTypedMessageBodyParts { get { return _rpcEncodedTypedMessageBodyParts; } } internal void SetBody(SerializerStub body, MessagePartDescriptionCollection rpcEncodedTypedMessageBodyParts) { _body = body; _rpcEncodedTypedMessageBodyParts = rpcEncodedTypedMessageBodyParts; } internal void SetHeaders(SerializerStub headers) { _headers = headers; } internal void SetHeaderDescriptionTable(OperationFormatter.MessageHeaderDescriptionTable headerDescriptionTable) { _headerDescriptionTable = headerDescriptionTable; } internal void SetUnknownHeaderDescription(MessageHeaderDescription unknownHeaderDescription) { _unknownHeaderDescription = unknownHeaderDescription; } } } } internal static class XmlSerializerHelper { static internal XmlReflectionMember GetXmlReflectionMember(MessagePartDescription part, bool isRpc, bool isEncoded, bool isWrapped) { string ns = isRpc ? null : part.Namespace; ICustomAttributeProvider additionalAttributesProvider = null; if (isEncoded || part.AdditionalAttributesProvider is MemberInfo) additionalAttributesProvider = part.AdditionalAttributesProvider; XmlName memberName = string.IsNullOrEmpty(part.UniquePartName) ? null : new XmlName(part.UniquePartName, true /*isEncoded*/); XmlName elementName = part.XmlName; return GetXmlReflectionMember(memberName, elementName, ns, part.Type, additionalAttributesProvider, part.Multiple, isEncoded, isWrapped); } static internal XmlReflectionMember GetXmlReflectionMember(XmlName memberName, XmlName elementName, string ns, Type type, ICustomAttributeProvider additionalAttributesProvider, bool isMultiple, bool isEncoded, bool isWrapped) { if (isEncoded && isMultiple) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxMultiplePartsNotAllowedInEncoded, elementName.DecodedName, ns))); XmlReflectionMember member = new XmlReflectionMember(); member.MemberName = (memberName ?? elementName).DecodedName; member.MemberType = type; if (member.MemberType.IsByRef) member.MemberType = member.MemberType.GetElementType(); if (isMultiple) member.MemberType = member.MemberType.MakeArrayType(); if (additionalAttributesProvider != null) { if (isEncoded) member.SoapAttributes = new SoapAttributes(additionalAttributesProvider); else member.XmlAttributes = new XmlAttributes(additionalAttributesProvider); } if (isEncoded) { if (member.SoapAttributes == null) member.SoapAttributes = new SoapAttributes(); else { Type invalidAttributeType = null; if (member.SoapAttributes.SoapAttribute != null) invalidAttributeType = typeof(SoapAttributeAttribute); else if (member.SoapAttributes.SoapIgnore) invalidAttributeType = typeof(SoapIgnoreAttribute); else if (member.SoapAttributes.SoapType != null) invalidAttributeType = typeof(SoapTypeAttribute); if (invalidAttributeType != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidSoapAttribute, invalidAttributeType, elementName.DecodedName))); } if (member.SoapAttributes.SoapElement == null) member.SoapAttributes.SoapElement = new SoapElementAttribute(elementName.DecodedName); } else { if (member.XmlAttributes == null) member.XmlAttributes = new XmlAttributes(); else { Type invalidAttributeType = null; if (member.XmlAttributes.XmlAttribute != null) invalidAttributeType = typeof(XmlAttributeAttribute); else if (member.XmlAttributes.XmlAnyAttribute != null && !isWrapped) invalidAttributeType = typeof(XmlAnyAttributeAttribute); else if (member.XmlAttributes.XmlChoiceIdentifier != null) invalidAttributeType = typeof(XmlChoiceIdentifierAttribute); else if (member.XmlAttributes.XmlIgnore) invalidAttributeType = typeof(XmlIgnoreAttribute); else if (member.XmlAttributes.Xmlns) invalidAttributeType = typeof(XmlNamespaceDeclarationsAttribute); else if (member.XmlAttributes.XmlText != null) invalidAttributeType = typeof(XmlTextAttribute); else if (member.XmlAttributes.XmlEnum != null) invalidAttributeType = typeof(XmlEnumAttribute); if (invalidAttributeType != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(isWrapped ? SR.SFxInvalidXmlAttributeInWrapped : SR.SFxInvalidXmlAttributeInBare, invalidAttributeType, elementName.DecodedName))); if (member.XmlAttributes.XmlArray != null && isMultiple) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxXmlArrayNotAllowedForMultiple, elementName.DecodedName, ns))); } bool isArray = member.MemberType.IsArray; if ((isArray && !isMultiple && member.MemberType != typeof(byte[])) || (!isArray && typeof(IEnumerable).IsAssignableFrom(member.MemberType) && member.MemberType != typeof(string) && !typeof(XmlNode).IsAssignableFrom(member.MemberType) && !typeof(IXmlSerializable).IsAssignableFrom(member.MemberType))) { if (member.XmlAttributes.XmlArray != null) { if (member.XmlAttributes.XmlArray.ElementName == String.Empty) member.XmlAttributes.XmlArray.ElementName = elementName.DecodedName; if (member.XmlAttributes.XmlArray.Namespace == null) member.XmlAttributes.XmlArray.Namespace = ns; } else if (HasNoXmlParameterAttributes(member.XmlAttributes)) { member.XmlAttributes.XmlArray = new XmlArrayAttribute(); member.XmlAttributes.XmlArray.ElementName = elementName.DecodedName; member.XmlAttributes.XmlArray.Namespace = ns; } } else { if (member.XmlAttributes.XmlElements == null || member.XmlAttributes.XmlElements.Count == 0) { if (HasNoXmlParameterAttributes(member.XmlAttributes)) { XmlElementAttribute elementAttribute = new XmlElementAttribute(); elementAttribute.ElementName = elementName.DecodedName; elementAttribute.Namespace = ns; member.XmlAttributes.XmlElements.Add(elementAttribute); } } else { foreach (XmlElementAttribute elementAttribute in member.XmlAttributes.XmlElements) { if (elementAttribute.ElementName == String.Empty) elementAttribute.ElementName = elementName.DecodedName; if (elementAttribute.Namespace == null) elementAttribute.Namespace = ns; } } } } return member; } private static bool HasNoXmlParameterAttributes(XmlAttributes xmlAttributes) { return xmlAttributes.XmlAnyAttribute == null && (xmlAttributes.XmlAnyElements == null || xmlAttributes.XmlAnyElements.Count == 0) && xmlAttributes.XmlArray == null && xmlAttributes.XmlAttribute == null && !xmlAttributes.XmlIgnore && xmlAttributes.XmlText == null && xmlAttributes.XmlChoiceIdentifier == null && (xmlAttributes.XmlElements == null || xmlAttributes.XmlElements.Count == 0) && !xmlAttributes.Xmlns; } public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { #if FEATURE_NETNATIVE if (GeneratedXmlSerializers.IsInitialized) { return FromMappingsViaInjection(mappings, type); } #endif return FromMappingsViaReflection(mappings, type); } private static XmlSerializer[] FromMappingsViaReflection(XmlMapping[] mappings, Type type) { if (mappings == null || mappings.Length == 0) { return new XmlSerializer[0]; } return XmlSerializer.FromMappings(mappings, type); } #if FEATURE_NETNATIVE private static XmlSerializer[] FromMappingsViaInjection(XmlMapping[] mappings, Type type) { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; bool generatedSerializerNotFound = false; for (int i = 0; i < serializers.Length; i++) { Type t; GeneratedXmlSerializers.GetGeneratedSerializers().TryGetValue(mappings[i].GetKey(), out t); if (t == null) { generatedSerializerNotFound = true; break; } serializers[i] = new XmlSerializer(t); } if (generatedSerializerNotFound) { return XmlSerializer.FromMappings(mappings, type); } return serializers; } #endif } #if FEATURE_NETNATIVE internal static class XmlMappingExtension { private static ConcurrentDictionary<XmlMapping, string> s_dictionary = new ConcurrentDictionary<XmlMapping, string>(); public static string GetKey(this XmlMapping mapping) { s_dictionary.TryGetValue(mapping, out string key); return key; } public static void SetKeyInternal(this XmlMapping mapping, string key) { mapping.SetKey(key); s_dictionary.TryAdd(mapping, key); } } #endif }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Interfaces; using System.Runtime.InteropServices; using System.Drawing.Imaging; namespace OpenSim.Region.CoreModules.World.WorldMap { public enum DrawRoutine { Rectangle, Polygon, Ellipse } public struct face { public Point[] pts; } public struct DrawStruct { public SolidBrush brush; public face[] trns; } public struct DrawStruct2 { public float sort_order; public SolidBrush brush; public Point[] vertices; } /// <summary> /// A very fast, but special purpose, tool for doing lots of drawing operations. /// </summary> public class DirectBitmap : IDisposable { public Bitmap Bitmap { get; private set; } public Int32[] Bits { get; private set; } public bool Disposed { get; private set; } public int Height { get; private set; } public int Width { get; private set; } protected GCHandle BitsHandle { get; private set; } public DirectBitmap(int width, int height) { Width = width; Height = height; Bits = new Int32[width * height]; BitsHandle = GCHandle.Alloc(Bits, GCHandleType.Pinned); Bitmap = new Bitmap(width, height, width * 4, PixelFormat.Format32bppPArgb, BitsHandle.AddrOfPinnedObject()); } public void Dispose() { if (Disposed) return; Disposed = true; Bitmap.Dispose(); BitsHandle.Free(); } } public class MapImageModule : IMapImageGenerator, IRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; private IConfigSource m_config; private IMapTileTerrainRenderer terrainRenderer; private bool drawPrimVolume = true; private bool textureTerrain = false; private byte[] imageData = null; private DirectBitmap mapbmp = new DirectBitmap(256, 256); #region IMapImageGenerator Members public byte[] WriteJpeg2000Image() { if (terrainRenderer != null) { terrainRenderer.TerrainToBitmap(mapbmp); } if (drawPrimVolume) { DrawObjectVolume(m_scene, mapbmp); } int t = Environment.TickCount; try { imageData = OpenJPEG.EncodeFromImage(mapbmp.Bitmap, true); } catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke { m_log.Error("Failed generating terrain map: " + e); } t = Environment.TickCount - t; m_log.InfoFormat("[MAPTILE] encoding of image needed {0}ms", t); return imageData; } #endregion #region IRegionModule Members public void Initialize(Scene scene, IConfigSource source) { m_scene = scene; m_config = source; try { IConfig startupConfig = m_config.Configs["Startup"]; // Location supported for legacy INI files. IConfig worldmapConfig = m_config.Configs["WorldMap"]; if (startupConfig.GetString("MapImageModule", "MapImageModule") != "MapImageModule") return; // Go find the parameters in the new location and if not found go looking in the old. drawPrimVolume = (worldmapConfig != null && worldmapConfig.Contains("DrawPrimOnMapTile")) ? worldmapConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume) : startupConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume); textureTerrain = (worldmapConfig != null && worldmapConfig.Contains("TextureOnMapTile")) ? worldmapConfig.GetBoolean("TextureOnMapTile", textureTerrain) : startupConfig.GetBoolean("TextureOnMapTile", textureTerrain); } catch { m_log.Warn("[MAPTILE]: Failed to load StartupConfig"); } if (textureTerrain) { terrainRenderer = new TexturedMapTileRenderer(); } else { terrainRenderer = new ShadedMapTileRenderer(); } terrainRenderer.Initialize(m_scene, m_config); m_scene.RegisterModuleInterface<IMapImageGenerator>(this); } public void PostInitialize() { } public void Close() { } public string Name { get { return "MapImageModule"; } } public bool IsSharedModule { get { return false; } } #endregion private static readonly SolidBrush DefaultBrush = new SolidBrush(Color.Black); private static SolidBrush GetFaceBrush(SceneObjectPart part, uint face) { // Block sillyness that would cause an exception. if (face >= OpenMetaverse.Primitive.TextureEntry.MAX_FACES) return DefaultBrush; var facetexture = part.Shape.Textures.GetFace(face); // GetFace throws a generic exception if the parameter is greater than MAX_FACES. // TODO: compute a better color from the texture data AND the color applied. return new SolidBrush(Color.FromArgb( Math.Max(0, Math.Min(255, (int)(facetexture.RGBA.R * 255f))), Math.Max(0, Math.Min(255, (int)(facetexture.RGBA.G * 255f))), Math.Max(0, Math.Min(255, (int)(facetexture.RGBA.B * 255f))) )); // FromARGB can throw an exception if a parameter is outside 0-255, but that is prevented. } private static float ZOfCrossDiff(ref Vector3 P, ref Vector3 Q, ref Vector3 R) { // let A = Q - P // let B = R - P // Vz = AxBy - AyBx // = (Qx - Px)(Ry - Py) - (Qy - Py)(Rx - Px) return (Q.X - P.X)* (R.Y - P.Y) - (Q.Y - P.Y) * (R.X - P.X); } private static DirectBitmap DrawObjectVolume(Scene whichScene, DirectBitmap mapbmp) { int time_start = Environment.TickCount;//, time_start_temp = time_start; //int time_prep = 0, time_filtering = 0, time_vertex_calcs = 0, time_sort_height_calc = 0; //int time_obb_norm = 0, time_obb_calc = 0, time_obb_brush = 0, time_obb_addtolist = 0; //int time_sorting = 0, time_drawing = 0; //int sop_count = 0, sop_count_filtered = 0; m_log.Info("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile"); float scale_factor = (float)mapbmp.Height / OpenSim.Framework.Constants.RegionSize; SceneObjectGroup sog; Vector3 pos; Quaternion rot; Vector3 rotated_radial_scale; Vector3 radial_scale; DrawStruct2 drawdata; var drawdata_for_sorting = new List<DrawStruct2>(); var vertices = new Vector3[8]; // Get all the faces for valid prims and prep them for drawing. var entities = whichScene.GetEntities(); // GetEntities returns a new list of entities, so no threading issues. //time_prep += Environment.TickCount - time_start_temp; foreach (EntityBase obj in entities) { // Only SOGs till have the needed parts. sog = obj as SceneObjectGroup; if (sog == null) continue; foreach (var part in sog.GetParts()) { //++sop_count; /* * * * * * * * * * * * * * * * * * */ // FILTERING PASS /* * * * * * * * * * * * * * * * * * */ //time_start_temp = Environment.TickCount; if ( // get the null checks out of the way part == null || part.Shape == null || part.Shape.Textures == null || part.Shape.Textures.DefaultTexture == null || // Make sure the object isn't temp or phys (part.Flags & (PrimFlags.Physics | PrimFlags.Temporary | PrimFlags.TemporaryOnRez)) != 0 || // Draw only if the object is at least 1 meter wide in all directions part.Scale.X <= 1f || part.Scale.Y <= 1f || part.Scale.Z <= 1f || // Eliminate trees from this since we don't really have a good tree representation part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree || part.Shape.PCode == (byte)PCode.Grass ) continue; pos = part.GetWorldPosition(); if ( // skip prim in non-finite position Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) || Single.IsInfinity(pos.X) || Single.IsInfinity(pos.Y) || // skip prim outside of region (REVISIT: prims can be outside of region and still overlap into the region.) pos.X < 0f || pos.X >= 256f || pos.Y < 0f || pos.Y >= 256f || // skip prim Z at or above 256m above the terrain at that position. pos.Z >= (whichScene.Heightmap.GetRawHeightAt((int)pos.X, (int)pos.Y) + 256f) ) continue; rot = part.GetWorldRotation(); radial_scale.X = part.Shape.Scale.X * 0.5f; radial_scale.Y = part.Shape.Scale.Y * 0.5f; radial_scale.Z = part.Shape.Scale.Z * 0.5f; //time_filtering += Environment.TickCount - time_start_temp; //++sop_count_filtered; /* * * * * * * * * * * * * * * * * * */ // OBB VERTEX COMPUTATION /* * * * * * * * * * * * * * * * * * */ //time_start_temp = Environment.TickCount; /* Vertex pattern: # XYZ 0 --+ 1 +-+ 2 +++ 3 -++ 4 --- 5 +-- 6 ++- 7 -+- */ rotated_radial_scale.X = -radial_scale.X; rotated_radial_scale.Y = -radial_scale.Y; rotated_radial_scale.Z = radial_scale.Z; rotated_radial_scale *= rot; vertices[0].X = pos.X + rotated_radial_scale.X; vertices[0].Y = pos.Y + rotated_radial_scale.Y; vertices[0].Z = pos.Z + rotated_radial_scale.Z; rotated_radial_scale.X = radial_scale.X; rotated_radial_scale.Y = -radial_scale.Y; rotated_radial_scale.Z = radial_scale.Z; rotated_radial_scale *= rot; vertices[1].X = pos.X + rotated_radial_scale.X; vertices[1].Y = pos.Y + rotated_radial_scale.Y; vertices[1].Z = pos.Z + rotated_radial_scale.Z; rotated_radial_scale.X = radial_scale.X; rotated_radial_scale.Y = radial_scale.Y; rotated_radial_scale.Z = radial_scale.Z; rotated_radial_scale *= rot; vertices[2].X = pos.X + rotated_radial_scale.X; vertices[2].Y = pos.Y + rotated_radial_scale.Y; vertices[2].Z = pos.Z + rotated_radial_scale.Z; rotated_radial_scale.X = -radial_scale.X; rotated_radial_scale.Y = radial_scale.Y; rotated_radial_scale.Z = radial_scale.Z; rotated_radial_scale *= rot; vertices[3].X = pos.X + rotated_radial_scale.X; vertices[3].Y = pos.Y + rotated_radial_scale.Y; vertices[3].Z = pos.Z + rotated_radial_scale.Z; rotated_radial_scale.X = -radial_scale.X; rotated_radial_scale.Y = -radial_scale.Y; rotated_radial_scale.Z = -radial_scale.Z; rotated_radial_scale *= rot; vertices[4].X = pos.X + rotated_radial_scale.X; vertices[4].Y = pos.Y + rotated_radial_scale.Y; vertices[4].Z = pos.Z + rotated_radial_scale.Z; rotated_radial_scale.X = radial_scale.X; rotated_radial_scale.Y = -radial_scale.Y; rotated_radial_scale.Z = -radial_scale.Z; rotated_radial_scale *= rot; vertices[5].X = pos.X + rotated_radial_scale.X; vertices[5].Y = pos.Y + rotated_radial_scale.Y; vertices[5].Z = pos.Z + rotated_radial_scale.Z; rotated_radial_scale.X = radial_scale.X; rotated_radial_scale.Y = radial_scale.Y; rotated_radial_scale.Z = -radial_scale.Z; rotated_radial_scale *= rot; vertices[6].X = pos.X + rotated_radial_scale.X; vertices[6].Y = pos.Y + rotated_radial_scale.Y; vertices[6].Z = pos.Z + rotated_radial_scale.Z; rotated_radial_scale.X = -radial_scale.X; rotated_radial_scale.Y = radial_scale.Y; rotated_radial_scale.Z = -radial_scale.Z; rotated_radial_scale *= rot; vertices[7].X = pos.X + rotated_radial_scale.X; vertices[7].Y = pos.Y + rotated_radial_scale.Y; vertices[7].Z = pos.Z + rotated_radial_scale.Z; //time_vertex_calcs += Environment.TickCount - time_start_temp; /* * * * * * * * * * * * * * * * * * */ // SORT HEIGHT CALC /* * * * * * * * * * * * * * * * * * */ //time_start_temp = Environment.TickCount; // Sort faces by AABB top height, which by nature will always be the maximum Z value of all upwards facing face vertices, but is also simply the highest vertex. drawdata.sort_order = Math.Max(vertices[0].Z, Math.Max(vertices[1].Z, Math.Max(vertices[2].Z, Math.Max(vertices[3].Z, Math.Max(vertices[4].Z, Math.Max(vertices[5].Z, Math.Max(vertices[6].Z, vertices[7].Z ) ) ) ) ) ) ) ; //time_sort_height_calc += Environment.TickCount - time_start_temp; /* * * * * * * * * * * * * * * * * * */ // OBB DRAWING PREPARATION PASS /* * * * * * * * * * * * * * * * * * */ // Compute face 0 of OBB and add if facing up. //time_start_temp = Environment.TickCount; //if (Vector3.Cross(Vector3.Subtract(vertices[1], vertices[0]), Vector3.Subtract(vertices[3], vertices[0])).Z > 0) if (ZOfCrossDiff(ref vertices[0], ref vertices[1], ref vertices[3]) > 0) { //time_obb_norm += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata.brush = GetFaceBrush(part, 0); //time_obb_brush += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata.vertices = new Point[4]; drawdata.vertices[0].X = (int)(vertices[0].X * scale_factor); drawdata.vertices[0].Y = mapbmp.Height - (int)(vertices[0].Y * scale_factor); drawdata.vertices[1].X = (int)(vertices[1].X * scale_factor); drawdata.vertices[1].Y = mapbmp.Height - (int)(vertices[1].Y * scale_factor); drawdata.vertices[2].X = (int)(vertices[2].X * scale_factor); drawdata.vertices[2].Y = mapbmp.Height - (int)(vertices[2].Y * scale_factor); drawdata.vertices[3].X = (int)(vertices[3].X * scale_factor); drawdata.vertices[3].Y = mapbmp.Height - (int)(vertices[3].Y * scale_factor); //time_obb_calc += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata_for_sorting.Add(drawdata); //time_obb_addtolist += Environment.TickCount - time_start_temp; } else { //time_obb_norm += Environment.TickCount - time_start_temp; } // Compute face 1 of OBB and add if facing up. //time_start_temp = Environment.TickCount; //if (Vector3.Cross(Vector3.Subtract(vertices[5], vertices[4]), Vector3.Subtract(vertices[0], vertices[4])).Z > 0) if (ZOfCrossDiff(ref vertices[4], ref vertices[5], ref vertices[0]) > 0) { //time_obb_norm += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata.brush = GetFaceBrush(part, 1); //time_obb_brush += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata.vertices = new Point[4]; drawdata.vertices[0].X = (int)(vertices[4].X * scale_factor); drawdata.vertices[0].Y = mapbmp.Height - (int)(vertices[4].Y * scale_factor); drawdata.vertices[1].X = (int)(vertices[5].X * scale_factor); drawdata.vertices[1].Y = mapbmp.Height - (int)(vertices[5].Y * scale_factor); drawdata.vertices[2].X = (int)(vertices[1].X * scale_factor); drawdata.vertices[2].Y = mapbmp.Height - (int)(vertices[1].Y * scale_factor); drawdata.vertices[3].X = (int)(vertices[0].X * scale_factor); drawdata.vertices[3].Y = mapbmp.Height - (int)(vertices[0].Y * scale_factor); //time_obb_calc += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata_for_sorting.Add(drawdata); //time_obb_addtolist += Environment.TickCount - time_start_temp; } else { //time_obb_norm += Environment.TickCount - time_start_temp; } // Compute face 2 of OBB and add if facing up. //time_start_temp = Environment.TickCount; //if (Vector3.Cross(Vector3.Subtract(vertices[6], vertices[5]), Vector3.Subtract(vertices[1], vertices[5])).Z > 0) if (ZOfCrossDiff(ref vertices[5], ref vertices[6], ref vertices[1]) > 0) { //time_obb_norm += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata.brush = GetFaceBrush(part, 2); //time_obb_brush += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata.vertices = new Point[4]; drawdata.vertices[0].X = (int)(vertices[5].X * scale_factor); drawdata.vertices[0].Y = mapbmp.Height - (int)(vertices[5].Y * scale_factor); drawdata.vertices[1].X = (int)(vertices[6].X * scale_factor); drawdata.vertices[1].Y = mapbmp.Height - (int)(vertices[6].Y * scale_factor); drawdata.vertices[2].X = (int)(vertices[2].X * scale_factor); drawdata.vertices[2].Y = mapbmp.Height - (int)(vertices[2].Y * scale_factor); drawdata.vertices[3].X = (int)(vertices[1].X * scale_factor); drawdata.vertices[3].Y = mapbmp.Height - (int)(vertices[1].Y * scale_factor); //time_obb_calc += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata_for_sorting.Add(drawdata); //time_obb_addtolist += Environment.TickCount - time_start_temp; } else { //time_obb_norm += Environment.TickCount - time_start_temp; } // Compute face 3 of OBB and add if facing up. //time_start_temp = Environment.TickCount; //if (Vector3.Cross(Vector3.Subtract(vertices[7], vertices[6]), Vector3.Subtract(vertices[2], vertices[6])).Z > 0) if (ZOfCrossDiff(ref vertices[6], ref vertices[7], ref vertices[2]) > 0) { //time_obb_norm += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata.brush = GetFaceBrush(part, 3); //time_obb_brush += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata.vertices = new Point[4]; drawdata.vertices[0].X = (int)(vertices[6].X * scale_factor); drawdata.vertices[0].Y = mapbmp.Height - (int)(vertices[6].Y * scale_factor); drawdata.vertices[1].X = (int)(vertices[7].X * scale_factor); drawdata.vertices[1].Y = mapbmp.Height - (int)(vertices[7].Y * scale_factor); drawdata.vertices[2].X = (int)(vertices[3].X * scale_factor); drawdata.vertices[2].Y = mapbmp.Height - (int)(vertices[3].Y * scale_factor); drawdata.vertices[3].X = (int)(vertices[2].X * scale_factor); drawdata.vertices[3].Y = mapbmp.Height - (int)(vertices[2].Y * scale_factor); //time_obb_calc += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata_for_sorting.Add(drawdata); //time_obb_addtolist += Environment.TickCount - time_start_temp; } else { //time_obb_norm += Environment.TickCount - time_start_temp; } // Compute face 4 of OBB and add if facing up. //time_start_temp = Environment.TickCount; //if (Vector3.Cross(Vector3.Subtract(vertices[4], vertices[7]), Vector3.Subtract(vertices[3], vertices[7])).Z > 0) if (ZOfCrossDiff(ref vertices[7], ref vertices[4], ref vertices[3]) > 0) { //time_obb_norm += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata.brush = GetFaceBrush(part, 4); //time_obb_brush += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata.vertices = new Point[4]; drawdata.vertices[0].X = (int)(vertices[7].X * scale_factor); drawdata.vertices[0].Y = mapbmp.Height - (int)(vertices[7].Y * scale_factor); drawdata.vertices[1].X = (int)(vertices[4].X * scale_factor); drawdata.vertices[1].Y = mapbmp.Height - (int)(vertices[4].Y * scale_factor); drawdata.vertices[2].X = (int)(vertices[0].X * scale_factor); drawdata.vertices[2].Y = mapbmp.Height - (int)(vertices[0].Y * scale_factor); drawdata.vertices[3].X = (int)(vertices[3].X * scale_factor); drawdata.vertices[3].Y = mapbmp.Height - (int)(vertices[3].Y * scale_factor); //time_obb_calc += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata_for_sorting.Add(drawdata); //time_obb_addtolist += Environment.TickCount - time_start_temp; } else { //time_obb_norm += Environment.TickCount - time_start_temp; } // Compute face 5 of OBB and add if facing up. //time_start_temp = Environment.TickCount; //if (Vector3.Cross(Vector3.Subtract(vertices[6], vertices[7]), Vector3.Subtract(vertices[4], vertices[7])).Z > 0) if (ZOfCrossDiff(ref vertices[7], ref vertices[6], ref vertices[4]) > 0) { //time_obb_norm += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata.brush = GetFaceBrush(part, 5); //time_obb_brush += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata.vertices = new Point[4]; drawdata.vertices[0].X = (int)(vertices[7].X * scale_factor); drawdata.vertices[0].Y = mapbmp.Height - (int)(vertices[7].Y * scale_factor); drawdata.vertices[1].X = (int)(vertices[6].X * scale_factor); drawdata.vertices[1].Y = mapbmp.Height - (int)(vertices[6].Y * scale_factor); drawdata.vertices[2].X = (int)(vertices[5].X * scale_factor); drawdata.vertices[2].Y = mapbmp.Height - (int)(vertices[5].Y * scale_factor); drawdata.vertices[3].X = (int)(vertices[4].X * scale_factor); drawdata.vertices[3].Y = mapbmp.Height - (int)(vertices[4].Y * scale_factor); //time_obb_calc += Environment.TickCount - time_start_temp; //time_start_temp = Environment.TickCount; drawdata_for_sorting.Add(drawdata); //time_obb_addtolist += Environment.TickCount - time_start_temp; } else { //time_obb_norm += Environment.TickCount - time_start_temp; } } } // Sort faces by Z position //time_start_temp = Environment.TickCount; drawdata_for_sorting.Sort((h1, h2) => h1.sort_order.CompareTo(h2.sort_order));; //time_sorting = Environment.TickCount - time_start_temp; // Draw the faces //time_start_temp = Environment.TickCount; using (Graphics g = Graphics.FromImage(mapbmp.Bitmap)) { g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; for (int s = 0; s < drawdata_for_sorting.Count; s++) { g.FillPolygon(drawdata_for_sorting[s].brush, drawdata_for_sorting[s].vertices); } } //time_drawing = Environment.TickCount - time_start_temp; //m_log.InfoFormat("[MAPTILE]: Generating Maptile Step 2 (Objects): Processed {0} entities, {1} prims, {2} used for map drawing, resulting in {3} faces to draw.", // entities.Count, sop_count, sop_count_filtered, drawdata_for_sorting.Count //); m_log.InfoFormat("[MAPTILE]: Generating Maptile Step 2 (Objects): Timing: " + "total time: {0}ms",// + //"prepping took {1}ms, " + //"filtering prims took {2}ms, " + //"calculating vertices took {3}ms, " + //"computing sorting height took {4}ms, " + //"calculating OBB normal took {5}ms, " + //"getting OBB face colors took {6}ms, " + //"calculating OBBs took {7}ms, " + //"adding OBBs to list took {8}ms, " + //"sorting took {9}ms, " + //"drawing took {10}ms, " + Environment.TickCount - time_start//, //time_prep, time_filtering, time_vertex_calcs, time_sort_height_calc, //time_obb_norm, time_obb_brush, time_obb_calc, time_obb_addtolist, //time_sorting, time_drawing ); return mapbmp; } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Text; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit; using System.Windows.Forms; using System.Collections; namespace Revit.SDK.Samples.NewHostedSweep.CS { /// <summary> /// Provides functions to create hosted sweep and preserves available edges and type. /// It is the base class of FasciaCreator, GutterCreator, and SlabEdgeCreator. /// </summary> public abstract class HostedSweepCreator { #region Public Interfaces /// <summary> /// A string indicates which type this creator can create. /// </summary> virtual public String Name { get { return "Hosted Sweep"; } } /// <summary> /// A dictionary stores all the element=>edges which hosted-sweep can be created on. /// </summary> public abstract Dictionary<Autodesk.Revit.DB.Element, List<Edge>> SupportEdges { get; } /// <summary> /// All type of hosted-sweep. /// </summary> public abstract IEnumerable AllTypes { get; } /// <summary> /// A dictionary stores all the element=>geometry which hosted-sweep can be created on. /// </summary> public Dictionary<Autodesk.Revit.DB.Element, ElementGeometry> ElemGeomDic { get { return m_elemGeom; } } /// <summary> /// Create a hosted-sweep according to the CreationData parameter. /// </summary> /// <param name="creationData">CreationData parameter</param> /// <returns>ModificationData which contains the created hosted-sweep</returns> public ModificationData Create(CreationData creationData) { ReferenceArray refArr = new ReferenceArray(); foreach (Edge edge in creationData.EdgesForHostedSweep) { refArr.Append(edge.Reference); } ModificationData modificationData = null; Transaction transaction = new Transaction(m_rvtDoc, "CreateHostedSweep"); try { transaction.Start(); HostedSweep createdHostedSweep = CreateHostedSweep(creationData.Symbol, refArr); if (transaction.Commit() == TransactionStatus.Committed) { m_rvtUIDoc.ShowElements(createdHostedSweep); // just only end transaction return true, we will create the hosted sweep. modificationData = new ModificationData(createdHostedSweep, creationData); m_createdHostedSweeps.Add(modificationData); } } catch { transaction.RollBack(); } return modificationData; } /// <summary> /// A list to store all the created hosted-sweep by this creator. /// </summary> public List<ModificationData> CreatedHostedSweeps { get { return m_createdHostedSweeps; } } /// <summary> /// Revit active document. /// </summary> public Document RvtDocument { get { return m_rvtDoc; } } /// <summary> /// Revit UI document. /// </summary> public UIDocument RvtUIDocument { get { return m_rvtUIDoc; } } #endregion #region Fields and Constructor /// <summary> /// List of Modification to store all the created hosted-sweep by this. /// </summary> private List<ModificationData> m_createdHostedSweeps; /// <summary> /// Revit active document. /// </summary> protected Document m_rvtDoc; /// <summary> /// Revit UI document. /// </summary> protected UIDocument m_rvtUIDoc; /// <summary> /// Dictionary to store element's geometry which this creator can be used. /// </summary> protected Dictionary<Autodesk.Revit.DB.Element, ElementGeometry> m_elemGeom; /// <summary> /// Constructor which takes a Revit.Document as parameter. /// </summary> /// <param name="rvtDoc">Revit.Document parameter</param> protected HostedSweepCreator(Autodesk.Revit.UI.UIDocument rvtDoc) { m_rvtUIDoc = rvtDoc; m_rvtDoc = rvtDoc.Document; m_elemGeom = new Dictionary<Autodesk.Revit.DB.Element, ElementGeometry>(); m_createdHostedSweeps = new List<ModificationData>(); } #endregion #region Protected Methods /// <summary> /// Create a hosted-sweep according to the given Symbol and ReferenceArray. /// </summary> /// <param name="symbol">Hosted-sweep Symbol</param> /// <param name="refArr">Hosted-sweep ReferenceArray</param> /// <returns>Created hosted-sweep</returns> protected abstract HostedSweep CreateHostedSweep(ElementType symbol, ReferenceArray refArr); /// <summary> /// Extract the geometry of the given Element. /// </summary> /// <param name="elem">Element parameter</param> /// <returns>Element's geometry</returns> protected ElementGeometry ExtractGeom(Autodesk.Revit.DB.Element elem) { Solid result = null; Options options = new Options(); options.ComputeReferences = true; Autodesk.Revit.DB.GeometryElement gElement = elem.get_Geometry(options); foreach (GeometryObject gObj in gElement.Objects) { result = gObj as Solid; if (result != null && result.Faces.Size > 0) break; } BoundingBoxXYZ box = elem.get_BoundingBox(null); return new ElementGeometry(result, box); } #endregion } }
/************************************************************************** * MIT License * * Copyright (C) 2014 Morten Kvistgaard <mk@pch-engineering.dk> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * *********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.IO.BACnet; using System.Globalization; using System.Windows.Forms.Design; using System.Windows.Forms; using System.Drawing.Design; namespace Utilities { /// <summary> /// Helper classses for dynamic property grid manipulations. /// Note: Following attribute can be helpful also: [System.ComponentModel.TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] /// </summary> class DynamicPropertyGridContainer: CollectionBase,ICustomTypeDescriptor { /// <summary> /// Add CustomProperty to Collectionbase List /// </summary> /// <param name="Value"></param> public void Add(CustomProperty Value) { base.List.Add(Value); } /// <summary> /// Remove item from List /// </summary> /// <param name="Name"></param> public void Remove(string Name) { foreach(CustomProperty prop in base.List) { if(prop.Name == Name) { base.List.Remove(prop); return; } } } /// <summary> /// Indexer /// </summary> public CustomProperty this[int index] { get { return (CustomProperty)base.List[index]; } set { base.List[index] = (CustomProperty)value; } } public CustomProperty this[string name] { get { foreach (CustomProperty p in this) { if (p.Name == name) return p; } return null; } } #region "TypeDescriptor Implementation" /// <summary> /// Get Class Name /// </summary> /// <returns>String</returns> public String GetClassName() { return TypeDescriptor.GetClassName(this,true); } /// <summary> /// GetAttributes /// </summary> /// <returns>AttributeCollection</returns> public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this,true); } /// <summary> /// GetComponentName /// </summary> /// <returns>String</returns> public String GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } /// <summary> /// GetConverter /// </summary> /// <returns>TypeConverter</returns> public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } /// <summary> /// GetDefaultEvent /// </summary> /// <returns>EventDescriptor</returns> public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } /// <summary> /// GetDefaultProperty /// </summary> /// <returns>PropertyDescriptor</returns> public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } /// <summary> /// GetEditor /// </summary> /// <param name="editorBaseType">editorBaseType</param> /// <returns>object</returns> public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } public EventDescriptorCollection GetEvents() { return TypeDescriptor.GetEvents(this, true); } public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { PropertyDescriptor[] newProps = new PropertyDescriptor[this.Count]; for (int i = 0; i < this.Count; i++) { CustomProperty prop = (CustomProperty) this[i]; newProps[i] = new CustomPropertyDescriptor(ref prop, attributes); } return new PropertyDescriptorCollection(newProps); } public PropertyDescriptorCollection GetProperties() { return TypeDescriptor.GetProperties(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) { return this; } #endregion public override string ToString() { return "Custom type"; } } /// <summary> /// Custom property class /// </summary> public class CustomProperty { private string m_name = string.Empty; private bool m_readonly = false; private object m_old_value = null; private object m_value = null; private Type m_type; private object m_tag; private DynamicEnum m_options; private string m_category; // Modif FC : change type private BacnetApplicationTags? m_description; // Modif FC : constructor public CustomProperty(string name, object value, Type type, bool read_only, string category = "", BacnetApplicationTags? description = null, DynamicEnum options = null, object tag = null) { this.m_name = name; this.m_old_value = value; this.m_value = value; this.m_type = type; this.m_readonly = read_only; this.m_tag = tag; this.m_options = options; this.m_category = "BacnetProperty"; this.m_description = description; } public DynamicEnum Options { get { return m_options; } } public Type Type { get { return m_type; } } public string Category { get { return m_category; } } // Modif FC public string Description { get { return m_description == null ? null : m_description.ToString(); } } // Modif FC : added public BacnetApplicationTags? bacnetApplicationTags { get { return m_description; } } public bool ReadOnly { get { return m_readonly; } } public string Name { get { return m_name; } } public bool Visible { get { return true; } } public object Value { get { return m_value; } set { m_value = value; } } public object Tag { get { return m_tag; } } public void Reset() { m_value = m_old_value; } } #region " DoubleConvert" /// <summary> /// A class to allow the conversion of doubles to string representations of /// their exact decimal values. The implementation aims for readability over /// efficiency. /// </summary> public class DoubleConverter { /// <summary> /// Converts the given double to a string representation of its /// exact decimal value. /// </summary> /// <param name="d">The double to convert.</param> /// <returns>A string representation of the double's exact decimal value.</return> public static string ToExactString(double d) { if (double.IsPositiveInfinity(d)) return System.Globalization.NumberFormatInfo.CurrentInfo.PositiveInfinitySymbol; if (double.IsNegativeInfinity(d)) return System.Globalization.NumberFormatInfo.CurrentInfo.NegativeInfinitySymbol; if (double.IsNaN(d)) return System.Globalization.NumberFormatInfo.CurrentInfo.NaNSymbol; // Translate the double into sign, exponent and mantissa. long bits = BitConverter.DoubleToInt64Bits(d); // Note that the shift is sign-extended, hence the test against -1 not 1 bool negative = (bits < 0); int exponent = (int)((bits >> 52) & 0x7ffL); long mantissa = bits & 0xfffffffffffffL; // Subnormal numbers; exponent is effectively one higher, // but there's no extra normalisation bit in the mantissa if (exponent == 0) { exponent++; } // Normal numbers; leave exponent as it is but add extra // bit to the front of the mantissa else { mantissa = mantissa | (1L << 52); } // Bias the exponent. It's actually biased by 1023, but we're // treating the mantissa as m.0 rather than 0.m, so we need // to subtract another 52 from it. exponent -= 1075; if (mantissa == 0) { return "0"; } /* Normalize */ while ((mantissa & 1) == 0) { /* i.e., Mantissa is even */ mantissa >>= 1; exponent++; } /// Construct a new decimal expansion with the mantissa ArbitraryDecimal ad = new ArbitraryDecimal(mantissa); // If the exponent is less than 0, we need to repeatedly // divide by 2 - which is the equivalent of multiplying // by 5 and dividing by 10. if (exponent < 0) { for (int i = 0; i < -exponent; i++) ad.MultiplyBy(5); ad.Shift(-exponent); } // Otherwise, we need to repeatedly multiply by 2 else { for (int i = 0; i < exponent; i++) ad.MultiplyBy(2); } // Finally, return the string with an appropriate sign if (negative) return "-" + ad.ToString(); else return ad.ToString(); } /// <summary>Private class used for manipulating class ArbitraryDecimal { /// <summary>Digits in the decimal expansion, one byte per digit byte[] digits; /// <summary> /// How many digits are *after* the decimal point /// </summary> int decimalPoint = 0; /// <summary> /// Constructs an arbitrary decimal expansion from the given long. /// The long must not be negative. /// </summary> internal ArbitraryDecimal(long x) { string tmp = x.ToString(System.Globalization.CultureInfo.InvariantCulture); digits = new byte[tmp.Length]; for (int i = 0; i < tmp.Length; i++) digits[i] = (byte)(tmp[i] - '0'); Normalize(); } /// <summary> /// Multiplies the current expansion by the given amount, which should /// only be 2 or 5. /// </summary> internal void MultiplyBy(int amount) { byte[] result = new byte[digits.Length + 1]; for (int i = digits.Length - 1; i >= 0; i--) { int resultDigit = digits[i] * amount + result[i + 1]; result[i] = (byte)(resultDigit / 10); result[i + 1] = (byte)(resultDigit % 10); } if (result[0] != 0) { digits = result; } else { Array.Copy(result, 1, digits, 0, digits.Length); } Normalize(); } /// <summary> /// Shifts the decimal point; a negative value makes /// the decimal expansion bigger (as fewer digits come after the /// decimal place) and a positive value makes the decimal /// expansion smaller. /// </summary> internal void Shift(int amount) { decimalPoint += amount; } /// <summary> /// Removes leading/trailing zeroes from the expansion. /// </summary> internal void Normalize() { int first; for (first = 0; first < digits.Length; first++) if (digits[first] != 0) break; int last; for (last = digits.Length - 1; last >= 0; last--) if (digits[last] != 0) break; if (first == 0 && last == digits.Length - 1) return; byte[] tmp = new byte[last - first + 1]; for (int i = 0; i < tmp.Length; i++) tmp[i] = digits[i + first]; decimalPoint -= digits.Length - (last + 1); digits = tmp; } /// <summary> /// Converts the value to a proper decimal string representation. /// </summary> public override String ToString() { char[] digitString = new char[digits.Length]; for (int i = 0; i < digits.Length; i++) digitString[i] = (char)(digits[i] + '0'); // Simplest case - nothing after the decimal point, // and last real digit is non-zero, eg value=35 if (decimalPoint == 0) { return new string(digitString); } // Fairly simple case - nothing after the decimal // point, but some 0s to add, eg value=350 if (decimalPoint < 0) { return new string(digitString) + new string('0', -decimalPoint); } // Nothing before the decimal point, eg 0.035 if (decimalPoint >= digitString.Length) { return "0" + System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + new string('0', (decimalPoint - digitString.Length)) + new string(digitString); } // Most complicated case - part of the string comes // before the decimal point, part comes after it, // eg 3.5 return new string(digitString, 0, digitString.Length - decimalPoint) + System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + new string(digitString, digitString.Length - decimalPoint, decimalPoint); } } } #endregion public class DynamicEnum : ICollection { private Dictionary<string, int> m_stringIndex = new Dictionary<string, int>(); private Dictionary<int, string> m_intIndex = new Dictionary<int, string>(); public bool IsFlag { get; set; } public int this[string name] { get { int value = 0; if (name.IndexOf(',') != -1) { int num = 0; foreach (string str2 in name.Split(new char[] { ',' })) { m_stringIndex.TryGetValue(str2.Trim(), out value); num |= value; } return num; } m_stringIndex.TryGetValue(name, out value); return value; } } public string this[int value] { get { if (IsFlag) { string str = ""; foreach (KeyValuePair<string, int> entry in m_stringIndex) { if ((value & entry.Value) > 0 || (entry.Value == 0 && value == 0)) str += ", " + entry.Key; } if (str != "") str = str.Substring(2); return str; } else { string name; m_intIndex.TryGetValue(value, out name); return name; } } } public void Add(string name, int value) { m_stringIndex.Add(name, value); m_intIndex.Add(value, name); } public bool Contains(string name) { return m_stringIndex.ContainsKey(name); } public bool Contains(int value) { return m_intIndex.ContainsKey(value); } public IEnumerator GetEnumerator() { return m_stringIndex.GetEnumerator(); } public int Count { get { return m_stringIndex.Count; } } public void CopyTo(Array array, int index) { int i = 0; foreach (KeyValuePair<string, int> entry in this) array.SetValue(entry, i++ + index); } public bool IsSynchronized { get { throw new NotImplementedException(); } } public object SyncRoot { get { throw new NotImplementedException(); } } } public class DynamicEnumConverter : TypeConverter { // Fields private DynamicEnum m_e; public DynamicEnumConverter(DynamicEnum e) { m_e = e; } private static bool is_number(string str) { if (string.IsNullOrWhiteSpace(str) || str.Length == 0) return false; for (int i = 0; i < str.Length; i++) if (!char.IsNumber(str, i)) return false; return true; } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is string && value != null) { string str = (string)value; str = str.Trim(); if (m_e.Contains(str)) return m_e[str]; else if (is_number(str)) { int int_val; if (str.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase)) int_val = int.Parse(str.Substring(2), System.Globalization.NumberStyles.HexNumber); else int_val = int.Parse(str); return int_val; } else { return m_e[str]; } } return base.ConvertFrom(context, culture, value); } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return true; } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return true; } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == null) throw new ArgumentNullException("destinationType"); if ((destinationType == typeof(string)) && (value != null)) { if (value is string) { return value; } else if (value is KeyValuePair<string, int>) return ((KeyValuePair<string, int>)value).Key; int val = (int)Convert.ChangeType(value, typeof(int)); return m_e[val]; } return base.ConvertTo(context, culture, value, destinationType); } public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new TypeConverter.StandardValuesCollection(m_e); } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return !m_e.IsFlag; } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool IsValid(ITypeDescriptorContext context, object value) { if (value is string) return m_e.Contains((string)value); int val = (int)Convert.ChangeType(value, typeof(int)); return m_e.Contains(val); } } public class CustomSingleConverter : SingleConverter { public static bool DontDisplayExactFloats { get; set; } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if ((destinationType == typeof(string)) && (value.GetType() == typeof(float)) && !DontDisplayExactFloats) { return DoubleConverter.ToExactString((double)(float)value); } return base.ConvertTo(context, culture, value, destinationType); } } public class BacnetObjectIdentifierConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(BacnetObjectId)) return true; return base.CanConvertTo(context, destinationType); } public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } // Call to change the display public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { if (destinationType == typeof(System.String) && value is BacnetObjectId) { BacnetObjectId objId = (BacnetObjectId)value; return objId.type + ":" + objId.instance; } return base.ConvertTo(context, culture, value, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { try { string[] s = (value as String).Split(':'); return new BacnetObjectId((BacnetObjectTypes)Enum.Parse(typeof(BacnetObjectTypes), s[0]), Convert.ToUInt16(s[1])); } catch { return null; } } return base.ConvertFrom(context, culture, value); } } public class BacnetDeviceObjectPropertyReferenceConverter: ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(BacnetDeviceObjectPropertyReference)) return true; return base.CanConvertTo(context, destinationType); } public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { if (destinationType == typeof(System.String) && value is BacnetDeviceObjectPropertyReference) { BacnetDeviceObjectPropertyReference pr = (BacnetDeviceObjectPropertyReference)value; return "Reference to " +pr.objectIdentifier.ToString(); } else return base.ConvertTo(context, culture, value, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { try { // A realy hidden service !!! // and remember that PRESENT_VALUE = 85 // entry like OBJECT_ANALOG_INPUT:0:85 // string[] s = (value as String).Split(':'); return new BacnetDeviceObjectPropertyReference( new BacnetObjectId((BacnetObjectTypes)Enum.Parse(typeof(BacnetObjectTypes), s[0]), Convert.ToUInt16(s[1])), (BacnetPropertyIds)Convert.ToUInt16(s[2]) ); } catch { return null; } } return base.ConvertFrom(context, culture, value); } } public class BacnetBitStringConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { try { return BacnetBitString.Parse(value as String); } catch { return null; } } return base.ConvertFrom(context, culture, value); } } // used for BacnetTime (without Date, but stored in a DateTime struct) public class BacnetTimeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { try { return DateTime.Parse("1/1/1 "+(string)value,System.Threading.Thread.CurrentThread.CurrentCulture); } catch { return null; } } return base.ConvertFrom(context, culture, value); } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(DateTime)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { if (destinationType == typeof(System.String) && value is DateTime) { DateTime dt = (DateTime)value; return dt.ToLongTimeString(); } else return base.ConvertTo(context, culture, value, destinationType); } } // http://www.acodemics.co.uk/2014/03/20/c-datetimepicker-in-propertygrid/ // used for BacnetTime Edition public class BacnetTimePickerEditor : UITypeEditor { IWindowsFormsEditorService editorService; DateTimePicker picker = new DateTimePicker(); public BacnetTimePickerEditor() { picker.Format = DateTimePickerFormat.Time; picker.ShowUpDown = true; } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if (provider != null) { this.editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; } if (this.editorService != null) { DateTime dt= (DateTime)value; // this value is 1/1/1 for the date, DatetimePicket don't accept it picker.Value = new DateTime(2000, 1, 1, dt.Hour, dt.Minute, dt.Second); // only HH:MM:SS is important this.editorService.DropDownControl(picker); value = picker.Value; } return value; } } // In order to give a readable list instead of a bitstring public class BacnetBitStringToEnumListDisplay : UITypeEditor { IWindowsFormsEditorService editorService; ListBox ObjetList; bool LinearEnum; Enum currentPropertyEnum; // the corresponding Enum is given in parameters // and also how the value is fixed 0,1,2... or 1,2,4,8... in the enumeration public BacnetBitStringToEnumListDisplay(Enum e, bool LinearEnum, bool DisplayAll=false) { currentPropertyEnum = e; this.LinearEnum = LinearEnum; if (DisplayAll == true) ObjetList = new CheckedListBox(); else ObjetList = new ListBox(); } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } private static string GetNiceName(String name) { if (name.StartsWith("OBJECT_")) name = name.Substring(7); if (name.StartsWith("SERVICE_SUPPORTED_")) name = name.Substring(18); if (name.StartsWith("STATUS_FLAG_")) name = name.Substring(12); if (name.StartsWith("EVENT_ENABLE_")) name = name.Substring(13); if (name.StartsWith("EVENT_")) name = name.Substring(6); name = name.Replace('_', ' '); name = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(name.ToLower()); return name; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if (provider != null) { this.editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; } if (this.editorService != null) { String bbs = value.ToString(); for (int i=0;i<bbs.Length;i++) { try { String Text; if (LinearEnum==true) Text = Enum.GetName(currentPropertyEnum.GetType(), i); // for 'classic' Enum like 0,1,2,3 ... else Text = Enum.GetName(currentPropertyEnum.GetType(), 1 << i); // for 2^n shift Enum like 1,2,4,8, ... if ((bbs[i] == '1') && !(ObjetList is CheckedListBox)) ObjetList.Items.Add(GetNiceName(Text)); if (ObjetList is CheckedListBox) (ObjetList as CheckedListBox).Items.Add(GetNiceName(Text), bbs[i] == '1'); } catch { } } if (ObjetList.Items.Count == 0) // when bitstring is only 00000... ObjetList.Items.Add("... Nothing"); // shows the list this.editorService.DropDownControl(ObjetList); } return value; // do not allows any change } } // In order to remove the default PriorityArray editor which is a problem public class BacnetEditPriorityArray : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.None; } } // In order to give a readable name to classic enums public class BacnetEnumValueDisplay : UITypeEditor { ListBox EnumList; IWindowsFormsEditorService editorService; Enum currentPropertyEnum; // the corresponding Enum is given in parameter public BacnetEnumValueDisplay(Enum e) { currentPropertyEnum = e; } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } public static string GetNiceName(String name) { if (name == null) return ""; // Outbound enum (proprietary) if (name.StartsWith("EVENT_STATE_")) name = name.Substring(12); if (name.StartsWith("POLARITY_")) name = name.Substring(9); if (name.StartsWith("RELIABILITY_")) name = name.Substring(12); if (name.StartsWith("SEGMENTATION_")) name = name.Substring(13); if (name.StartsWith("STATUS_")) name = name.Substring(7); if (name.StartsWith("NOTIFY_")) name = name.Substring(7); if (name.StartsWith("UNITS_")) name = name.Substring(6); name = name.Replace('_', ' '); name = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(name.ToLower()); return name; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if (provider != null) { this.editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; } if (this.editorService != null) { int InitialIdx = (int)(uint)value; if (EnumList == null) { EnumList = new ListBox(); EnumList.Click += new EventHandler(EnumList_Click); // get all the Enum values string String[] sl=Enum.GetNames(currentPropertyEnum.GetType()); for (int i = 0; i < sl.Length; i++) { if ((currentPropertyEnum.GetType() == typeof(BacnetObjectTypes)) && (i >= (int)BacnetObjectTypes.MAX_ASHRAE_OBJECT_TYPE)) break; // One property with some content not usefull EnumList.Items.Add(i.ToString() + " : " + GetNiceName(sl[i])); // add to the list } if (InitialIdx<EnumList.Items.Count) EnumList.SelectedIndex = InitialIdx; // select the current item if any } this.editorService.DropDownControl(EnumList); // shows the list if ((EnumList.SelectedIndex!=InitialIdx)&&(InitialIdx<EnumList.Items.Count)) return (uint)EnumList.SelectedIndex; // change the value if required } return value; } void EnumList_Click(object sender, EventArgs e) { if (this.editorService != null) this.editorService.CloseDropDown(); } } // used for BacnetTime (without Date, but stored in a DateTime struct) public class BacnetEnumValueConverter : TypeConverter { Enum currentPropertyEnum; // the corresponding Enum is given in parameter public BacnetEnumValueConverter(Enum e) { currentPropertyEnum = e; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { if (destinationType == typeof(System.String) && value is uint) { int i = (int)(uint)value; return i.ToString() + " : " + BacnetEnumValueDisplay.GetNiceName(Enum.GetName(currentPropertyEnum.GetType(), (uint)i)); } else return base.ConvertTo(context, culture, value, destinationType); } } // by FC // this class is used to display // the priority name instead of the index base 0 for the Priority Array // the priority level name for notification class priority array // the priority level name for the event time stamp // the 1 base array index for multistate objects text property // Thank to Gerd Klevesaat's article in http://www.codeproject.com/Articles/4448/Customized-display-of-collection-data-in-a-Propert public class BacnetArrayIndexConverter : ArrayConverter { public enum BacnetEventStates { TO_OFF_NORMAL, TO_FAULT, TO_NORMAL }; public class BacnetArrayPropertyDescriptor : PropertyDescriptor { private PropertyDescriptor m_Property = null; private int m_idx; private Enum m_enum; public BacnetArrayPropertyDescriptor(PropertyDescriptor Property, int Idx, Enum e) : base(Property) { m_Property = Property; m_idx = Idx; m_enum = e; } // This is what we want, and only this public override string DisplayName { get { if (m_enum!=null) { string s = Enum.GetValues(m_enum.GetType()).GetValue(m_idx).ToString(); s = s.Replace('_', ' '); return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower()); } else return "[" + m_idx.ToString() + "]"; // special behaviour for State Text in mutlistate objects, only array bounds shift, no more ! } } public override bool CanResetValue(object component) { return m_Property.CanResetValue(component); } public override Type ComponentType { get { return m_Property.ComponentType; }} public override object GetValue(object component) { return m_Property.GetValue(component); } public override bool IsReadOnly { get { return m_Property.IsReadOnly; } } public override Type PropertyType { get { return m_Property.PropertyType; }} public override void ResetValue(object component) { m_Property.ResetValue(component); } public override void SetValue(object component, object value) { m_Property.SetValue(component, value); } public override bool ShouldSerializeValue(object component) { return m_Property.ShouldSerializeValue(component); } } Enum _e; public BacnetArrayIndexConverter(Enum e) { _e=e; } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { try { PropertyDescriptorCollection s = base.GetProperties(context, value, attributes); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // PriorityArray is a C# 0 base array for a Bacnet 1 base array // use also for StateText property array in multistate objects : http://www.chipkin.com/bacnet-multi-state-variables-state-zero/ int shift=0; if ((_e==null) || (_e.GetType() == typeof(BacnetWritePriority))) shift = 1; for (int i = 0; i < s.Count; i++) { BacnetArrayPropertyDescriptor pd = new BacnetArrayPropertyDescriptor(s[i], i + shift, _e); pds.Add(pd); } return pds; } catch { return base.GetProperties(context, value, attributes); } } } /// <summary> /// Custom PropertyDescriptor /// </summary> /// class CustomPropertyDescriptor: PropertyDescriptor { CustomProperty m_Property; static CustomPropertyDescriptor() { TypeDescriptor.AddAttributes(typeof(BacnetDeviceObjectPropertyReference), new TypeConverterAttribute(typeof(BacnetDeviceObjectPropertyReferenceConverter))); TypeDescriptor.AddAttributes(typeof(BacnetObjectId), new TypeConverterAttribute(typeof(BacnetObjectIdentifierConverter))); TypeDescriptor.AddAttributes(typeof(BacnetBitString), new TypeConverterAttribute(typeof(BacnetBitStringConverter))); } public CustomPropertyDescriptor(ref CustomProperty myProperty, Attribute [] attrs) :base(myProperty.Name, attrs) { m_Property = myProperty; } public CustomProperty CustomProperty { get { return m_Property; } } #region PropertyDescriptor specific public override bool CanResetValue(object component) { return true; } public override Type ComponentType { get { return null; } } public override object GetValue(object component) { return m_Property.Value; } public override string Description { get { return m_Property.Description; } } public override string Category { get { return m_Property.Category; } } public override string DisplayName { get { return m_Property.Name; } } public override bool IsReadOnly { get { return m_Property.ReadOnly; } } public override void ResetValue(object component) { m_Property.Reset(); } public override bool ShouldSerializeValue(object component) { return false; } public override void SetValue(object component, object value) { m_Property.Value = value; } public override Type PropertyType { get { return m_Property.Type; } } public override TypeConverter Converter { get { if (m_Property.Options != null) return new DynamicEnumConverter(m_Property.Options); else if (m_Property.Type == typeof(float)) return new CustomSingleConverter(); else if (m_Property.bacnetApplicationTags == BacnetApplicationTags.BACNET_APPLICATION_TAG_TIME) return new BacnetTimeConverter(); // A lot of classic Bacnet Enum BacnetPropertyReference bpr = (BacnetPropertyReference)m_Property.Tag; switch ((BacnetPropertyIds)bpr.propertyIdentifier) { case BacnetPropertyIds.PROP_OBJECT_TYPE: return new BacnetEnumValueConverter(new BacnetObjectTypes()); case BacnetPropertyIds.PROP_NOTIFY_TYPE: return new BacnetEnumValueConverter(new BacnetEventNotificationData.BacnetNotifyTypes()); case BacnetPropertyIds.PROP_EVENT_TYPE: return new BacnetEnumValueConverter(new BacnetEventNotificationData.BacnetEventTypes()); case BacnetPropertyIds.PROP_EVENT_STATE: return new BacnetEnumValueConverter(new BacnetEventNotificationData.BacnetEventStates()); case BacnetPropertyIds.PROP_POLARITY: return new BacnetEnumValueConverter(new BacnetPolarity()); case BacnetPropertyIds.PROP_UNITS: return new BacnetEnumValueConverter(new BacnetUnitsId()); case BacnetPropertyIds.PROP_RELIABILITY: return new BacnetEnumValueConverter(new BacnetReliability()); case BacnetPropertyIds.PROP_SEGMENTATION_SUPPORTED: return new BacnetEnumValueConverter(new BacnetSegmentations()); case BacnetPropertyIds.PROP_SYSTEM_STATUS: return new BacnetEnumValueConverter(new BacnetDeviceStatus()); case BacnetPropertyIds.PROP_LAST_RESTART_REASON: return new BacnetEnumValueConverter(new BacnetRestartReason()); case BacnetPropertyIds.PROP_PRIORITY_FOR_WRITING: return new BacnetEnumValueConverter(new BacnetWritePriority()); case BacnetPropertyIds.PROP_PRIORITY_ARRAY: return new BacnetArrayIndexConverter(new BacnetWritePriority()); case BacnetPropertyIds.PROP_PRIORITY : return new BacnetArrayIndexConverter(new BacnetArrayIndexConverter.BacnetEventStates()); case BacnetPropertyIds.PROP_EVENT_TIME_STAMPS : return new BacnetArrayIndexConverter(new BacnetArrayIndexConverter.BacnetEventStates()); case BacnetPropertyIds.PROP_STATE_TEXT : return new BacnetArrayIndexConverter(null); case BacnetPropertyIds.PROP_PROGRAM_CHANGE : return new BacnetEnumValueConverter(new BacnetProgramChange()); case BacnetPropertyIds.PROP_PROGRAM_STATE: return new BacnetEnumValueConverter(new BacnetProgramState()); case BacnetPropertyIds.PROP_REASON_FOR_HALT: return new BacnetEnumValueConverter(new BacnetReasonForHalt()); case BacnetPropertyIds.PROP_BACKUP_AND_RESTORE_STATE: return new BacnetEnumValueConverter(new BACnetBackupState()); case BacnetPropertyIds.PROP_FILE_ACCESS_METHOD: return new BacnetEnumValueConverter(new BacnetFileAccessMethod()); default: return base.Converter; } } } // Give a way to display/modify some specifics values in a ListBox public override object GetEditor(Type editorBaseType) { // All Bacnet Time as this if (m_Property.bacnetApplicationTags == BacnetApplicationTags.BACNET_APPLICATION_TAG_TIME) return new BacnetTimePickerEditor(); BacnetPropertyReference bpr=(BacnetPropertyReference)m_Property.Tag; // A lot of classic Bacnet Enum & BitString switch ((BacnetPropertyIds)bpr.propertyIdentifier) { case BacnetPropertyIds.PROP_PROTOCOL_OBJECT_TYPES_SUPPORTED: return new BacnetBitStringToEnumListDisplay(new BacnetObjectTypes(), true); case BacnetPropertyIds.PROP_PROTOCOL_SERVICES_SUPPORTED: return new BacnetBitStringToEnumListDisplay(new BacnetServicesSupported(), true); case BacnetPropertyIds.PROP_STATUS_FLAGS: return new BacnetBitStringToEnumListDisplay(new BacnetStatusFlags(), false, true); case BacnetPropertyIds.PROP_LIMIT_ENABLE: return new BacnetBitStringToEnumListDisplay(new BacnetEventNotificationData.BacnetLimitEnable(), false, true); case BacnetPropertyIds.PROP_EVENT_ENABLE: case BacnetPropertyIds.PROP_ACK_REQUIRED: case BacnetPropertyIds.PROP_ACKED_TRANSITIONS: return new BacnetBitStringToEnumListDisplay(new BacnetEventNotificationData.BacnetEventEnable(), false, true); case BacnetPropertyIds.PROP_OBJECT_TYPE: return new BacnetEnumValueDisplay(new BacnetObjectTypes()); case BacnetPropertyIds.PROP_NOTIFY_TYPE: return new BacnetEnumValueDisplay(new BacnetEventNotificationData.BacnetNotifyTypes()); case BacnetPropertyIds.PROP_EVENT_TYPE: return new BacnetEnumValueDisplay(new BacnetEventNotificationData.BacnetEventTypes()); case BacnetPropertyIds.PROP_EVENT_STATE: return new BacnetEnumValueDisplay(new BacnetEventNotificationData.BacnetEventStates()); case BacnetPropertyIds.PROP_POLARITY: return new BacnetEnumValueDisplay(new BacnetPolarity()); case BacnetPropertyIds.PROP_UNITS: return new BacnetEnumValueDisplay(new BacnetUnitsId()); case BacnetPropertyIds.PROP_RELIABILITY: return new BacnetEnumValueDisplay(new BacnetReliability()); case BacnetPropertyIds.PROP_SEGMENTATION_SUPPORTED: return new BacnetEnumValueDisplay(new BacnetSegmentations()); case BacnetPropertyIds.PROP_SYSTEM_STATUS: return new BacnetEnumValueDisplay(new BacnetDeviceStatus()); case BacnetPropertyIds.PROP_LAST_RESTART_REASON: return new BacnetEnumValueDisplay(new BacnetRestartReason()); case BacnetPropertyIds.PROP_PRIORITY_FOR_WRITING: return new BacnetEnumValueDisplay(new BacnetWritePriority()); case BacnetPropertyIds.PROP_PROGRAM_CHANGE: return new BacnetEnumValueDisplay(new BacnetProgramChange()); case BacnetPropertyIds.PROP_PRIORITY_ARRAY: return new BacnetEditPriorityArray(); case BacnetPropertyIds.PROP_BACKUP_AND_RESTORE_STATE: return new BacnetEnumValueDisplay(new BACnetBackupState()); case BacnetPropertyIds.PROP_FILE_ACCESS_METHOD: return new BacnetEnumValueDisplay(new BacnetFileAccessMethod()); default : return base.GetEditor(editorBaseType); } } public DynamicEnum Options { get { return m_Property.Options; } } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Retail.V2.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedCatalogServiceClientSnippets { /// <summary>Snippet for ListCatalogs</summary> public void ListCatalogsRequestObject() { // Snippet: ListCatalogs(ListCatalogsRequest, CallSettings) // Create client CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create(); // Initialize request argument(s) ListCatalogsRequest request = new ListCatalogsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; // Make the request PagedEnumerable<ListCatalogsResponse, Catalog> response = catalogServiceClient.ListCatalogs(request); // Iterate over all response items, lazily performing RPCs as required foreach (Catalog item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListCatalogsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Catalog item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Catalog> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Catalog item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListCatalogsAsync</summary> public async Task ListCatalogsRequestObjectAsync() { // Snippet: ListCatalogsAsync(ListCatalogsRequest, CallSettings) // Create client CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync(); // Initialize request argument(s) ListCatalogsRequest request = new ListCatalogsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; // Make the request PagedAsyncEnumerable<ListCatalogsResponse, Catalog> response = catalogServiceClient.ListCatalogsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Catalog item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListCatalogsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Catalog item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Catalog> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Catalog item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListCatalogs</summary> public void ListCatalogs() { // Snippet: ListCatalogs(string, string, int?, CallSettings) // Create client CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedEnumerable<ListCatalogsResponse, Catalog> response = catalogServiceClient.ListCatalogs(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Catalog item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListCatalogsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Catalog item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Catalog> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Catalog item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListCatalogsAsync</summary> public async Task ListCatalogsAsync() { // Snippet: ListCatalogsAsync(string, string, int?, CallSettings) // Create client CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedAsyncEnumerable<ListCatalogsResponse, Catalog> response = catalogServiceClient.ListCatalogsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Catalog item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListCatalogsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Catalog item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Catalog> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Catalog item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListCatalogs</summary> public void ListCatalogsResourceNames() { // Snippet: ListCatalogs(LocationName, string, int?, CallSettings) // Create client CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedEnumerable<ListCatalogsResponse, Catalog> response = catalogServiceClient.ListCatalogs(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Catalog item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListCatalogsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Catalog item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Catalog> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Catalog item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListCatalogsAsync</summary> public async Task ListCatalogsResourceNamesAsync() { // Snippet: ListCatalogsAsync(LocationName, string, int?, CallSettings) // Create client CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedAsyncEnumerable<ListCatalogsResponse, Catalog> response = catalogServiceClient.ListCatalogsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Catalog item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListCatalogsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Catalog item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Catalog> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Catalog item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for UpdateCatalog</summary> public void UpdateCatalogRequestObject() { // Snippet: UpdateCatalog(UpdateCatalogRequest, CallSettings) // Create client CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create(); // Initialize request argument(s) UpdateCatalogRequest request = new UpdateCatalogRequest { Catalog = new Catalog(), UpdateMask = new FieldMask(), }; // Make the request Catalog response = catalogServiceClient.UpdateCatalog(request); // End snippet } /// <summary>Snippet for UpdateCatalogAsync</summary> public async Task UpdateCatalogRequestObjectAsync() { // Snippet: UpdateCatalogAsync(UpdateCatalogRequest, CallSettings) // Additional: UpdateCatalogAsync(UpdateCatalogRequest, CancellationToken) // Create client CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync(); // Initialize request argument(s) UpdateCatalogRequest request = new UpdateCatalogRequest { Catalog = new Catalog(), UpdateMask = new FieldMask(), }; // Make the request Catalog response = await catalogServiceClient.UpdateCatalogAsync(request); // End snippet } /// <summary>Snippet for UpdateCatalog</summary> public void UpdateCatalog() { // Snippet: UpdateCatalog(Catalog, FieldMask, CallSettings) // Create client CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create(); // Initialize request argument(s) Catalog catalog = new Catalog(); FieldMask updateMask = new FieldMask(); // Make the request Catalog response = catalogServiceClient.UpdateCatalog(catalog, updateMask); // End snippet } /// <summary>Snippet for UpdateCatalogAsync</summary> public async Task UpdateCatalogAsync() { // Snippet: UpdateCatalogAsync(Catalog, FieldMask, CallSettings) // Additional: UpdateCatalogAsync(Catalog, FieldMask, CancellationToken) // Create client CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync(); // Initialize request argument(s) Catalog catalog = new Catalog(); FieldMask updateMask = new FieldMask(); // Make the request Catalog response = await catalogServiceClient.UpdateCatalogAsync(catalog, updateMask); // End snippet } /// <summary>Snippet for SetDefaultBranch</summary> public void SetDefaultBranchRequestObject() { // Snippet: SetDefaultBranch(SetDefaultBranchRequest, CallSettings) // Create client CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create(); // Initialize request argument(s) SetDefaultBranchRequest request = new SetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), BranchIdAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Note = "", }; // Make the request catalogServiceClient.SetDefaultBranch(request); // End snippet } /// <summary>Snippet for SetDefaultBranchAsync</summary> public async Task SetDefaultBranchRequestObjectAsync() { // Snippet: SetDefaultBranchAsync(SetDefaultBranchRequest, CallSettings) // Additional: SetDefaultBranchAsync(SetDefaultBranchRequest, CancellationToken) // Create client CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync(); // Initialize request argument(s) SetDefaultBranchRequest request = new SetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), BranchIdAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Note = "", }; // Make the request await catalogServiceClient.SetDefaultBranchAsync(request); // End snippet } /// <summary>Snippet for SetDefaultBranch</summary> public void SetDefaultBranch() { // Snippet: SetDefaultBranch(string, CallSettings) // Create client CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create(); // Initialize request argument(s) string catalog = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]"; // Make the request catalogServiceClient.SetDefaultBranch(catalog); // End snippet } /// <summary>Snippet for SetDefaultBranchAsync</summary> public async Task SetDefaultBranchAsync() { // Snippet: SetDefaultBranchAsync(string, CallSettings) // Additional: SetDefaultBranchAsync(string, CancellationToken) // Create client CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync(); // Initialize request argument(s) string catalog = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]"; // Make the request await catalogServiceClient.SetDefaultBranchAsync(catalog); // End snippet } /// <summary>Snippet for SetDefaultBranch</summary> public void SetDefaultBranchResourceNames() { // Snippet: SetDefaultBranch(CatalogName, CallSettings) // Create client CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create(); // Initialize request argument(s) CatalogName catalog = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"); // Make the request catalogServiceClient.SetDefaultBranch(catalog); // End snippet } /// <summary>Snippet for SetDefaultBranchAsync</summary> public async Task SetDefaultBranchResourceNamesAsync() { // Snippet: SetDefaultBranchAsync(CatalogName, CallSettings) // Additional: SetDefaultBranchAsync(CatalogName, CancellationToken) // Create client CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync(); // Initialize request argument(s) CatalogName catalog = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"); // Make the request await catalogServiceClient.SetDefaultBranchAsync(catalog); // End snippet } /// <summary>Snippet for GetDefaultBranch</summary> public void GetDefaultBranchRequestObject() { // Snippet: GetDefaultBranch(GetDefaultBranchRequest, CallSettings) // Create client CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create(); // Initialize request argument(s) GetDefaultBranchRequest request = new GetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), }; // Make the request GetDefaultBranchResponse response = catalogServiceClient.GetDefaultBranch(request); // End snippet } /// <summary>Snippet for GetDefaultBranchAsync</summary> public async Task GetDefaultBranchRequestObjectAsync() { // Snippet: GetDefaultBranchAsync(GetDefaultBranchRequest, CallSettings) // Additional: GetDefaultBranchAsync(GetDefaultBranchRequest, CancellationToken) // Create client CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync(); // Initialize request argument(s) GetDefaultBranchRequest request = new GetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), }; // Make the request GetDefaultBranchResponse response = await catalogServiceClient.GetDefaultBranchAsync(request); // End snippet } /// <summary>Snippet for GetDefaultBranch</summary> public void GetDefaultBranch() { // Snippet: GetDefaultBranch(string, CallSettings) // Create client CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create(); // Initialize request argument(s) string catalog = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]"; // Make the request GetDefaultBranchResponse response = catalogServiceClient.GetDefaultBranch(catalog); // End snippet } /// <summary>Snippet for GetDefaultBranchAsync</summary> public async Task GetDefaultBranchAsync() { // Snippet: GetDefaultBranchAsync(string, CallSettings) // Additional: GetDefaultBranchAsync(string, CancellationToken) // Create client CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync(); // Initialize request argument(s) string catalog = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]"; // Make the request GetDefaultBranchResponse response = await catalogServiceClient.GetDefaultBranchAsync(catalog); // End snippet } /// <summary>Snippet for GetDefaultBranch</summary> public void GetDefaultBranchResourceNames() { // Snippet: GetDefaultBranch(CatalogName, CallSettings) // Create client CatalogServiceClient catalogServiceClient = CatalogServiceClient.Create(); // Initialize request argument(s) CatalogName catalog = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"); // Make the request GetDefaultBranchResponse response = catalogServiceClient.GetDefaultBranch(catalog); // End snippet } /// <summary>Snippet for GetDefaultBranchAsync</summary> public async Task GetDefaultBranchResourceNamesAsync() { // Snippet: GetDefaultBranchAsync(CatalogName, CallSettings) // Additional: GetDefaultBranchAsync(CatalogName, CancellationToken) // Create client CatalogServiceClient catalogServiceClient = await CatalogServiceClient.CreateAsync(); // Initialize request argument(s) CatalogName catalog = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"); // Make the request GetDefaultBranchResponse response = await catalogServiceClient.GetDefaultBranchAsync(catalog); // End snippet } } }
// 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.Text; using System.Diagnostics; using System.Collections.Generic; namespace System.Xml { internal partial class XmlWellFormedWriter : XmlWriter { // // Private types // class NamespaceResolverProxy : IXmlNamespaceResolver { XmlWellFormedWriter wfWriter; internal NamespaceResolverProxy(XmlWellFormedWriter wfWriter) { this.wfWriter = wfWriter; } IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) { throw NotImplemented.ByDesign; } string IXmlNamespaceResolver.LookupNamespace(string prefix) { return wfWriter.LookupNamespace(prefix); } string IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return wfWriter.LookupPrefix(namespaceName); } } partial struct ElementScope { internal int prevNSTop; internal string prefix; internal string localName; internal string namespaceUri; internal XmlSpace xmlSpace; internal string xmlLang; internal void Set(string prefix, string localName, string namespaceUri, int prevNSTop) { this.prevNSTop = prevNSTop; this.prefix = prefix; this.namespaceUri = namespaceUri; this.localName = localName; this.xmlSpace = (System.Xml.XmlSpace)(int)-1; this.xmlLang = null; } internal void WriteEndElement(XmlRawWriter rawWriter) { rawWriter.WriteEndElement(prefix, localName, namespaceUri); } internal void WriteFullEndElement(XmlRawWriter rawWriter) { rawWriter.WriteFullEndElement(prefix, localName, namespaceUri); } } enum NamespaceKind { Written, NeedToWrite, Implied, Special, } partial struct Namespace { internal string prefix; internal string namespaceUri; internal NamespaceKind kind; internal int prevNsIndex; internal void Set(string prefix, string namespaceUri, NamespaceKind kind) { this.prefix = prefix; this.namespaceUri = namespaceUri; this.kind = kind; this.prevNsIndex = -1; } internal void WriteDecl(XmlWriter writer, XmlRawWriter rawWriter) { Debug.Assert(kind == NamespaceKind.NeedToWrite); if (null != rawWriter) { rawWriter.WriteNamespaceDeclaration(prefix, namespaceUri); } else { if (prefix.Length == 0) { writer.WriteStartAttribute(string.Empty, XmlConst.NsXmlNs, XmlConst.ReservedNsXmlNs); } else { writer.WriteStartAttribute(XmlConst.NsXmlNs, prefix, XmlConst.ReservedNsXmlNs); } writer.WriteString(namespaceUri); writer.WriteEndAttribute(); } } } struct AttrName { internal string prefix; internal string namespaceUri; internal string localName; internal int prev; internal void Set(string prefix, string localName, string namespaceUri) { this.prefix = prefix; this.namespaceUri = namespaceUri; this.localName = localName; this.prev = 0; } internal bool IsDuplicate(string prefix, string localName, string namespaceUri) { return ((this.localName == localName) && ((this.prefix == prefix) || (this.namespaceUri == namespaceUri))); } } enum SpecialAttribute { No = 0, DefaultXmlns, PrefixedXmlns, XmlSpace, XmlLang } partial class AttributeValueCache { enum ItemType { EntityRef, CharEntity, SurrogateCharEntity, Whitespace, String, StringChars, Raw, RawChars, ValueString, } class Item { internal ItemType type; internal object data; internal Item() { } internal void Set(ItemType type, object data) { this.type = type; this.data = data; } } class BufferChunk { internal char[] buffer; internal int index; internal int count; internal BufferChunk(char[] buffer, int index, int count) { this.buffer = buffer; this.index = index; this.count = count; } } StringBuilder stringValue = new StringBuilder(); string singleStringValue; // special-case for a single WriteString call Item[] items; int firstItem; int lastItem = -1; internal string StringValue { get { if (singleStringValue != null) { return singleStringValue; } else { return stringValue.ToString(); } } } internal void WriteEntityRef(string name) { if (singleStringValue != null) { StartComplexValue(); } switch (name) { case "lt": stringValue.Append('<'); break; case "gt": stringValue.Append('>'); break; case "quot": stringValue.Append('"'); break; case "apos": stringValue.Append('\''); break; case "amp": stringValue.Append('&'); break; default: stringValue.Append('&'); stringValue.Append(name); stringValue.Append(';'); break; } AddItem(ItemType.EntityRef, name); } internal void WriteCharEntity(char ch) { if (singleStringValue != null) { StartComplexValue(); } stringValue.Append(ch); AddItem(ItemType.CharEntity, ch); } internal void WriteSurrogateCharEntity(char lowChar, char highChar) { if (singleStringValue != null) { StartComplexValue(); } stringValue.Append(highChar); stringValue.Append(lowChar); AddItem(ItemType.SurrogateCharEntity, new char[] { lowChar, highChar }); } internal void WriteWhitespace(string ws) { if (singleStringValue != null) { StartComplexValue(); } stringValue.Append(ws); AddItem(ItemType.Whitespace, ws); } internal void WriteString(string text) { if (singleStringValue != null) { StartComplexValue(); } else { // special-case for a single WriteString if (lastItem == -1) { singleStringValue = text; return; } } stringValue.Append(text); AddItem(ItemType.String, text); } internal void WriteChars(char[] buffer, int index, int count) { if (singleStringValue != null) { StartComplexValue(); } stringValue.Append(buffer, index, count); AddItem(ItemType.StringChars, new BufferChunk(buffer, index, count)); } internal void WriteRaw(char[] buffer, int index, int count) { if (singleStringValue != null) { StartComplexValue(); } stringValue.Append(buffer, index, count); AddItem(ItemType.RawChars, new BufferChunk(buffer, index, count)); } internal void WriteRaw(string data) { if (singleStringValue != null) { StartComplexValue(); } stringValue.Append(data); AddItem(ItemType.Raw, data); } internal void WriteValue(string value) { if (singleStringValue != null) { StartComplexValue(); } stringValue.Append(value); AddItem(ItemType.ValueString, value); } internal void Replay(XmlWriter writer) { if (singleStringValue != null) { writer.WriteString(singleStringValue); return; } BufferChunk bufChunk; for (int i = firstItem; i <= lastItem; i++) { Item item = items[i]; switch (item.type) { case ItemType.EntityRef: writer.WriteEntityRef((string)item.data); break; case ItemType.CharEntity: writer.WriteCharEntity((char)item.data); break; case ItemType.SurrogateCharEntity: char[] chars = (char[])item.data; writer.WriteSurrogateCharEntity(chars[0], chars[1]); break; case ItemType.Whitespace: writer.WriteWhitespace((string)item.data); break; case ItemType.String: writer.WriteString((string)item.data); break; case ItemType.StringChars: bufChunk = (BufferChunk)item.data; writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count); break; case ItemType.Raw: writer.WriteRaw((string)item.data); break; case ItemType.RawChars: bufChunk = (BufferChunk)item.data; writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count); break; case ItemType.ValueString: writer.WriteValue((string)item.data); break; default: Debug.Assert(false, "Unexpected ItemType value."); break; } } } // This method trims whitespaces from the beginnig and the end of the string and cached writer events internal void Trim() { // if only one string value -> trim the write spaces directly if (singleStringValue != null) { singleStringValue = XmlConvertEx.TrimString(singleStringValue); return; } // trim the string in StringBuilder string valBefore = stringValue.ToString(); string valAfter = XmlConvertEx.TrimString(valBefore); if (valBefore != valAfter) { stringValue = new StringBuilder(valAfter); } // trim the beginning of the recorded writer events XmlCharType xmlCharType = XmlCharType.Instance; int i = firstItem; while (i == firstItem && i <= lastItem) { Item item = items[i]; switch (item.type) { case ItemType.Whitespace: firstItem++; break; case ItemType.String: case ItemType.Raw: case ItemType.ValueString: item.data = XmlConvertEx.TrimStringStart((string)item.data); if (((string)item.data).Length == 0) { // no characters left -> move the firstItem index to exclude it from the Replay firstItem++; } break; case ItemType.StringChars: case ItemType.RawChars: BufferChunk bufChunk = (BufferChunk)item.data; int endIndex = bufChunk.index + bufChunk.count; while (bufChunk.index < endIndex && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index])) { bufChunk.index++; bufChunk.count--; } if (bufChunk.index == endIndex) { // no characters left -> move the firstItem index to exclude it from the Replay firstItem++; } break; } i++; } // trim the end of the recorded writer events i = lastItem; while (i == lastItem && i >= firstItem) { Item item = items[i]; switch (item.type) { case ItemType.Whitespace: lastItem--; break; case ItemType.String: case ItemType.Raw: case ItemType.ValueString: item.data = XmlConvertEx.TrimStringEnd((string)item.data); if (((string)item.data).Length == 0) { // no characters left -> move the lastItem index to exclude it from the Replay lastItem--; } break; case ItemType.StringChars: case ItemType.RawChars: BufferChunk bufChunk = (BufferChunk)item.data; while (bufChunk.count > 0 && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index + bufChunk.count - 1])) { bufChunk.count--; } if (bufChunk.count == 0) { // no characters left -> move the lastItem index to exclude it from the Replay lastItem--; } break; } i--; } } internal void Clear() { singleStringValue = null; lastItem = -1; firstItem = 0; stringValue.Length = 0; } private void StartComplexValue() { Debug.Assert(singleStringValue != null); Debug.Assert(lastItem == -1); stringValue.Append(singleStringValue); AddItem(ItemType.String, singleStringValue); singleStringValue = null; } void AddItem(ItemType type, object data) { int newItemIndex = lastItem + 1; if (items == null) { items = new Item[4]; } else if (items.Length == newItemIndex) { Item[] newItems = new Item[newItemIndex * 2]; Array.Copy(items, newItems, newItemIndex); items = newItems; } if (items[newItemIndex] == null) { items[newItemIndex] = new Item(); } items[newItemIndex].Set(type, data); lastItem = newItemIndex; } } } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.Presentation { using System.Activities.Presentation.Internal.Properties; using System; using System.Runtime; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Text; using System.Activities.Presentation; // <summary> // The EditingContext class contains contextual state about a designer. This includes permanent // state such as list of services running in the designer. // It also includes transient state consisting of context items. Examples of transient // context item state include the set of currently selected objects as well as the editing tool // being used to manipulate objects on the design surface. // // The editing context is designed to be a concrete class for ease of use. It does have a protected // API that can be used to replace its implementation. // </summary> public class EditingContext : IDisposable { private ContextItemManager _contextItems; private ServiceManager _services; // <summary> // Creates a new editing context. // </summary> public EditingContext() { } // <summary> // The Disposing event gets fired just before the context gets disposed. // </summary> public event EventHandler Disposing; // <summary> // Returns the local collection of context items offered by this editing context. // </summary> // <value></value> public ContextItemManager Items { get { if (_contextItems == null) { _contextItems = CreateContextItemManager(); if (_contextItems == null) { throw FxTrace.Exception.AsError(new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, Resources.Error_NullImplementation, "CreateContextItemManager"))); } } return _contextItems; } } // <summary> // Returns the service manager for this editing context. // </summary> // <value></value> public ServiceManager Services { get { if (_services == null) { _services = CreateServiceManager(); if (_services == null) { throw FxTrace.Exception.AsError(new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, Resources.Error_NullImplementation, "CreateServiceManager"))); } } return _services; } } // <summary> // Creates an instance of the context item manager to be returned from // the ContextItems property. The default implementation creates a // ContextItemManager that supports delayed activation of design editor // managers through the declaration of a SubscribeContext attribute on // the design editor manager. // </summary> // <returns>Returns an implementation of the ContextItemManager class.</returns> protected virtual ContextItemManager CreateContextItemManager() { return new DefaultContextItemManager(this); } // <summary> // Creates an instance of the service manager to be returned from the // Services property. The default implementation creates a ServiceManager // that supports delayed activation of design editor managers through the // declaration of a SubscribeService attribute on the design editor manager. // </summary> // <returns>Returns an implemetation of the ServiceManager class.</returns> protected virtual ServiceManager CreateServiceManager() { return new DefaultServiceManager(); } // <summary> // Disposes this editing context. // </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // <summary> // Disposes this editing context. // <param name="disposing">True if this object is being disposed, or false if it is finalizing.</param> // </summary> protected virtual void Dispose(bool disposing) { if (disposing) { // Let any interested parties know the context is being disposed if (Disposing != null) { Disposing(this, EventArgs.Empty); } IDisposable d = _services as IDisposable; if (d != null) { d.Dispose(); } d = _contextItems as IDisposable; if (d != null) { d.Dispose(); } } } // <summary> // This is the default context item manager for our editing context. // </summary> private sealed class DefaultContextItemManager : ContextItemManager { private EditingContext _context; private DefaultContextLayer _currentLayer; private Dictionary<Type, SubscribeContextCallback> _subscriptions; internal DefaultContextItemManager(EditingContext context) { _context = context; _currentLayer = new DefaultContextLayer(null); } // <summary> // This changes a context item to the given value. It is illegal to pass // null here. If you want to set a context item to its empty value create // an instance of the item using a default constructor. // </summary> // <param name="value"></param> public override void SetValue(ContextItem value) { if (value == null) { throw FxTrace.Exception.ArgumentNull("value"); } // The rule for change is that we store the new value, // raise a change on the item, and then raise a change // to everyone else. If changing the item fails, we recover // the previous item. ContextItem existing, existingRawValue; existing = existingRawValue = GetValueNull(value.ItemType); if (existing == null) { existing = GetValue(value.ItemType); } bool success = false; try { _currentLayer.Items[value.ItemType] = value; NotifyItemChanged(_context, value, existing); success = true; } finally { if (success) { OnItemChanged(value); } else { // The item threw during its transition to // becoming active. Put the old one back. // We must put the old one back by re-activating // it. This could throw a second time, so we // cover this case by removing the value first. // Should it throw again, we won't recurse because // the existing raw value would be null. _currentLayer.Items.Remove(value.ItemType); if (existingRawValue != null) { SetValue(existingRawValue); } } } } // <summary> // Returns true if the item manager contains an item of the given type. // This only looks in the current layer. // </summary> // <param name="itemType"></param> // <returns></returns> public override bool Contains(Type itemType) { if (itemType == null) { throw FxTrace.Exception.ArgumentNull("itemType"); } if (!typeof(ContextItem).IsAssignableFrom(itemType)) { throw FxTrace.Exception.AsError(new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.Error_ArgIncorrectType, "itemType", typeof(ContextItem).FullName))); } return _currentLayer.Items.ContainsKey(itemType); } // <summary> // Returns an instance of the requested item type. If there is no context // item with the given type, an empty item will be created. // </summary> // <param name="itemType"></param> // <returns></returns> public override ContextItem GetValue(Type itemType) { ContextItem item = GetValueNull(itemType); if (item == null) { // Check the default item table and add a new // instance there if we need to if (!_currentLayer.DefaultItems.TryGetValue(itemType, out item)) { item = (ContextItem)Activator.CreateInstance(itemType); // Verify that the resulting item has the correct item type // If it doesn't, it means that the user provided a derived // item type if (item.ItemType != itemType) { throw FxTrace.Exception.AsError(new ArgumentException(string.Format( CultureInfo.CurrentCulture, Resources.Error_DerivedContextItem, itemType.FullName, item.ItemType.FullName))); } // Now push the item in the context so we have // a consistent reference _currentLayer.DefaultItems.Add(item.ItemType, item); } } return item; } // <summary> // Similar to GetValue, but returns NULL if the item isn't found instead of // creating an empty item. // </summary> // <param name="itemType"></param> // <returns></returns> private ContextItem GetValueNull(Type itemType) { if (itemType == null) { throw FxTrace.Exception.ArgumentNull("itemType"); } if (!typeof(ContextItem).IsAssignableFrom(itemType)) { throw FxTrace.Exception.AsError(new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.Error_ArgIncorrectType, "itemType", typeof(ContextItem).FullName))); } ContextItem item = null; DefaultContextLayer layer = _currentLayer; while (layer != null && !layer.Items.TryGetValue(itemType, out item)) { layer = layer.ParentLayer; } return item; } // <summary> // Enumerates the context items in the editing context. This enumeration // includes prior layers unless the enumerator hits an isolated layer. // Enumeration is typically not useful in most scenarios but it is provided so // that developers can search in the context and learn what is placed in it. // </summary> // <returns></returns> public override IEnumerator<ContextItem> GetEnumerator() { return _currentLayer.Items.Values.GetEnumerator(); } // <summary> // Called when an item changes value. This happens in one of two ways: // either the user has called Change, or the user has removed a layer. // </summary> // <param name="item"></param> private void OnItemChanged(ContextItem item) { SubscribeContextCallback callback; Fx.Assert(item != null, "You cannot pass a null item here."); if (_subscriptions != null && _subscriptions.TryGetValue(item.ItemType, out callback)) { callback(item); } } // <summary> // Adds an event callback that will be invoked with a context item of the given item type changes. // </summary> // <param name="contextItemType"></param> // <param name="callback"></param> public override void Subscribe(Type contextItemType, SubscribeContextCallback callback) { if (contextItemType == null) { throw FxTrace.Exception.ArgumentNull("contextItemType"); } if (callback == null) { throw FxTrace.Exception.ArgumentNull("callback"); } if (!typeof(ContextItem).IsAssignableFrom(contextItemType)) { throw FxTrace.Exception.AsError(new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.Error_ArgIncorrectType, "contextItemType", typeof(ContextItem).FullName))); } if (_subscriptions == null) { _subscriptions = new Dictionary<Type, SubscribeContextCallback>(); } SubscribeContextCallback existing = null; _subscriptions.TryGetValue(contextItemType, out existing); existing = (SubscribeContextCallback)Delegate.Combine(existing, callback); _subscriptions[contextItemType] = existing; // If the context is already present, invoke the callback. ContextItem item = GetValueNull(contextItemType); if (item != null) { callback(item); } } // <summary> // Removes a subscription. // </summary> public override void Unsubscribe(Type contextItemType, SubscribeContextCallback callback) { if (contextItemType == null) { throw FxTrace.Exception.ArgumentNull("contextItemType"); } if (callback == null) { throw FxTrace.Exception.ArgumentNull("callback"); } if (!typeof(ContextItem).IsAssignableFrom(contextItemType)) { throw FxTrace.Exception.AsError(new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.Error_ArgIncorrectType, "contextItemType", typeof(ContextItem).FullName))); } if (_subscriptions != null) { SubscribeContextCallback existing; if (_subscriptions.TryGetValue(contextItemType, out existing)) { existing = (SubscribeContextCallback)RemoveCallback(existing, callback); if (existing == null) { _subscriptions.Remove(contextItemType); } else { _subscriptions[contextItemType] = existing; } } } } // <summary> // This context layer contains our context items. // </summary> private class DefaultContextLayer { private DefaultContextLayer _parentLayer; private Dictionary<Type, ContextItem> _items; private Dictionary<Type, ContextItem> _defaultItems; internal DefaultContextLayer(DefaultContextLayer parentLayer) { _parentLayer = parentLayer; // can be null } internal Dictionary<Type, ContextItem> DefaultItems { get { if (_defaultItems == null) { _defaultItems = new Dictionary<Type, ContextItem>(); } return _defaultItems; } } internal Dictionary<Type, ContextItem> Items { get { if (_items == null) { _items = new Dictionary<Type, ContextItem>(); } return _items; } } internal DefaultContextLayer ParentLayer { get { return _parentLayer; } } } } // <summary> // This is the default service manager for our editing context. // </summary> private sealed class DefaultServiceManager : ServiceManager, IDisposable { private static readonly object _recursionSentinel = new object(); private Dictionary<Type, object> _services; private Dictionary<Type, SubscribeServiceCallback> _subscriptions; internal DefaultServiceManager() { } // <summary> // Returns true if the service manager contains a service of the given type. // </summary> // <param name="serviceType"></param> // <returns></returns> public override bool Contains(Type serviceType) { if (serviceType == null) { throw FxTrace.Exception.ArgumentNull("serviceType"); } return (_services != null && _services.ContainsKey(serviceType)); } // <summary> // Retrieves the requested service. This method returns null if the service could not be located. // </summary> // <param name="serviceType"></param> // <returns></returns> public override object GetService(Type serviceType) { object result = this.GetPublishedService(serviceType); if (result == null) { if (this.Contains(typeof(IServiceProvider))) { result = this.GetRequiredService<IServiceProvider>().GetService(serviceType); if (result != null) { this.Publish(serviceType, result); } } } return result; } object GetPublishedService(Type serviceType) { object service = null; if (serviceType == null) { throw FxTrace.Exception.ArgumentNull("serviceType"); } if (_services != null && _services.TryGetValue(serviceType, out service)) { // If this service is our recursion sentinel, it means that someone is recursing // while resolving a service callback. Throw to break out of the recursion // cycle. if (service == _recursionSentinel) { throw FxTrace.Exception.AsError(new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.Error_RecursionResolvingService, serviceType.FullName))); } // See if this service is a callback. If it is, invoke it and store // the resulting service back in the dictionary. PublishServiceCallback callback = service as PublishServiceCallback; if (callback != null) { // Store a recursion sentinel in the dictionary so we can easily // tell if someone is recursing _services[serviceType] = _recursionSentinel; try { service = callback(serviceType); if (service == null) { throw FxTrace.Exception.AsError(new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, Resources.Error_NullService, callback.Method.DeclaringType.FullName, serviceType.FullName))); } if (!serviceType.IsInstanceOfType(service)) { throw FxTrace.Exception.AsError(new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, Resources.Error_IncorrectServiceType, callback.Method.DeclaringType.FullName, serviceType.FullName, service.GetType().FullName))); } } finally { // Note, this puts the callback back in place if it threw. _services[serviceType] = service; } } } // If the service is not found locally, do not walk up the parent chain. // This was a major source of unreliability with the component model // design. For a service to be accessible from the editing context, it // must be added. return service; } // <summary> // Retrieves an enumerator that can be used to enumerate all of the services that this // service manager publishes. // </summary> // <returns></returns> public override IEnumerator<Type> GetEnumerator() { if (_services == null) { _services = new Dictionary<Type, object>(); } return _services.Keys.GetEnumerator(); } // <summary> // Calls back on the provided callback when someone has published the requested service. // If the service was already available, this method invokes the callback immediately. // // A generic version of this method is provided for convience, and calls the non-generic // method with appropriate casts. // </summary> // <param name="serviceType"></param> // <param name="callback"></param> public override void Subscribe(Type serviceType, SubscribeServiceCallback callback) { if (serviceType == null) { throw FxTrace.Exception.ArgumentNull("serviceType"); } if (callback == null) { throw FxTrace.Exception.ArgumentNull("callback"); } object service = GetService(serviceType); if (service != null) { // If the service is already available, callback immediately callback(serviceType, service); } else { // Otherwise, store this for later if (_subscriptions == null) { _subscriptions = new Dictionary<Type, SubscribeServiceCallback>(); } SubscribeServiceCallback existing = null; _subscriptions.TryGetValue(serviceType, out existing); existing = (SubscribeServiceCallback)Delegate.Combine(existing, callback); _subscriptions[serviceType] = existing; } } // <summary> // Calls back on the provided callback when someone has published the requested service. // If the service was already available, this method invokes the callback immediately. // // A generic version of this method is provided for convience, and calls the non-generic // method with appropriate casts. // </summary> // <param name="serviceType"></param> // <param name="callback"></param> public override void Publish(Type serviceType, PublishServiceCallback callback) { if (serviceType == null) { throw FxTrace.Exception.ArgumentNull("serviceType"); } if (callback == null) { throw FxTrace.Exception.ArgumentNull("callback"); } Publish(serviceType, (object)callback); } // <summary> // If you already have an instance to a service, you can publish it here. // </summary> // <param name="serviceType"></param> // <param name="serviceInstance"></param> public override void Publish(Type serviceType, object serviceInstance) { if (serviceType == null) { throw FxTrace.Exception.ArgumentNull("serviceType"); } if (serviceInstance == null) { throw FxTrace.Exception.ArgumentNull("serviceInstance"); } if (!(serviceInstance is PublishServiceCallback) && !serviceType.IsInstanceOfType(serviceInstance)) { throw FxTrace.Exception.AsError(new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.Error_IncorrectServiceType, typeof(ServiceManager).Name, serviceType.FullName, serviceInstance.GetType().FullName))); } if (_services == null) { _services = new Dictionary<Type, object>(); } try { _services.Add(serviceType, serviceInstance); } catch (ArgumentException e) { throw FxTrace.Exception.AsError(new ArgumentException(string.Format( CultureInfo.CurrentCulture, Resources.Error_DuplicateService, serviceType.FullName), e)); } // Now see if there were any subscriptions that required this service SubscribeServiceCallback subscribeCallback; if (_subscriptions != null && _subscriptions.TryGetValue(serviceType, out subscribeCallback)) { subscribeCallback(serviceType, GetService(serviceType)); _subscriptions.Remove(serviceType); } } // <summary> // Removes a subscription. // </summary> public override void Unsubscribe(Type serviceType, SubscribeServiceCallback callback) { if (serviceType == null) { throw FxTrace.Exception.ArgumentNull("serviceType"); } if (callback == null) { throw FxTrace.Exception.ArgumentNull("callback"); } if (_subscriptions != null) { SubscribeServiceCallback existing; if (_subscriptions.TryGetValue(serviceType, out existing)) { existing = (SubscribeServiceCallback)RemoveCallback(existing, callback); if (existing == null) { _subscriptions.Remove(serviceType); } else { _subscriptions[serviceType] = existing; } } } } // <summary> // We implement IDisposable so that the editing context can destroy us when it // shuts down. // </summary> void IDisposable.Dispose() { if (_services != null) { Dictionary<Type, object> services = _services; try { foreach (object value in services.Values) { IDisposable d = value as IDisposable; if (d != null) { d.Dispose(); } } } finally { _services = null; } } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime.Messaging; using Orleans.Runtime.Placement; using Orleans.Runtime.Configuration; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime { internal class Dispatcher { internal OrleansTaskScheduler Scheduler { get; private set; } internal ISiloMessageCenter Transport { get; private set; } private readonly Catalog catalog; private readonly Logger logger; private readonly ClusterConfiguration config; private readonly double rejectionInjectionRate; private readonly bool errorInjection; private readonly double errorInjectionRate; private readonly SafeRandom random; public Dispatcher( OrleansTaskScheduler scheduler, ISiloMessageCenter transport, Catalog catalog, ClusterConfiguration config) { Scheduler = scheduler; this.catalog = catalog; Transport = transport; this.config = config; logger = LogManager.GetLogger("Dispatcher", LoggerType.Runtime); rejectionInjectionRate = config.Globals.RejectionInjectionRate; double messageLossInjectionRate = config.Globals.MessageLossInjectionRate; errorInjection = rejectionInjectionRate > 0.0d || messageLossInjectionRate > 0.0d; errorInjectionRate = rejectionInjectionRate + messageLossInjectionRate; random = new SafeRandom(); } #region Receive path /// <summary> /// Receive a new message: /// - validate order constraints, queue (or possibly redirect) if out of order /// - validate transactions constraints /// - invoke handler if ready, otherwise enqueue for later invocation /// </summary> /// <param name="message"></param> public void ReceiveMessage(Message message) { MessagingProcessingStatisticsGroup.OnDispatcherMessageReceive(message); // Don't process messages that have already timed out if (message.IsExpired) { logger.Warn(ErrorCode.Dispatcher_DroppingExpiredMessage, "Dropping an expired message: {0}", message); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Expired"); message.DropExpiredMessage(MessagingStatisticsGroup.Phase.Dispatch); return; } // check if its targeted at a new activation if (message.TargetGrain.IsSystemTarget) { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "ReceiveMessage on system target."); throw new InvalidOperationException("Dispatcher was called ReceiveMessage on system target for " + message); } if (errorInjection && ShouldInjectError(message)) { if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_InjectingRejection, "Injecting a rejection"); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "ErrorInjection"); RejectMessage(message, Message.RejectionTypes.Unrecoverable, null, "Injected rejection"); return; } try { Task ignore; ActivationData target = catalog.GetOrCreateActivation( message.TargetAddress, message.IsNewPlacement, message.NewGrainType, String.IsNullOrEmpty(message.GenericGrainType) ? null : message.GenericGrainType, message.RequestContextData, out ignore); if (ignore != null) { ignore.Ignore(); } if (message.Direction == Message.Directions.Response) { ReceiveResponse(message, target); } else // Request or OneWay { if (target.State == ActivationState.Valid) { catalog.ActivationCollector.TryRescheduleCollection(target); } // Silo is always capable to accept a new request. It's up to the activation to handle its internal state. // If activation is shutting down, it will queue and later forward this request. ReceiveRequest(message, target); } } catch (Exception ex) { try { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Non-existent activation"); var nea = ex as Catalog.NonExistentActivationException; if (nea == null) { var str = String.Format("Error creating activation for {0}. Message {1}", message.NewGrainType, message); logger.Error(ErrorCode.Dispatcher_ErrorCreatingActivation, str, ex); throw new OrleansException(str, ex); } if (nea.IsStatelessWorker) { if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_Intermediate_GetOrCreateActivation, String.Format("Intermediate StatelessWorker NonExistentActivation for message {0}", message), ex); } else { logger.Info(ErrorCode.Dispatcher_Intermediate_GetOrCreateActivation, String.Format("Intermediate NonExistentActivation for message {0}", message), ex); } ActivationAddress nonExistentActivation = nea.NonExistentActivation; if (message.Direction != Message.Directions.Response) { // Un-register the target activation so we don't keep getting spurious messages. // The time delay (one minute, as of this writing) is to handle the unlikely but possible race where // this request snuck ahead of another request, with new placement requested, for the same activation. // If the activation registration request from the new placement somehow sneaks ahead of this un-registration, // we want to make sure that we don't un-register the activation we just created. // We would add a counter here, except that there's already a counter for this in the Catalog. // Note that this has to run in a non-null scheduler context, so we always queue it to the catalog's context if (config.Globals.DirectoryLazyDeregistrationDelay > TimeSpan.Zero) { Scheduler.QueueWorkItem(new ClosureWorkItem( // don't use message.TargetAddress, cause it may have been removed from the headers by this time! async () => { try { await Silo.CurrentSilo.LocalGrainDirectory.UnregisterConditionallyAsync( nonExistentActivation); } catch(Exception exc) { logger.Warn(ErrorCode.Dispatcher_FailedToUnregisterNonExistingAct, String.Format("Failed to un-register NonExistentActivation {0}", nonExistentActivation), exc); } }, () => "LocalGrainDirectory.UnregisterConditionallyAsync"), catalog.SchedulingContext); } ProcessRequestToInvalidActivation(message, nonExistentActivation, null, "Non-existent activation"); } else { logger.Warn(ErrorCode.Dispatcher_NoTargetActivation, "No target activation {0} for response message: {1}", nonExistentActivation, message); Silo.CurrentSilo.LocalGrainDirectory.InvalidateCacheEntry(nonExistentActivation); } } catch (Exception exc) { // Unable to create activation for this request - reject message RejectMessage(message, Message.RejectionTypes.Transient, exc); } } } public void RejectMessage( Message message, Message.RejectionTypes rejectType, Exception exc, string rejectInfo = null) { if (message.Direction == Message.Directions.Request) { var str = String.Format("{0} {1}", rejectInfo ?? "", exc == null ? "" : exc.ToString()); MessagingStatisticsGroup.OnRejectedMessage(message); Message rejection = message.CreateRejectionResponse(rejectType, str, exc as OrleansException); SendRejectionMessage(rejection); } else { logger.Warn(ErrorCode.Messaging_Dispatcher_DiscardRejection, "Discarding {0} rejection for message {1}. Exc = {2}", Enum.GetName(typeof(Message.Directions), message.Direction), message, exc == null ? "" : exc.Message); } } internal void SendRejectionMessage(Message rejection) { if (rejection.Result == Message.ResponseTypes.Rejection) { Transport.SendMessage(rejection); rejection.ReleaseBodyAndHeaderBuffers(); } else { throw new InvalidOperationException( "Attempt to invoke Dispatcher.SendRejectionMessage() for a message that isn't a rejection."); } } private void ReceiveResponse(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.State == ActivationState.Invalid) { logger.Warn(ErrorCode.Dispatcher_Receive_InvalidActivation, "Response received for invalid activation {0}", message); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Ivalid"); return; } MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message); if (Transport.TryDeliverToProxy(message)) return; RuntimeClient.Current.ReceiveResponse(message); } } /// <summary> /// Check if we can locally accept this message. /// Redirects if it can't be accepted. /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> private void ReceiveRequest(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.State == ActivationState.Invalid) { ProcessRequestToInvalidActivation( message, targetActivation.Address, targetActivation.ForwardingAddress, "ReceiveRequest"); } else if (!ActivationMayAcceptRequest(targetActivation, message)) { // Check for deadlock before Enqueueing. if (config.Globals.PerformDeadlockDetection && !message.TargetGrain.IsSystemTarget) { try { CheckDeadlock(message); } catch (DeadlockException exc) { // Record that this message is no longer flowing through the system MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Deadlock"); logger.Warn(ErrorCode.Dispatcher_DetectedDeadlock, "Detected Application Deadlock: {0}", exc.Message); // We want to send DeadlockException back as an application exception, rather than as a system rejection. SendResponse(message, Response.ExceptionResponse(exc)); return; } } EnqueueRequest(message, targetActivation); } else { HandleIncomingRequest(message, targetActivation); } } } /// <summary> /// Determine if the activation is able to currently accept the given message /// - always accept responses /// For other messages, require that: /// - activation is properly initialized /// - the message would not cause a reentrancy conflict /// </summary> /// <param name="targetActivation"></param> /// <param name="incoming"></param> /// <returns></returns> private bool ActivationMayAcceptRequest(ActivationData targetActivation, Message incoming) { if (!targetActivation.State.Equals(ActivationState.Valid)) return false; if (!targetActivation.IsCurrentlyExecuting) return true; return CanInterleave(targetActivation, incoming); } /// <summary> /// Whether an incoming message can interleave /// </summary> /// <param name="targetActivation"></param> /// <param name="incoming"></param> /// <returns></returns> public bool CanInterleave(ActivationData targetActivation, Message incoming) { bool canInterleave = catalog.IsReentrantGrain(targetActivation.ActivationId) || incoming.IsAlwaysInterleave || targetActivation.Running == null || (targetActivation.Running.IsReadOnly && incoming.IsReadOnly); return canInterleave; } /// <summary> /// Check if the current message will cause deadlock. /// Throw DeadlockException if yes. /// </summary> /// <param name="message">Message to analyze</param> private void CheckDeadlock(Message message) { var requestContext = message.RequestContextData; object obj; if (requestContext == null || !requestContext.TryGetValue(RequestContext.CALL_CHAIN_REQUEST_CONTEXT_HEADER, out obj) || obj == null) return; // first call in a chain var prevChain = ((IList)obj); ActivationId nextActivationId = message.TargetActivation; // check if the target activation already appears in the call chain. foreach (object invocationObj in prevChain) { var prevId = ((RequestInvocationHistory)invocationObj).ActivationId; if (!prevId.Equals(nextActivationId) || catalog.IsReentrantGrain(nextActivationId)) continue; var newChain = new List<RequestInvocationHistory>(); newChain.AddRange(prevChain.Cast<RequestInvocationHistory>()); newChain.Add(new RequestInvocationHistory(message)); throw new DeadlockException(newChain); } } /// <summary> /// Handle an incoming message and queue/invoke appropriate handler /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> public void HandleIncomingRequest(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.State == ActivationState.Invalid) { ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "HandleIncomingRequest"); return; } // Now we can actually scheduler processing of this request targetActivation.RecordRunning(message); var context = new SchedulingContext(targetActivation); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message); Scheduler.QueueWorkItem(new InvokeWorkItem(targetActivation, message, context), context); } } /// <summary> /// Enqueue message for local handling after transaction completes /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> private void EnqueueRequest(Message message, ActivationData targetActivation) { var overloadException = targetActivation.CheckOverloaded(logger); if (overloadException != null) { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Overload2"); RejectMessage(message, Message.RejectionTypes.Overloaded, overloadException, "Target activation is overloaded " + targetActivation); return; } bool enqueuedOk = targetActivation.EnqueueMessage(message); if (!enqueuedOk) { ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "EnqueueRequest"); } // Dont count this as end of processing. The message will come back after queueing via HandleIncomingRequest. #if DEBUG // This is a hot code path, so using #if to remove diags from Release version // Note: Caller already holds lock on activation if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_EnqueueMessage, "EnqueueMessage for {0}: targetActivation={1}", message.TargetActivation, targetActivation.DumpStatus()); #endif } internal void ProcessRequestToInvalidActivation( Message message, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { // Just use this opportunity to invalidate local Cache Entry as well. if (oldAddress != null) { Silo.CurrentSilo.LocalGrainDirectory.InvalidateCacheEntry(oldAddress); } // IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already. Scheduler.QueueWorkItem(new ClosureWorkItem( () => TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc)), catalog.SchedulingContext); } internal void ProcessRequestsToInvalidActivation( List<Message> messages, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { // Just use this opportunity to invalidate local Cache Entry as well. if (oldAddress != null) { Silo.CurrentSilo.LocalGrainDirectory.InvalidateCacheEntry(oldAddress); } logger.Info(ErrorCode.Messaging_Dispatcher_ForwardingRequests, String.Format("Forwarding {0} requests to old address {1} after {2}.", messages.Count, oldAddress, failedOperation)); // IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already. Scheduler.QueueWorkItem(new ClosureWorkItem( () => { foreach (var message in messages) { TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc); } } ), catalog.SchedulingContext); } internal void TryForwardRequest(Message message, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { bool forwardingSucceded = true; try { logger.Info(ErrorCode.Messaging_Dispatcher_TryForward, String.Format("Trying to forward after {0}, ForwardCount = {1}. Message {2}.", failedOperation, message.ForwardCount, message)); MessagingProcessingStatisticsGroup.OnDispatcherMessageReRouted(message); if (oldAddress != null) { message.AddToCacheInvalidationHeader(oldAddress); } forwardingSucceded = InsideRuntimeClient.Current.TryForwardMessage(message, forwardingAddress); } catch (Exception exc2) { forwardingSucceded = false; exc = exc2; } finally { if (!forwardingSucceded) { var str = String.Format("Forwarding failed: tried to forward message {0} for {1} times after {2} to invalid activation. Rejecting now.", message, message.ForwardCount, failedOperation); logger.Warn(ErrorCode.Messaging_Dispatcher_TryForwardFailed, str, exc); RejectMessage(message, Message.RejectionTypes.Transient, exc, str); } } } #endregion #region Send path /// <summary> /// Send an outgoing message /// - may buffer for transaction completion / commit if it ends a transaction /// - choose target placement address, maintaining send order /// - add ordering info and maintain send order /// /// </summary> /// <param name="message"></param> /// <param name="sendingActivation"></param> public async Task AsyncSendMessage(Message message, ActivationData sendingActivation = null) { try { await AddressMessage(message); TransportMessage(message); } catch (Exception ex) { if (ShouldLogError(ex)) { logger.Error(ErrorCode.Dispatcher_SelectTarget_Failed, String.Format("SelectTarget failed with {0}", ex.Message), ex); } MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "SelectTarget failed"); RejectMessage(message, Message.RejectionTypes.Unrecoverable, ex); } } private bool ShouldLogError(Exception ex) { return !(ex.GetBaseException() is KeyNotFoundException) && !(ex.GetBaseException() is ClientNotAvailableException); } // this is a compatibility method for portions of the code base that don't use // async/await yet, which is almost everything. there's no liability to discarding the // Task returned by AsyncSendMessage() internal void SendMessage(Message message, ActivationData sendingActivation = null) { AsyncSendMessage(message, sendingActivation).Ignore(); } /// <summary> /// Resolve target address for a message /// - use transaction info /// - check ordering info in message and sending activation /// - use sender's placement strategy /// </summary> /// <param name="message"></param> /// <returns>Resolve when message is addressed (modifies message fields)</returns> private async Task AddressMessage(Message message) { var targetAddress = message.TargetAddress; if (targetAddress.IsComplete) return; // placement strategy is determined by searching for a specification. first, we check for a strategy associated with the grain reference, // second, we check for a strategy associated with the target's interface. third, we check for a strategy associated with the activation sending the // message. var strategy = targetAddress.Grain.IsGrain ? catalog.GetGrainPlacementStrategy(targetAddress.Grain) : null; var placementResult = await PlacementDirectorsManager.Instance.SelectOrAddActivation( message.SendingAddress, message.TargetGrain, InsideRuntimeClient.Current.Catalog, strategy); if (placementResult.IsNewPlacement && targetAddress.Grain.IsClient) { logger.Error(ErrorCode.Dispatcher_AddressMsg_UnregisteredClient, String.Format("AddressMessage could not find target for client pseudo-grain {0}", message)); throw new KeyNotFoundException(String.Format("Attempting to send a message {0} to an unregistered client pseudo-grain {1}", message, targetAddress.Grain)); } message.SetTargetPlacement(placementResult); if (placementResult.IsNewPlacement) { CounterStatistic.FindOrCreate(StatisticNames.DISPATCHER_NEW_PLACEMENT).Increment(); } if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_AddressMsg_SelectTarget, "AddressMessage Placement SelectTarget {0}", message); } internal void SendResponse(Message request, Response response) { // create the response var message = request.CreateResponseMessage(); message.BodyObject = response; if (message.TargetGrain.IsSystemTarget) { SendSystemTargetMessage(message); } else { TransportMessage(message); } } internal void SendSystemTargetMessage(Message message) { message.Category = message.TargetGrain.Equals(Constants.MembershipOracleId) ? Message.Categories.Ping : Message.Categories.System; if (message.TargetSilo == null) { message.TargetSilo = Transport.MyAddress; } if (message.TargetActivation == null) { message.TargetActivation = ActivationId.GetSystemActivation(message.TargetGrain, message.TargetSilo); } TransportMessage(message); } /// <summary> /// Directly send a message to the transport without processing /// </summary> /// <param name="message"></param> public void TransportMessage(Message message) { if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_Send_AddressedMessage, "Addressed message {0}", message); Transport.SendMessage(message); } #endregion #region Execution /// <summary> /// Invoked when an activation has finished a transaction and may be ready for additional transactions /// </summary> /// <param name="activation">The activation that has just completed processing this message</param> /// <param name="message">The message that has just completed processing. /// This will be <c>null</c> for the case of completion of Activate/Deactivate calls.</param> internal void OnActivationCompletedRequest(ActivationData activation, Message message) { lock (activation) { #if DEBUG // This is a hot code path, so using #if to remove diags from Release version if (logger.IsVerbose2) { logger.Verbose2(ErrorCode.Dispatcher_OnActivationCompletedRequest_Waiting, "OnActivationCompletedRequest {0}: Activation={1}", activation.ActivationId, activation.DumpStatus()); } #endif activation.ResetRunning(message); // ensure inactive callbacks get run even with transactions disabled if (!activation.IsCurrentlyExecuting) activation.RunOnInactive(); // Run message pump to see if there is a new request arrived to be processed RunMessagePump(activation); } } internal void RunMessagePump(ActivationData activation) { // Note: this method must be called while holding lock (activation) #if DEBUG // This is a hot code path, so using #if to remove diags from Release version // Note: Caller already holds lock on activation if (logger.IsVerbose2) { logger.Verbose2(ErrorCode.Dispatcher_ActivationEndedTurn_Waiting, "RunMessagePump {0}: Activation={1}", activation.ActivationId, activation.DumpStatus()); } #endif // don't run any messages if activation is not ready or deactivating if (!activation.State.Equals(ActivationState.Valid)) return; bool runLoop; do { runLoop = false; var nextMessage = activation.PeekNextWaitingMessage(); if (nextMessage == null) continue; if (!ActivationMayAcceptRequest(activation, nextMessage)) continue; activation.DequeueNextWaitingMessage(); // we might be over-writing an already running read only request. HandleIncomingRequest(nextMessage, activation); runLoop = true; } while (runLoop); } private bool ShouldInjectError(Message message) { if (!errorInjection || message.Direction != Message.Directions.Request) return false; double r = random.NextDouble() * 100; if (!(r < errorInjectionRate)) return false; if (r < rejectionInjectionRate) { return true; } if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_InjectingMessageLoss, "Injecting a message loss"); // else do nothing and intentionally drop message on the floor to inject a message loss return true; } #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 Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryOrTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckByteOrTest(bool useInterpreter) { byte[] array = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyByteOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckSByteOrTest(bool useInterpreter) { sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifySByteOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUShortOrTest(bool useInterpreter) { ushort[] array = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUShortOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckShortOrTest(bool useInterpreter) { short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyShortOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUIntOrTest(bool useInterpreter) { uint[] array = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUIntOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckIntOrTest(bool useInterpreter) { int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyIntOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckULongOrTest(bool useInterpreter) { ulong[] array = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyULongOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLongOrTest(bool useInterpreter) { long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyLongOr(array[i], array[j], useInterpreter); } } } #endregion #region Test verifiers private static void VerifyByteOr(byte a, byte b, bool useInterpreter) { Expression<Func<byte>> e = Expression.Lambda<Func<byte>>( Expression.Or( Expression.Constant(a, typeof(byte)), Expression.Constant(b, typeof(byte))), Enumerable.Empty<ParameterExpression>()); Func<byte> f = e.Compile(useInterpreter); Assert.Equal((byte)(a | b), f()); } private static void VerifySByteOr(sbyte a, sbyte b, bool useInterpreter) { Expression<Func<sbyte>> e = Expression.Lambda<Func<sbyte>>( Expression.Or( Expression.Constant(a, typeof(sbyte)), Expression.Constant(b, typeof(sbyte))), Enumerable.Empty<ParameterExpression>()); Func<sbyte> f = e.Compile(useInterpreter); Assert.Equal((sbyte)(a | b), f()); } private static void VerifyUShortOr(ushort a, ushort b, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.Or( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); Assert.Equal((ushort)(a | b), f()); } private static void VerifyShortOr(short a, short b, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.Or( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); Assert.Equal((short)(a | b), f()); } private static void VerifyUIntOr(uint a, uint b, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.Or( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); Assert.Equal(a | b, f()); } private static void VerifyIntOr(int a, int b, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Or( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(a | b, f()); } private static void VerifyULongOr(ulong a, ulong b, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.Or( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); Assert.Equal(a | b, f()); } private static void VerifyLongOr(long a, long b, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.Or( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); Assert.Equal(a | b, f()); } #endregion [Fact] public static void CannotReduce() { Expression exp = Expression.Or(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void ThrowsOnLeftNull() { Assert.Throws<ArgumentNullException>("left", () => Expression.Or(null, Expression.Constant(""))); } [Fact] public static void ThrowsOnRightNull() { Assert.Throws<ArgumentNullException>("right", () => Expression.Or(Expression.Constant(""), null)); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Fact] public static void ThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("left", () => Expression.Or(value, Expression.Constant(1))); } [Fact] public static void ThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("right", () => Expression.Or(Expression.Constant(1), value)); } [Fact] public static void ToStringTest() { BinaryExpression e1 = Expression.Or(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a | b)", e1.ToString()); BinaryExpression e2 = Expression.Or(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(bool), "b")); Assert.Equal("(a Or b)", e2.ToString()); BinaryExpression e3 = Expression.Or(Expression.Parameter(typeof(bool?), "a"), Expression.Parameter(typeof(bool?), "b")); Assert.Equal("(a Or b)", e3.ToString()); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using MixedRealityToolkit.Common; using UnityEngine; namespace MixedRealityToolkit.Utilities { // The easiest way to use this script is to drop in the HeadsUpDirectionIndicator prefab // from the Mixed Reality Toolkit. If you're having issues with the prefab or can't find it, // you can simply create an empty GameObject and attach this script. You'll need to // create your own pointer object which can by any 3D game object. You'll need to adjust // the depth, margin and pivot variables to affect the right appearance. After that you // simply need to specify the "targetObject" and then you should be set. // // This script assumes your point object "aims" along its local up axis and orients the // object according to that assumption. public class HeadsUpDirectionIndicator : MonoBehaviour { // Use as a named indexer for Unity's frustum planes. The order follows that laid // out in the API documentation. DO NOT CHANGE ORDER unless a corresponding change // has been made in the Unity API. private enum FrustumPlanes { Left = 0, Right, Bottom, Top, Near, Far } [Tooltip("The object the direction indicator will point to.")] public GameObject TargetObject; [Tooltip("The camera depth at which the indicator rests.")] public float Depth; [Tooltip("The point around which the indicator pivots. Should be placed at the model's 'tip'.")] public Vector3 Pivot; [Tooltip("The object used to 'point' at the target.")] public GameObject PointerPrefab; [Tooltip("Determines what percentage of the visible field should be margin.")] [Range(0.0f, 1.0f)] public float IndicatorMarginPercent; [Tooltip("Debug draw the planes used to calculate the pointer lock location.")] public bool DebugDrawPointerOrientationPlanes; private GameObject pointer; private static int frustumLastUpdated = -1; private static Plane[] frustumPlanes; private static Vector3 cameraForward; private static Vector3 cameraPosition; private static Vector3 cameraRight; private static Vector3 cameraUp; private Plane[] indicatorVolume; private void Start() { Depth = Mathf.Clamp(Depth, CameraCache.Main.nearClipPlane, CameraCache.Main.farClipPlane); if (PointerPrefab == null) { this.gameObject.SetActive(false); return; } pointer = GameObject.Instantiate(PointerPrefab); // We create the effect of pivoting rotations by parenting the pointer and // offsetting its position. pointer.transform.parent = transform; pointer.transform.position = -Pivot; // Allocate the space to hold the indicator volume planes. Later portions of the algorithm take for // granted that these objects have been initialized. indicatorVolume = new Plane[] { new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane() }; } // Update the direction indicator's position and orientation every frame. private void Update() { if (!HasObjectsToTrack()) { return; } int currentFrameCount = Time.frameCount; if (currentFrameCount != frustumLastUpdated) { // Collect the updated camera information for the current frame CacheCameraTransform(CameraCache.Main); frustumLastUpdated = currentFrameCount; } UpdatePointerTransform(CameraCache.Main, indicatorVolume, TargetObject.transform.position); } private bool HasObjectsToTrack() { return TargetObject != null && pointer != null; } // Cache data from the camera state that are costly to retrieve. private void CacheCameraTransform(Camera camera) { cameraForward = camera.transform.forward; cameraPosition = camera.transform.position; cameraRight = camera.transform.right; cameraUp = camera.transform.up; frustumPlanes = GeometryUtility.CalculateFrustumPlanes(camera); } // Assuming the target object is outside the view which of the four "wall" planes should // the pointer snap to. private FrustumPlanes GetExitPlane(Vector3 targetPosition, Camera camera) { // To do this we first create two planes that diagonally bisect the frustum // These panes create four quadrants. We then infer the exit plane based on // which quadrant the target position is in. // Calculate a set of vectors that can be used to build the frustum corners in world // space. float aspect = camera.aspect; float fovy = 0.5f * camera.fieldOfView; float near = camera.nearClipPlane; float far = camera.farClipPlane; float tanFovy = Mathf.Tan(Mathf.Deg2Rad * fovy); float tanFovx = aspect * tanFovy; // Calculate the edges of the frustum as world space offsets from the middle of the // frustum in world space. Vector3 nearTop = near * tanFovy * cameraUp; Vector3 nearRight = near * tanFovx * cameraRight; Vector3 nearBottom = -nearTop; Vector3 nearLeft = -nearRight; Vector3 farTop = far * tanFovy * cameraUp; Vector3 farRight = far * tanFovx * cameraRight; Vector3 farLeft = -farRight; // Calculate the center point of the near plane and the far plane as offsets from the // camera in world space. Vector3 nearBase = near * cameraForward; Vector3 farBase = far * cameraForward; // Calculate the frustum corners needed to create 'd' Vector3 nearUpperLeft = nearBase + nearTop + nearLeft; Vector3 nearLowerRight = nearBase + nearBottom + nearRight; Vector3 farUpperLeft = farBase + farTop + farLeft; Plane d = new Plane(nearUpperLeft, nearLowerRight, farUpperLeft); // Calculate the frustum corners needed to create 'e' Vector3 nearUpperRight = nearBase + nearTop + nearRight; Vector3 nearLowerLeft = nearBase + nearBottom + nearLeft; Vector3 farUpperRight = farBase + farTop + farRight; Plane e = new Plane(nearUpperRight, nearLowerLeft, farUpperRight); #if UNITY_EDITOR if (DebugDrawPointerOrientationPlanes) { // Debug draw a triangle coplanar with 'd' Debug.DrawLine(nearUpperLeft, nearLowerRight); Debug.DrawLine(nearLowerRight, farUpperLeft); Debug.DrawLine(farUpperLeft, nearUpperLeft); // Debug draw a triangle coplanar with 'e' Debug.DrawLine(nearUpperRight, nearLowerLeft); Debug.DrawLine(nearLowerLeft, farUpperRight); Debug.DrawLine(farUpperRight, nearUpperRight); } #endif // We're not actually interested in the "distance" to the planes. But the sign // of the distance tells us which quadrant the target position is in. float dDistance = d.GetDistanceToPoint(targetPosition); float eDistance = e.GetDistanceToPoint(targetPosition); // d e // +\- +/- // \ -d +e / // \ / // \ / // \ / // \ / // +d +e \/ // /\ -d -e // / \ // / \ // / \ // / \ // / +d -e \ // +/- +\- if (dDistance > 0.0f) { if (eDistance > 0.0f) { return FrustumPlanes.Left; } else { return FrustumPlanes.Bottom; } } else { if (eDistance > 0.0f) { return FrustumPlanes.Top; } else { return FrustumPlanes.Right; } } } // given a frustum wall we wish to snap the pointer to, this function returns a ray // along which the pointer should be placed to appear at the appropriate point along // the edge of the indicator field. private bool TryGetIndicatorPosition(Vector3 targetPosition, Plane frustumWall, out Ray r) { // Think of the pointer as pointing the shortest rotation a user must make to see a // target. The shortest rotation can be obtained by finding the great circle defined // be the target, the camera position and the center position of the view. The tangent // vector of the great circle points the direction of the shortest rotation. This // great circle and thus any of it's tangent vectors are coplanar with the plane // defined by these same three points. Vector3 cameraToTarget = targetPosition - cameraPosition; Vector3 normal = Vector3.Cross(cameraToTarget.normalized, cameraForward); // In the case that the three points are colinear we cannot form a plane but we'll // assume the target is directly behind us and we'll use a pre-chosen plane. if (normal == Vector3.zero) { normal = -Vector3.right; } Plane q = new Plane(normal, targetPosition); return TryIntersectPlanes(frustumWall, q, out r); } // Obtain the line of intersection of two planes. This is based on a method // described in the GPU Gems series. private bool TryIntersectPlanes(Plane p, Plane q, out Ray intersection) { Vector3 rNormal = Vector3.Cross(p.normal, q.normal); float det = rNormal.sqrMagnitude; if (det != 0.0f) { Vector3 rPoint = ((Vector3.Cross(rNormal, q.normal) * p.distance) + (Vector3.Cross(p.normal, rNormal) * q.distance)) / det; intersection = new Ray(rPoint, rNormal); return true; } else { intersection = new Ray(); return false; } } // Modify the pointer location and orientation to point along the shortest rotation, // toward tergetPosition, keeping the pointer confined inside the frustum defined by // planes. private void UpdatePointerTransform(Camera camera, Plane[] planes, Vector3 targetPosition) { // Use the camera information to create the new bounding volume UpdateIndicatorVolume(camera); // Start by assuming the pointer should be placed at the target position. Vector3 indicatorPosition = cameraPosition + Depth * (targetPosition - cameraPosition).normalized; // Test the target position with the frustum planes except the "far" plane since // far away objects should be considered in view. bool pointNotInsideIndicatorField = false; for (int i = 0; i < 5; ++i) { float dot = Vector3.Dot(planes[i].normal, (targetPosition - cameraPosition).normalized); if (dot <= 0.0f) { pointNotInsideIndicatorField = true; break; } } // if the target object appears outside the indicator area... if (pointNotInsideIndicatorField) { // ...then we need to do some geometry calculations to lock it to the edge. // used to determine which edge of the screen the indicator vector // would exit through. FrustumPlanes exitPlane = GetExitPlane(targetPosition, camera); Ray r; if (TryGetIndicatorPosition(targetPosition, planes[(int)exitPlane], out r)) { indicatorPosition = cameraPosition + Depth * r.direction.normalized; } } this.transform.position = indicatorPosition; // The pointer's direction should always appear pointing away from the user's center // of view. Thus we find the center point of the user's view in world space. // But the pointer should also appear perpendicular to the viewer so we find the // center position of the view that is on the same plane as the pointer position. // We do this by projecting the vector from the pointer to the camera onto the // the camera's forward vector. Vector3 indicatorFieldOffset = indicatorPosition - cameraPosition; indicatorFieldOffset = Vector3.Dot(indicatorFieldOffset, cameraForward) * cameraForward; Vector3 indicatorFieldCenter = cameraPosition + indicatorFieldOffset; Vector3 pointerDirection = (indicatorPosition - indicatorFieldCenter).normalized; // Align this object's up vector with the pointerDirection this.transform.rotation = Quaternion.LookRotation(cameraForward, pointerDirection); } // Here we adjust the Camera's frustum planes to place the cursor in a smaller // volume, thus creating the effect of a "margin" private void UpdateIndicatorVolume(Camera camera) { // The top, bottom and side frustum planes are used to restrict the movement // of the pointer. These reside at indices 0-3; for (int i = 0; i < 4; ++i) { // We can make the frustum smaller by rotating the walls "in" toward the // camera's forward vector. // First find the angle between the Camera's forward and the plane's normal float angle = Mathf.Acos(Vector3.Dot(frustumPlanes[i].normal.normalized, cameraForward)); // Then we calculate how much we should rotate the plane in based on the // user's setting. 90 degrees is our maximum as at that point we no longer // have a valid frustum. float angleStep = IndicatorMarginPercent * (0.5f * Mathf.PI - angle); // Because the frustum plane normals face in we must actually rotate away from the forward vector // to narrow the frustum. Vector3 normal = Vector3.RotateTowards(frustumPlanes[i].normal, cameraForward, -angleStep, 0.0f); indicatorVolume[i].normal = normal.normalized; indicatorVolume[i].distance = frustumPlanes[i].distance; } indicatorVolume[4] = frustumPlanes[4]; indicatorVolume[5] = frustumPlanes[5]; } } }
// 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.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Threading; namespace System.Globalization { // Gregorian Calendars use Era Info [Serializable] internal class EraInfo { internal int era; // The value of the era. internal long ticks; // The time in ticks when the era starts internal int yearOffset; // The offset to Gregorian year when the era starts. // Gregorian Year = Era Year + yearOffset // Era Year = Gregorian Year - yearOffset internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may // be affected by the DateTime.MinValue; internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1) [OptionalField(VersionAdded = 4)] internal String eraName; // The era name [OptionalField(VersionAdded = 4)] internal String abbrevEraName; // Abbreviated Era Name [OptionalField(VersionAdded = 4)] internal String englishEraName; // English era name internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; } internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear, String eraName, String abbrevEraName, String englishEraName) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; this.eraName = eraName; this.abbrevEraName = abbrevEraName; this.englishEraName = englishEraName; } } // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) [Serializable] internal class GregorianCalendarHelper { // 1 tick = 100ns = 10E-7 second // Number of ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal int MaxYear { get { return (m_maxYear); } } internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; [OptionalField(VersionAdded = 1)] internal int m_maxYear = 9999; [OptionalField(VersionAdded = 1)] internal int m_minYear; internal Calendar m_Cal; [OptionalField(VersionAdded = 1)] internal EraInfo[] m_EraInfo; [OptionalField(VersionAdded = 1)] internal int[] m_eras = null; // Construct an instance of gregorian calendar. internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo) { m_Cal = cal; m_EraInfo = eraInfo; m_maxYear = m_EraInfo[0].maxEraYear; m_minYear = m_EraInfo[0].minEraYear; ; } /*=================================GetGregorianYear========================== **Action: Get the Gregorian year value for the specified year in an era. **Returns: The Gregorian year value. **Arguments: ** year the year value in Japanese calendar ** era the Japanese emperor era value. **Exceptions: ** ArgumentOutOfRangeException if year value is invalid or era value is invalid. ============================================================================*/ internal int GetGregorianYear(int year, int era) { if (year < 0) { throw new ArgumentOutOfRangeException("year", SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, m_EraInfo[i].minEraYear, m_EraInfo[i].maxEraYear)); } return (m_EraInfo[i].yearOffset + year); } } throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } internal bool IsValidYear(int year, int era) { if (year < 0) { return false; } if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { return false; } return true; } } return false; } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) { CheckTicksRange(ticks); // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 int y400 = n / DaysPer400Years; // n = day number within 400-year period n -= y400 * DaysPer400Years; // y100 = number of whole 100-year periods within 400-year period int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if (y100 == 4) y100 = 3; // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period int y4 = n / DaysPer4Years; // n = day number within 4-year period n -= y4 * DaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) y1 = 3; // If year was requested, compute and return it if (part == DatePartYear) { return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1); } // n = day number within year n -= y1 * DaysPerYear; // If day-of-year was requested, return it if (part == DatePartDayOfYear) { return (n + 1); } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3)); int[] days = leapYear ? DaysToMonth366 : DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = n >> 5 + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it if (part == DatePartMonth) return (m); // Return 1-based day-of-month return (n - days[m - 1] + 1); } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal static long DateToTicks(int year, int month, int day) { return (GetAbsoluteDate(year, month, day) * TicksPerDay); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { //TimeSpan.TimeToTicks is a family access function which does no error checking, so //we need to put some error checking out here. if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( "millisecond", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)); } return (InternalGloablizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond); ; } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } internal void CheckTicksRange(long ticks) { if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks) { throw new ArgumentOutOfRangeException( "time", String.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime)); } Contract.EndContractBlock(); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( "months", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, 120000)); } Contract.EndContractBlock(); CheckTicksRange(time.Ticks); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + (time.Ticks % TicksPerDay); Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek GetDayOfWeek(DateTime time) { CheckTicksRange(time.Ticks); return ((DayOfWeek)((time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } // Returns the number of days in the month given by the year and // month arguments. // [Pure] public int GetDaysInMonth(int year, int month, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); return (days[month] - days[month - 1]); } // Returns the number of days in the year given by the year argument for the current era. // public int GetDaysInYear(int year, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365); } // Returns the era for the specified DateTime value. public int GetEra(DateTime time) { long ticks = time.Ticks; // The assumption here is that m_EraInfo is listed in reverse order. for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (m_EraInfo[i].era); } } throw new ArgumentOutOfRangeException("time", SR.ArgumentOutOfRange_Era); } public int[] Eras { get { if (m_eras == null) { m_eras = new int[m_EraInfo.Length]; for (int i = 0; i < m_EraInfo.Length; i++) { m_eras[i] = m_EraInfo[i].era; } } return ((int[])m_eras.Clone()); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public int GetMonthsInYear(int year, int era) { year = GetGregorianYear(year, era); return (12); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public int GetYear(DateTime time) { long ticks = time.Ticks; int year = GetDatePart(ticks, DatePartYear); for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(SR.Argument_NoEra); } // Returns the year that match the specified Gregorian year. The returned value is an // integer between 1 and 9999. // public int GetYear(int year, DateTime time) { long ticks = time.Ticks; for (int i = 0; i < m_EraInfo.Length; i++) { // while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era // and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause // using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset // which will end up with zero as calendar year. // We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989 if (ticks >= m_EraInfo[i].ticks && year > m_EraInfo[i].yearOffset) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(SR.Argument_NoEra); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public bool IsLeapDay(int year, int month, int day, int era) { // year/month/era checking is done in GetDaysInMonth() if (day < 1 || day > GetDaysInMonth(year, month, era)) { throw new ArgumentOutOfRangeException( "day", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, GetDaysInMonth(year, month, era))); } Contract.EndContractBlock(); if (!IsLeapYear(year, era)) { return (false); } if (month == 2 && day == 29) { return (true); } return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public int GetLeapMonth(int year, int era) { year = GetGregorianYear(year, era); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public bool IsLeapMonth(int year, int month, int era) { year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException( "month", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, 12)); } return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public bool IsLeapYear(int year, int era) { year = GetGregorianYear(year, era); return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { year = GetGregorianYear(year, era); long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond); CheckTicksRange(ticks); return (new DateTime(ticks)); } public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { CheckTicksRange(time.Ticks); // Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear() // can call GetYear() that exceeds the supported range of the Gregorian-based calendars. return (GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek)); } public int ToFourDigitYear(int year, int twoDigitYearMax) { if (year < 0) { throw new ArgumentOutOfRangeException("year", SR.ArgumentOutOfRange_NeedPosNum); } Contract.EndContractBlock(); if (year < 100) { int y = year % 100; return ((twoDigitYearMax / 100 - (y > twoDigitYearMax % 100 ? 1 : 0)) * 100 + y); } if (year < m_minYear || year > m_maxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, m_minYear, m_maxYear)); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } } }
using Xunit; namespace Jint.Tests.Ecma { public class Test_15_4_4_16 : EcmaTest { [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryMustExistAsAFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-0-1.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryLengthMustBe1() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-0-2.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToUndefinedThrowsATypeerror() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-1.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToTheMathObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-10.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToDateObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-11.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToRegexpObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-12.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToTheJsonObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-13.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToErrorObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-14.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToTheArgumentsObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-15.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToNullThrowsATypeerror() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-2.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToBooleanPrimitive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-3.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToBooleanObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-4.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToNumberPrimitive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-5.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToNumberObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-6.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToStringPrimitive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-7.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToStringObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-8.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToFunctionObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-1-9.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToArrayLikeObjectLengthIsAnOwnDataProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-1.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToArrayLikeObjectLengthIsAnInheritedAccessorProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-10.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToArrayLikeObjectLengthIsAnOwnAccessorPropertyWithoutAGetFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-11.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryLengthIsOwnAccessorPropertyWithoutAGetFunctionThatOverridesAnInheritedAccessorProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-12.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToTheArrayLikeObjectThatLengthIsInheritedAccessorPropertyWithoutAGetFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-13.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToTheArrayLikeObjectThatLengthPropertyDoesnTExist() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-14.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryLengthIsPropertyOfTheGlobalObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-15.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-17.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToStringObjectWhichImplementsItsOwnPropertyGetMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-18.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToFunctionObjectWhichImplementsItsOwnPropertyGetMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-19.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryLengthIsOwnDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-2.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToArrayLikeObjectLengthIsAnOwnDataPropertyThatOverridesAnInheritedDataProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-3.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryLengthIsOwnDataPropertyThatOverridesAnInheritedDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-4.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToArrayLikeObjectLengthIsAnOwnDataPropertyThatOverridesAnInheritedAccessorProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-5.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToArrayLikeObjectLengthIsAnInheritedDataProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-6.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToArrayLikeObjectLengthIsAnOwnAccessorProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-7.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToArrayLikeObjectLengthIsAnOwnAccessorPropertyThatOverridesAnInheritedDataProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-8.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAppliedToArrayLikeObjectLengthIsAnOwnAccessorPropertyThatOverridesAnInheritedAccessorProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-9.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsUndefined() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-1.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsANumberValueIsNan() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-10.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryLengthIsAStringContainingAPositiveNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-11.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryLengthIsAStringContainingANegativeNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-12.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryLengthIsAStringContainingADecimalNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-13.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryLengthIsAStringContainingInfinity() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-14.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryLengthIsAStringContainingAnExponentialNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-15.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryLengthIsAStringContainingAHexNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-16.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryLengthIsAStringContainingANumberWithLeadingZeros() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-17.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsAStringThatCanTConvertToANumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-18.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsAnObjectWhichHasAnOwnTostringMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-19.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryOnAnArrayLikeObjectIfLengthIs1LengthOverriddenToTrueTypeConversion() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-2.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsAnObjectWhichHasAnOwnValueofMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-20.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryLengthIsAnObjectThatHasAnOwnValueofMethodThatReturnsAnObjectAndTostringMethodThatReturnsAString() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-21.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThrowsTypeerrorExceptionWhenLengthIsAnObjectWithTostringAndValueofMethodsThatDonTReturnPrimitiveValues() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-22.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryUsesInheritedValueofMethodWhenLengthIsAnObjectWithAnOwnTostringAndInheritedValueofMethods() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-23.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsAPositiveNonIntegerEnsureTruncationOccursInTheProperDirection() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-24.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsANegativeNonIntegerEnsureTruncationOccursInTheProperDirection() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-25.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsBoundaryValue232() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-28.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsBoundaryValue2321() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-29.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsANumberValueIs0() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-3.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsANumberValueIs02() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-4.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsANumberValueIs03() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-5.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsANumberValueIsPositive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-6.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsANumberValueIsNegative() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-7.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsANumberValueIsInfinity() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-8.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryValueOfLengthIsANumberValueIsInfinity2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-9.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThrowsTypeerrorIfCallbackfnIsUndefined() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-4-1.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryTheExceptionIsNotThrownIfExceptionWasThrownByStep2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-4-10.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryTheExceptionIsNotThrownIfExceptionWasThrownByStep3() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-4-11.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallbackfnIsAFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-4-12.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallingWithNoCallbackfnIsTheSameAsPassingUndefinedForCallbackfn() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-4-15.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThrowsTypeerrorIfCallbackfnIsNull() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-4-3.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThrowsTypeerrorIfCallbackfnIsBoolean() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-4-4.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThrowsTypeerrorIfCallbackfnIsNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-4-5.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThrowsTypeerrorIfCallbackfnIsString() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-4-6.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThrowsTypeerrorIfCallbackfnIsObjectWithoutACallInternalMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-4-7.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEverySideEffectsProducedByStep2AreVisibleWhenAnExceptionOccurs() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-4-8.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEverySideEffectsProducedByStep3AreVisibleWhenAnExceptionOccurs() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-4-9.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisargNotPassedToStrictCallbackfn() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-1-s.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisargNotPassed() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-1.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryArrayObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-10.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryStringObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-11.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryBooleanObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-12.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryNumberObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-13.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryTheMathObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-14.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDateObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-15.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryRegexpObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-16.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryTheJsonObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-17.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryErrorObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-18.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryTheArgumentsObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-19.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisargIsObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-2.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryTheGlobalObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-21.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryBooleanPrimitiveCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-22.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryNumberPrimitiveCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-23.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryStringPrimitiveCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-24.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisargIsArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-3.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisargIsObjectFromObjectTemplatePrototype() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-4.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisargIsObjectFromObjectTemplate() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-5.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisargIsFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-6.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryBuiltInFunctionsCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-7.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryFunctionObjectCanBeUsedAsThisarg() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-9.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryConsidersNewElementsAddedToArrayAfterTheCall() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-1.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryConsidersNewValueOfElementsInArrayAfterTheCall() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-2.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDoesnTVisitDeletedElementsInArrayAfterTheCall() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-3.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDoesnTVisitDeletedElementsWhenArrayLengthIsDecreased() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-4.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDoesnTConsiderNewlyAddedElementsInSparseArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-5.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryVisitsDeletedElementInArrayAfterTheCallWhenSameIndexIsAlsoPresentInPrototype() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-6.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDeletingTheArrayItselfWithinTheCallbackfnOfArrayPrototypeEveryIsSuccessfulOnceArrayPrototypeEveryIsCalledForAllElements() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-7.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryNoObservableEffectsOccurIfLenIs0() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-8.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryModificationsToLengthDonTChangeNumberOfIterations() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-9.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallbackfnNotCalledForIndexesNeverBeenAssignedValues() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-1.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDeletingPropertyOfPrototypeCausesPrototypeIndexPropertyNotToBeVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-10.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDeletingPropertyOfPrototypeCausesPrototypeIndexPropertyNotToBeVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-11.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDeletingOwnPropertyWithPrototypePropertyCausesPrototypeIndexPropertyToBeVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-12.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDeletingOwnPropertyWithPrototypePropertyCausesPrototypeIndexPropertyToBeVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-13.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDecreasingLengthOfArrayCausesIndexPropertyNotToBeVisited() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-14.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDecreasingLengthOfArrayWithPrototypePropertyCausesPrototypeIndexPropertyToBeVisited() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-15.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDecreasingLengthOfArrayDoesNotDeleteNonConfigurableProperties() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-16.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryAddedPropertiesInStep2AreVisibleHere() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-2.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDeletedPropertiesInStep2AreVisibleHere() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-3.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryPropertiesAddedIntoOwnObjectAfterCurrentPositionAreVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-4.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryPropertiesAddedIntoOwnObjectAfterCurrentPositionAreVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-5.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryPropertiesCanBeAddedToPrototypeAfterCurrentPositionAreVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-6.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryPropertiesCanBeAddedToPrototypeAfterCurrentPositionAreVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-7.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDeletingOwnPropertyCausesIndexPropertyNotToBeVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-8.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDeletingOwnPropertyCausesIndexPropertyNotToBeVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-9.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-1.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-10.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-11.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-12.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-13.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-14.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsInheritedAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-15.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-16.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-17.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-18.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionThatOverridesAnInheritedAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-19.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-2.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionThatOverridesAnInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-20.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsInheritedAccessorPropertyWithoutAGetFunctionOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-21.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsInheritedAccessorPropertyWithoutAGetFunctionOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-22.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisObjectIsAnGlobalObjectWhichContainsIndexProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-23.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisObjectIsTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethodNumberOfArgumentsIsLessThanNumberOfParameters() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-25.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisObjectIsTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethodNumberOfArgumentsEqualsNumberOfParameters() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-26.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisObjectIsTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethodNumberOfArgumentsIsGreaterThanNumberOfParameters() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-27.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementChangedByGetterOnPreviousIterationsIsObservedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-28.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementChangedByGetterOnPreviousIterationsIsObservedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-29.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-3.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryUnnhandledExceptionsHappenedInGetterTerminateIterationOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-30.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryUnhandledExceptionsHappenedInGetterTerminateIterationOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-31.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedDataPropertyOnAnArray2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-4.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-5.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-6.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsInheritedDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-7.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsInheritedDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-8.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementToBeRetrievedIsOwnAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-9.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallbackfnCalledWithCorrectParameters() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-1.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallbackfnIsCalledWith1FormalParameter() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-10.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallbackfnIsCalledWith2FormalParameter() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-11.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallbackfnIsCalledWith3FormalParameter() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-12.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallbackfnThatUsesArgumentsObjectToGetParameterValue() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-13.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisOfCallbackfnIsABooleanObjectWhenTIsNotAnObjectTIsABooleanPrimitive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-16.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisOfCallbackfnIsANumberObjectWhenTIsNotAnObjectTIsANumberPrimitive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-17.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryThisOfCallbackfnIsAnStringObjectWhenTIsNotAnObjectTIsAStringPrimitive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-18.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryNonIndexedPropertiesAreNotCalled() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-19.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallbackfnTakes3Arguments() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-2.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallbackfnCalledWithCorrectParametersThisargIsCorrect() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-20.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallbackfnCalledWithCorrectParametersKvalueIsCorrect() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-21.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallbackfnCalledWithCorrectParametersTheIndexKIsCorrect() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-22.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallbackfnCalledWithCorrectParametersThisObjectOIsCorrect() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-23.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryImmediatelyReturnsFalseIfCallbackfnReturnsFalse() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-3.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryKValuesArePassedInAscendingNumericOrder() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-4.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryKValuesAreAccessedDuringEachIterationAndNotPriorToStartingTheLoopOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-5.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryArgumentsToCallbackfnAreSelfConsistent() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-6.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryUnhandledExceptionsHappenedInCallbackfnTerminateIteration() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-7.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryElementChangedByCallbackfnOnPreviousIterationsIsObserved() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-8.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryCallbackfnIsCalledWith0FormalParameter() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-9.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsUndefined() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-1.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsANumberValueIsInfinity() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-10.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsANumberValueIsInfinity2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-11.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsANumberValueIsNan() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-12.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsAnEmptyString() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-13.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsANonEmptyString() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-14.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsAFunctionObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-15.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsAnArrayObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-16.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsAStringObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-17.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsABooleanObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-18.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsANumberObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-19.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsNull() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-2.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsTheMathObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-20.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsADateObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-21.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsARegexpObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-22.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsTheJsonObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-23.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsAnErrorObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-24.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsTheArgumentsObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-25.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsTheGlobalObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-27.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryFalsePreventsFurtherSideEffects() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-28.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueNewBooleanFalseOfCallbackfnIsTreatedAsTrueValue() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-29.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsABooleanValueIsFalse() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-3.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsABooleanValueIsTrue() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-4.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsANumberValueIs0() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-5.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsANumberValueIs02() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-6.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsANunmberValueIs0() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-7.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsANumberValueIsPositiveNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-8.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnValueOfCallbackfnIsANumberValueIsNegativeNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-iii-9.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnsTrueIfLengthIs0EmptyArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-8-1.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEverySubclassedArrayWhenLengthIsReduced() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-8-10.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnsTrueWhenAllCallsToCallbackfnReturnTrue() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-8-11.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDoesnTMutateTheArrayOnWhichItIsCalledOn() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-8-12.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryDoesnTVisitExpandos() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-8-13.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnsTrueIfLengthIs0SubclassedArrayLengthOverriddenToNullTypeConversion() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-8-2.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnsTrueIfLengthIs0SubclassedArrayLengthOverriddenToFalseTypeConversion() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-8-3.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnsTrueIfLengthIs0SubclassedArrayLengthOverriddenTo0TypeConversion() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-8-4.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnsTrueIfLengthIs0SubclassedArrayLengthOverriddenTo0TypeConversion2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-8-5.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnsTrueIfLengthIs0SubclassedArrayLengthOverriddenWithObjWithValueof() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-8-6.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnsTrueIfLengthIs0SubclassedArrayLengthOverriddenWithObjWOValueofTostring() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-8-7.js", false); } [Fact] [Trait("Category", "15.4.4.16")] public void ArrayPrototypeEveryReturnsTrueIfLengthIs0SubclassedArrayLengthOverriddenWith() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-8-8.js", false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Concurrent.Tests { public class ConcurrentDictionaryTests { [Fact] public static void TestBasicScenarios() { ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>(); Task[] tks = new Task[2]; tks[0] = Task.Run(() => { var ret = cd.TryAdd(1, 11); if (!ret) { ret = cd.TryUpdate(1, 11, 111); Assert.True(ret); } ret = cd.TryAdd(2, 22); if (!ret) { ret = cd.TryUpdate(2, 22, 222); Assert.True(ret); } }); tks[1] = Task.Run(() => { var ret = cd.TryAdd(2, 222); if (!ret) { ret = cd.TryUpdate(2, 222, 22); Assert.True(ret); } ret = cd.TryAdd(1, 111); if (!ret) { ret = cd.TryUpdate(1, 111, 11); Assert.True(ret); } }); Task.WaitAll(tks); } [Fact] public static void TestAdd1() { TestAdd1(1, 1, 1, 10000); TestAdd1(5, 1, 1, 10000); TestAdd1(1, 1, 2, 5000); TestAdd1(1, 1, 5, 2000); TestAdd1(4, 0, 4, 2000); TestAdd1(16, 31, 4, 2000); TestAdd1(64, 5, 5, 5000); TestAdd1(5, 5, 5, 2500); } private static void TestAdd1(int cLevel, int initSize, int threads, int addsPerThread) { ConcurrentDictionary<int, int> dictConcurrent = new ConcurrentDictionary<int, int>(cLevel, 1); IDictionary<int, int> dict = dictConcurrent; int count = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < addsPerThread; j++) { dict.Add(j + ii * addsPerThread, -(j + ii * addsPerThread)); } if (Interlocked.Decrement(ref count) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { Assert.Equal(pair.Key, -pair.Value); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); int itemCount = threads * addsPerThread; for (int i = 0; i < itemCount; i++) expectKeys.Add(i); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), String.Format("The set of keys in the dictionary is are not the same as the expected" + Environment.NewLine + "TestAdd1(cLevel={0}, initSize={1}, threads={2}, addsPerThread={3})", cLevel, initSize, threads, addsPerThread) ); } // Finally, let's verify that the count is reported correctly. int expectedCount = threads * addsPerThread; Assert.Equal(expectedCount, dict.Count); Assert.Equal(expectedCount, dictConcurrent.ToArray().Length); } [Fact] public static void TestUpdate1() { TestUpdate1(1, 1, 10000); TestUpdate1(5, 1, 10000); TestUpdate1(1, 2, 5000); TestUpdate1(1, 5, 2001); TestUpdate1(4, 4, 2001); TestUpdate1(15, 5, 2001); TestUpdate1(64, 5, 5000); TestUpdate1(5, 5, 25000); } private static void TestUpdate1(int cLevel, int threads, int updatesPerThread) { IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); for (int i = 1; i <= updatesPerThread; i++) dict[i] = i; int running = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 1; j <= updatesPerThread; j++) { dict[j] = (ii + 2) * j; } if (Interlocked.Decrement(ref running) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { var div = pair.Value / pair.Key; var rem = pair.Value % pair.Key; Assert.Equal(0, rem); Assert.True(div > 1 && div <= threads+1, String.Format("* Invalid value={3}! TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread, div)); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); for (int i = 1; i <= updatesPerThread; i++) expectKeys.Add(i); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), String.Format("The set of keys in the dictionary is are not the same as the expected." + Environment.NewLine + "TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread) ); } } [Fact] public static void TestRead1() { TestRead1(1, 1, 10000); TestRead1(5, 1, 10000); TestRead1(1, 2, 5000); TestRead1(1, 5, 2001); TestRead1(4, 4, 2001); TestRead1(15, 5, 2001); TestRead1(64, 5, 5000); TestRead1(5, 5, 25000); } private static void TestRead1(int cLevel, int threads, int readsPerThread) { IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); for (int i = 0; i < readsPerThread; i += 2) dict[i] = i; int count = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < readsPerThread; j++) { int val = 0; if (dict.TryGetValue(j, out val)) { Assert.Equal(0, j % 2); Assert.Equal(j, val); } else { Assert.Equal(1, j % 2); } } if (Interlocked.Decrement(ref count) == 0) mre.Set(); }); } mre.WaitOne(); } } [Fact] public static void TestRemove1() { TestRemove1(1, 1, 10000); TestRemove1(5, 1, 1000); TestRemove1(1, 5, 2001); TestRemove1(4, 4, 2001); TestRemove1(15, 5, 2001); TestRemove1(64, 5, 5000); } private static void TestRemove1(int cLevel, int threads, int removesPerThread) { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); string methodparameters = string.Format("* TestRemove1(cLevel={0}, threads={1}, removesPerThread={2})", cLevel, threads, removesPerThread); int N = 2 * threads * removesPerThread; for (int i = 0; i < N; i++) dict[i] = -i; // The dictionary contains keys [0..N), each key mapped to a value equal to the key. // Threads will cooperatively remove all even keys int running = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < removesPerThread; j++) { int value; int key = 2 * (ii + j * threads); Assert.True(dict.TryRemove(key, out value), "Failed to remove an element! " + methodparameters); Assert.Equal(-key, value); } if (Interlocked.Decrement(ref running) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { Assert.Equal(pair.Key, -pair.Value); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); for (int i = 0; i < (threads * removesPerThread); i++) expectKeys.Add(2 * i + 1); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), " > Unexpected key value! " + methodparameters); } // Finally, let's verify that the count is reported correctly. Assert.Equal(expectKeys.Count, dict.Count); Assert.Equal(expectKeys.Count, dict.ToArray().Length); } [Fact] public static void TestRemove2() { TestRemove2(1); TestRemove2(10); TestRemove2(5000); } private static void TestRemove2(int removesPerThread) { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(); for (int i = 0; i < removesPerThread; i++) dict[i] = -i; // The dictionary contains keys [0..N), each key mapped to a value equal to the key. // Threads will cooperatively remove all even keys. const int SIZE = 2; int running = SIZE; bool[][] seen = new bool[SIZE][]; for (int i = 0; i < SIZE; i++) seen[i] = new bool[removesPerThread]; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int t = 0; t < SIZE; t++) { int thread = t; Task.Run( () => { for (int key = 0; key < removesPerThread; key++) { int value; if (dict.TryRemove(key, out value)) { seen[thread][key] = true; Assert.Equal(-key, value); } } if (Interlocked.Decrement(ref running) == 0) mre.Set(); }); } mre.WaitOne(); } Assert.Equal(0, dict.Count); for (int i = 0; i < removesPerThread; i++) { Assert.False(seen[0][i] == seen[1][i], String.Format("> FAILED. Two threads appear to have removed the same element. TestRemove2(removesPerThread={0})", removesPerThread) ); } } [Fact] public static void TestRemove3() { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(); dict[99] = -99; ICollection<KeyValuePair<int, int>> col = dict; // Make sure we cannot "remove" a key/value pair which is not in the dictionary for (int i = 0; i < 200; i++) { if (i != 99) { Assert.False(col.Remove(new KeyValuePair<int, int>(i, -99)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(i, -99)"); Assert.False(col.Remove(new KeyValuePair<int, int>(99, -i)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(99, -i)"); } } // Can we remove a key/value pair successfully? Assert.True(col.Remove(new KeyValuePair<int, int>(99, -99)), "Failed to remove existing key/value pair"); // Make sure the key/value pair is gone Assert.False(col.Remove(new KeyValuePair<int, int>(99, -99)), "Should not remove the key/value pair which has been removed"); // And that the dictionary is empty. We will check the count in a few different ways: Assert.Equal(0, dict.Count); Assert.Equal(0, dict.ToArray().Length); } [Fact] public static void TestGetOrAdd() { TestGetOrAddOrUpdate(1, 1, 1, 10000, true); TestGetOrAddOrUpdate(5, 1, 1, 10000, true); TestGetOrAddOrUpdate(1, 1, 2, 5000, true); TestGetOrAddOrUpdate(1, 1, 5, 2000, true); TestGetOrAddOrUpdate(4, 0, 4, 2000, true); TestGetOrAddOrUpdate(16, 31, 4, 2000, true); TestGetOrAddOrUpdate(64, 5, 5, 5000, true); TestGetOrAddOrUpdate(5, 5, 5, 25000, true); } [Fact] public static void TestAddOrUpdate() { TestGetOrAddOrUpdate(1, 1, 1, 10000, false); TestGetOrAddOrUpdate(5, 1, 1, 10000, false); TestGetOrAddOrUpdate(1, 1, 2, 5000, false); TestGetOrAddOrUpdate(1, 1, 5, 2000, false); TestGetOrAddOrUpdate(4, 0, 4, 2000, false); TestGetOrAddOrUpdate(16, 31, 4, 2000, false); TestGetOrAddOrUpdate(64, 5, 5, 5000, false); TestGetOrAddOrUpdate(5, 5, 5, 25000, false); } private static void TestGetOrAddOrUpdate(int cLevel, int initSize, int threads, int addsPerThread, bool isAdd) { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); int count = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < addsPerThread; j++) { if (isAdd) { //call either of the two overloads of GetOrAdd if (j + ii % 2 == 0) { dict.GetOrAdd(j, -j); } else { dict.GetOrAdd(j, x => -x); } } else { if (j + ii % 2 == 0) { dict.AddOrUpdate(j, -j, (k, v) => -j); } else { dict.AddOrUpdate(j, (k) => -k, (k, v) => -k); } } } if (Interlocked.Decrement(ref count) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { Assert.Equal(pair.Key, -pair.Value); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); for (int i = 0; i < addsPerThread; i++) expectKeys.Add(i); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), String.Format("* Test '{4}': Level={0}, initSize={1}, threads={2}, addsPerThread={3})" + Environment.NewLine + "> FAILED. The set of keys in the dictionary is are not the same as the expected.", cLevel, initSize, threads, addsPerThread, isAdd ? "GetOrAdd" : "GetOrUpdate")); } // Finally, let's verify that the count is reported correctly. Assert.Equal(addsPerThread, dict.Count); Assert.Equal(addsPerThread, dict.ToArray().Length); } [Fact] public static void TestBugFix669376() { var cd = new ConcurrentDictionary<string, int>(new OrdinalStringComparer()); cd["test"] = 10; Assert.True(cd.ContainsKey("TEST"), "Customized comparer didn't work"); } private class OrdinalStringComparer : IEqualityComparer<string> { public bool Equals(string x, string y) { var xlower = x.ToLowerInvariant(); var ylower = y.ToLowerInvariant(); return string.CompareOrdinal(xlower, ylower) == 0; } public int GetHashCode(string obj) { return 0; } } [Fact] public static void TestConstructor() { var dictionary = new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) }); Assert.False(dictionary.IsEmpty); Assert.Equal(1, dictionary.Keys.Count); Assert.Equal(1, dictionary.Values.Count); } [Fact] public static void TestDebuggerAttributes() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new ConcurrentDictionary<string, int>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new ConcurrentDictionary<string, int>()); } [Fact] public static void TestConstructor_Negative() { Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>((IEqualityComparer<int>)null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null IEqualityComparer is passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null, EqualityComparer<int>.Default)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null collection and non null IEqualityComparer passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) }, null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when non null collection and null IEqualityComparer passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<string, int>(new[] { new KeyValuePair<string, int>(null, 1) })); // "TestConstructor: FAILED. Constructor didn't throw ANE when collection has null key passed"); Assert.Throws<ArgumentException>( () => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1), new KeyValuePair<int, int>(1, 2) })); // "TestConstructor: FAILED. Constructor didn't throw AE when collection has duplicate keys passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>(1, null, EqualityComparer<int>.Default)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>(1, new[] { new KeyValuePair<int, int>(1, 1) }, null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>(1, 1, null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed"); Assert.Throws<ArgumentOutOfRangeException>( () => new ConcurrentDictionary<int, int>(0, 10)); // "TestConstructor: FAILED. Constructor didn't throw AORE when <1 concurrencyLevel passed"); Assert.Throws<ArgumentOutOfRangeException>( () => new ConcurrentDictionary<int, int>(-1, 0)); // "TestConstructor: FAILED. Constructor didn't throw AORE when < 0 capacity passed"); } [Fact] public static void TestExceptions() { var dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>( () => dictionary.TryAdd(null, 0)); // "TestExceptions: FAILED. TryAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.ContainsKey(null)); // "TestExceptions: FAILED. Contains didn't throw ANE when null key is passed"); int item; Assert.Throws<ArgumentNullException>( () => dictionary.TryRemove(null, out item)); // "TestExceptions: FAILED. TryRemove didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.TryGetValue(null, out item)); // "TestExceptions: FAILED. TryGetValue didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => { var x = dictionary[null]; }); // "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed"); Assert.Throws<KeyNotFoundException>( () => { var x = dictionary["1"]; }); // "TestExceptions: FAILED. this[] TryGetValue didn't throw KeyNotFoundException!"); Assert.Throws<ArgumentNullException>( () => dictionary[null] = 1); // "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd(null, (k) => 0)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd("1", null)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null valueFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd(null, 0)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate(null, (k) => 0, (k, v) => 0)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate("1", null, (k, v) => 0)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null updateFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate(null, (k) => 0, null)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null addFactory is passed"); dictionary.TryAdd("1", 1); Assert.Throws<ArgumentException>( () => ((IDictionary<string, int>)dictionary).Add("1", 2)); // "TestExceptions: FAILED. IDictionary didn't throw AE when duplicate key is passed"); } [Fact] public static void TestIDictionary() { IDictionary dictionary = new ConcurrentDictionary<string, int>(); Assert.False(dictionary.IsReadOnly); // Empty dictionary should not enumerate Assert.Empty(dictionary); const int SIZE = 10; for (int i = 0; i < SIZE; i++) dictionary.Add(i.ToString(), i); Assert.Equal(SIZE, dictionary.Count); //test contains Assert.False(dictionary.Contains(1), "TestIDictionary: FAILED. Contain retuned true for incorrect key type"); Assert.False(dictionary.Contains("100"), "TestIDictionary: FAILED. Contain retuned true for incorrect key"); Assert.True(dictionary.Contains("1"), "TestIDictionary: FAILED. Contain retuned false for correct key"); //test GetEnumerator int count = 0; foreach (var obj in dictionary) { DictionaryEntry entry = (DictionaryEntry)obj; string key = (string)entry.Key; int value = (int)entry.Value; int expectedValue = int.Parse(key); Assert.True(value == expectedValue, String.Format("TestIDictionary: FAILED. Unexpected value returned from GetEnumerator, expected {0}, actual {1}", value, expectedValue)); count++; } Assert.Equal(SIZE, count); Assert.Equal(SIZE, dictionary.Keys.Count); Assert.Equal(SIZE, dictionary.Values.Count); //Test Remove dictionary.Remove("9"); Assert.Equal(SIZE - 1, dictionary.Count); //Test this[] for (int i = 0; i < dictionary.Count; i++) Assert.Equal(i, (int)dictionary[i.ToString()]); dictionary["1"] = 100; // try a valid setter Assert.Equal(100, (int)dictionary["1"]); //nonsexist key Assert.Null(dictionary["NotAKey"]); } [Fact] public static void TestIDictionary_Negative() { IDictionary dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>( () => dictionary.Add(null, 1)); // "TestIDictionary: FAILED. Add didn't throw ANE when null key is passed"); Assert.Throws<ArgumentException>( () => dictionary.Add(1, 1)); // "TestIDictionary: FAILED. Add didn't throw AE when incorrect key type is passed"); Assert.Throws<ArgumentException>( () => dictionary.Add("1", "1")); // "TestIDictionary: FAILED. Add didn't throw AE when incorrect value type is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.Contains(null)); // "TestIDictionary: FAILED. Contain didn't throw ANE when null key is passed"); //Test Remove Assert.Throws<ArgumentNullException>( () => dictionary.Remove(null)); // "TestIDictionary: FAILED. Remove didn't throw ANE when null key is passed"); //Test this[] Assert.Throws<ArgumentNullException>( () => { object val = dictionary[null]; }); // "TestIDictionary: FAILED. this[] getter didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary[null] = 0); // "TestIDictionary: FAILED. this[] setter didn't throw ANE when null key is passed"); Assert.Throws<ArgumentException>( () => dictionary[1] = 0); // "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid key type is passed"); Assert.Throws<ArgumentException>( () => dictionary["1"] = "0"); // "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid value type is passed"); } [Fact] public static void TestICollection() { ICollection dictionary = new ConcurrentDictionary<int, int>(); Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!"); int key = -1; int value = +1; //add one item to the dictionary ((ConcurrentDictionary<int, int>)dictionary).TryAdd(key, value); var objectArray = new Object[1]; dictionary.CopyTo(objectArray, 0); Assert.Equal(key, ((KeyValuePair<int, int>)objectArray[0]).Key); Assert.Equal(value, ((KeyValuePair<int, int>)objectArray[0]).Value); var keyValueArray = new KeyValuePair<int, int>[1]; dictionary.CopyTo(keyValueArray, 0); Assert.Equal(key, keyValueArray[0].Key); Assert.Equal(value, keyValueArray[0].Value); var entryArray = new DictionaryEntry[1]; dictionary.CopyTo(entryArray, 0); Assert.Equal(key, (int)entryArray[0].Key); Assert.Equal(value, (int)entryArray[0].Value); } [Fact] public static void TestICollection_Negative() { ICollection dictionary = new ConcurrentDictionary<int, int>(); Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!"); Assert.Throws<NotSupportedException>(() => { var obj = dictionary.SyncRoot; }); // "TestICollection: FAILED. SyncRoot property didn't throw"); Assert.Throws<ArgumentNullException>(() => dictionary.CopyTo(null, 0)); // "TestICollection: FAILED. CopyTo didn't throw ANE when null Array is passed"); Assert.Throws<ArgumentOutOfRangeException>(() => dictionary.CopyTo(new object[] { }, -1)); // "TestICollection: FAILED. CopyTo didn't throw AORE when negative index passed"); //add one item to the dictionary ((ConcurrentDictionary<int, int>)dictionary).TryAdd(1, 1); Assert.Throws<ArgumentException>(() => dictionary.CopyTo(new object[] { }, 0)); // "TestICollection: FAILED. CopyTo didn't throw AE when the Array size is smaller than the dictionary count"); } [Fact] public static void TestClear() { var dictionary = new ConcurrentDictionary<int, int>(); for (int i = 0; i < 10; i++) dictionary.TryAdd(i, i); Assert.Equal(10, dictionary.Count); dictionary.Clear(); Assert.Equal(0, dictionary.Count); int item; Assert.False(dictionary.TryRemove(1, out item), "TestClear: FAILED. TryRemove succeeded after Clear"); Assert.True(dictionary.IsEmpty, "TestClear: FAILED. IsEmpty returned false after Clear"); } public static void TestTryUpdate() { var dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>( () => dictionary.TryUpdate(null, 0, 0)); // "TestTryUpdate: FAILED. TryUpdate didn't throw ANE when null key is passed"); for (int i = 0; i < 10; i++) dictionary.TryAdd(i.ToString(), i); for (int i = 0; i < 10; i++) { Assert.True(dictionary.TryUpdate(i.ToString(), i + 1, i), "TestTryUpdate: FAILED. TryUpdate failed!"); Assert.Equal(i + 1, dictionary[i.ToString()]); } //test TryUpdate concurrently dictionary.Clear(); for (int i = 0; i < 1000; i++) dictionary.TryAdd(i.ToString(), i); var mres = new ManualResetEventSlim(); Task[] tasks = new Task[10]; ThreadLocal<ThreadData> updatedKeys = new ThreadLocal<ThreadData>(true); for (int i = 0; i < tasks.Length; i++) { // We are creating the Task using TaskCreationOptions.LongRunning because... // there is no guarantee that the Task will be created on another thread. // There is also no guarantee that using this TaskCreationOption will force // it to be run on another thread. tasks[i] = Task.Factory.StartNew((obj) => { mres.Wait(); int index = (((int)obj) + 1) + 1000; updatedKeys.Value = new ThreadData(); updatedKeys.Value.ThreadIndex = index; for (int j = 0; j < dictionary.Count; j++) { if (dictionary.TryUpdate(j.ToString(), index, j)) { if (dictionary[j.ToString()] != index) { updatedKeys.Value.Succeeded = false; return; } updatedKeys.Value.Keys.Add(j.ToString()); } } }, i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } mres.Set(); Task.WaitAll(tasks); int numberSucceeded = 0; int totalKeysUpdated = 0; foreach (var threadData in updatedKeys.Values) { totalKeysUpdated += threadData.Keys.Count; if (threadData.Succeeded) numberSucceeded++; } Assert.True(numberSucceeded == tasks.Length, "One or more threads failed!"); Assert.True(totalKeysUpdated == dictionary.Count, String.Format("TestTryUpdate: FAILED. The updated keys count doesn't match the dictionary count, expected {0}, actual {1}", dictionary.Count, totalKeysUpdated)); foreach (var value in updatedKeys.Values) { for (int i = 0; i < value.Keys.Count; i++) Assert.True(dictionary[value.Keys[i]] == value.ThreadIndex, String.Format("TestTryUpdate: FAILED. The updated value doesn't match the thread index, expected {0} actual {1}", value.ThreadIndex, dictionary[value.Keys[i]])); } //test TryUpdate with non atomic values (intPtr > 8) var dict = new ConcurrentDictionary<int, Struct16>(); dict.TryAdd(1, new Struct16(1, -1)); Assert.True(dict.TryUpdate(1, new Struct16(2, -2), new Struct16(1, -1)), "TestTryUpdate: FAILED. TryUpdate failed for non atomic values ( > 8 bytes)"); } #region Helper Classes and Methods private class ThreadData { public int ThreadIndex; public bool Succeeded = true; public List<string> Keys = new List<string>(); } private struct Struct16 : IEqualityComparer<Struct16> { public long L1, L2; public Struct16(long l1, long l2) { L1 = l1; L2 = l2; } public bool Equals(Struct16 x, Struct16 y) { return x.L1 == y.L1 && x.L2 == y.L2; } public int GetHashCode(Struct16 obj) { return (int)L1; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; namespace System.Security.Principal { public sealed class NTAccount : IdentityReference { #region Private members private readonly string _name; // // Limit for nt account names for users is 20 while that for groups is 256 // internal const int MaximumAccountNameLength = 256; // // Limit for dns domain names is 255 // internal const int MaximumDomainNameLength = 255; #endregion #region Constructors public NTAccount(string domainName, string accountName) { if (accountName == null) { throw new ArgumentNullException("accountName"); } if (accountName.Length == 0) { throw new ArgumentException(SR.Argument_StringZeroLength, "accountName"); } if (accountName.Length > MaximumAccountNameLength) { throw new ArgumentException(SR.IdentityReference_AccountNameTooLong, "accountName"); } if (domainName != null && domainName.Length > MaximumDomainNameLength) { throw new ArgumentException(SR.IdentityReference_DomainNameTooLong, "domainName"); } Contract.EndContractBlock(); if (domainName == null || domainName.Length == 0) { _name = accountName; } else { _name = domainName + "\\" + accountName; } } public NTAccount(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_StringZeroLength, "name"); } if (name.Length > (MaximumDomainNameLength + 1 /* '\' */ + MaximumAccountNameLength)) { throw new ArgumentException(SR.IdentityReference_AccountNameTooLong, "name"); } Contract.EndContractBlock(); _name = name; } #endregion #region Inherited properties and methods public override string Value { get { return ToString(); } } public override bool IsValidTargetType(Type targetType) { if (targetType == typeof(SecurityIdentifier)) { return true; } else if (targetType == typeof(NTAccount)) { return true; } else { return false; } } public override IdentityReference Translate(Type targetType) { if (targetType == null) { throw new ArgumentNullException("targetType"); } Contract.EndContractBlock(); if (targetType == typeof(NTAccount)) { return this; // assumes that NTAccount objects are immutable } else if (targetType == typeof(SecurityIdentifier)) { IdentityReferenceCollection irSource = new IdentityReferenceCollection(1); irSource.Add(this); IdentityReferenceCollection irTarget; irTarget = NTAccount.Translate(irSource, targetType, true); return irTarget[0]; } else { throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, "targetType"); } } public override bool Equals(object o) { return (this == o as NTAccount); // invokes operator== } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(_name); } public override string ToString() { return _name; } internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceAccounts, Type targetType, bool forceSuccess) { bool SomeFailed = false; IdentityReferenceCollection Result; Result = Translate(sourceAccounts, targetType, out SomeFailed); if (forceSuccess && SomeFailed) { IdentityReferenceCollection UnmappedIdentities = new IdentityReferenceCollection(); foreach (IdentityReference id in Result) { if (id.GetType() != targetType) { UnmappedIdentities.Add(id); } } throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, UnmappedIdentities); } return Result; } internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceAccounts, Type targetType, out bool someFailed) { if (sourceAccounts == null) { throw new ArgumentNullException("sourceAccounts"); } Contract.EndContractBlock(); if (targetType == typeof(SecurityIdentifier)) { return TranslateToSids(sourceAccounts, out someFailed); } throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, "targetType"); } #endregion #region Operators public static bool operator ==(NTAccount left, NTAccount right) { object l = left; object r = right; if (l == r) { return true; } else if (l == null || r == null) { return false; } else { return (left.ToString().Equals(right.ToString(), StringComparison.OrdinalIgnoreCase)); } } public static bool operator !=(NTAccount left, NTAccount right) { return !(left == right); // invoke operator== } #endregion #region Private methods private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed) { if (sourceAccounts == null) { throw new ArgumentNullException("sourceAccounts"); } if (sourceAccounts.Count == 0) { throw new ArgumentException(SR.Arg_EmptyCollection, "sourceAccounts"); } Contract.EndContractBlock(); SafeLsaPolicyHandle LsaHandle = SafeLsaPolicyHandle.InvalidHandle; SafeLsaMemoryHandle ReferencedDomainsPtr = SafeLsaMemoryHandle.InvalidHandle; SafeLsaMemoryHandle SidsPtr = SafeLsaMemoryHandle.InvalidHandle; try { // // Construct an array of unicode strings // Interop.UNICODE_STRING[] Names = new Interop.UNICODE_STRING[sourceAccounts.Count]; int currentName = 0; foreach (IdentityReference id in sourceAccounts) { NTAccount nta = id as NTAccount; if (nta == null) { throw new ArgumentException(SR.Argument_ImproperType, "sourceAccounts"); } Names[currentName].Buffer = nta.ToString(); if (Names[currentName].Buffer.Length * 2 + 2 > ushort.MaxValue) { // this should never happen since we are already validating account name length in constructor and // it is less than this limit Debug.Assert(false, "NTAccount::TranslateToSids - source account name is too long."); throw new InvalidOperationException(); } Names[currentName].Length = (ushort)(Names[currentName].Buffer.Length * 2); Names[currentName].MaximumLength = (ushort)(Names[currentName].Length + 2); currentName++; } // // Open LSA policy (for lookup requires it) // LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES); // // Now perform the actual lookup // someFailed = false; uint ReturnCode; ReturnCode = Interop.mincore.LsaLookupNames2(LsaHandle, 0, sourceAccounts.Count, Names, ref ReferencedDomainsPtr, ref SidsPtr); // // Make a decision regarding whether it makes sense to proceed // based on the return code and the value of the forceSuccess argument // if (ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY || ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES) { throw new OutOfMemoryException(); } else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } else if (ReturnCode == Interop.StatusOptions.STATUS_NONE_MAPPED || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED) { someFailed = true; } else if (ReturnCode != 0) { int win32ErrorCode = Interop.mincore.RtlNtStatusToDosError(unchecked((int)ReturnCode)); if (win32ErrorCode != Interop.mincore.Errors.ERROR_TRUSTED_RELATIONSHIP_FAILURE) { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Interop.LsaLookupNames(2) returned unrecognized error {0}", win32ErrorCode)); } throw new Win32Exception(win32ErrorCode); } // // Interpret the results and generate SID objects // IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceAccounts.Count); if (ReturnCode == 0 || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED) { SidsPtr.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf<Interop.LSA_TRANSLATED_SID2>()); Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr); Interop.LSA_TRANSLATED_SID2[] translatedSids = new Interop.LSA_TRANSLATED_SID2[sourceAccounts.Count]; SidsPtr.ReadArray(0, translatedSids, 0, translatedSids.Length); for (int i = 0; i < sourceAccounts.Count; i++) { Interop.LSA_TRANSLATED_SID2 Lts = translatedSids[i]; // // Only some names are recognized as NTAccount objects // switch ((SidNameUse)Lts.Use) { case SidNameUse.User: case SidNameUse.Group: case SidNameUse.Alias: case SidNameUse.Computer: case SidNameUse.WellKnownGroup: Result.Add(new SecurityIdentifier(Lts.Sid, true)); break; default: someFailed = true; Result.Add(sourceAccounts[i]); break; } } } else { for (int i = 0; i < sourceAccounts.Count; i++) { Result.Add(sourceAccounts[i]); } } return Result; } finally { LsaHandle.Dispose(); ReferencedDomainsPtr.Dispose(); SidsPtr.Dispose(); } } #endregion } }
using BTDB.KVDBLayer; using BTDB.StreamLayer; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // ReSharper disable MemberCanBeProtected.Global namespace BTDB.ODBLayer { class RelationEnumerator<T> : IEnumerator<T>, IEnumerable<T> { readonly IInternalObjectDBTransaction _transaction; protected readonly RelationInfo.ItemLoaderInfo ItemLoader; readonly IRelationModificationCounter _modificationCounter; readonly IKeyValueDBTransaction _keyValueTr; long _prevProtectionCounter; uint _pos; bool _seekNeeded; protected readonly byte[] KeyBytes; readonly int _prevModificationCounter; public RelationEnumerator(IInternalObjectDBTransaction tr, RelationInfo relationInfo, ReadOnlySpan<byte> keyBytes, IRelationModificationCounter modificationCounter, int loaderIndex) { _transaction = tr; ItemLoader = relationInfo.ItemLoaderInfos[loaderIndex]; _keyValueTr = _transaction.KeyValueDBTransaction; _prevProtectionCounter = _keyValueTr.CursorMovedCounter; KeyBytes = keyBytes.ToArray(); _modificationCounter = modificationCounter; _pos = 0; _seekNeeded = true; _prevModificationCounter = _modificationCounter.ModificationCounter; } public RelationEnumerator(IInternalObjectDBTransaction tr, RelationInfo relationInfo, byte[] keyBytes, IRelationModificationCounter modificationCounter, int loaderIndex) { _transaction = tr; ItemLoader = relationInfo.ItemLoaderInfos[loaderIndex]; _keyValueTr = _transaction.KeyValueDBTransaction; _prevProtectionCounter = _keyValueTr.CursorMovedCounter; KeyBytes = keyBytes; _modificationCounter = modificationCounter; _pos = 0; _seekNeeded = true; _prevModificationCounter = _modificationCounter.ModificationCounter; } public bool MoveNext() { if (!_seekNeeded) _pos++; if (_keyValueTr.CursorMovedCounter != _prevProtectionCounter) { _modificationCounter.CheckModifiedDuringEnum(_prevModificationCounter); } var ret = Seek(); _prevProtectionCounter = _keyValueTr.CursorMovedCounter; return ret; } bool Seek() { if (!_keyValueTr.SetKeyIndex(KeyBytes, _pos)) return false; _seekNeeded = false; return true; } public T Current { [SkipLocalsInit] get { SeekCurrent(); Span<byte> keyBuffer = stackalloc byte[512]; var keyBytes = _keyValueTr.GetKey(ref MemoryMarshal.GetReference(keyBuffer), keyBuffer.Length); return CreateInstance(keyBytes, _keyValueTr); } } public byte[] GetKeyBytes() { SeekCurrent(); return _keyValueTr.GetKeyToArray(); } void SeekCurrent() { if (_seekNeeded) throw new BTDBException("Invalid access to uninitialized Current."); if (_keyValueTr.CursorMovedCounter != _prevProtectionCounter) { _modificationCounter.CheckModifiedDuringEnum(_prevModificationCounter); Seek(); } _prevProtectionCounter = _keyValueTr.CursorMovedCounter; } protected virtual T CreateInstance(in ReadOnlySpan<byte> keyBytes, in IKeyValueDBTransaction kvtr) { return (T)ItemLoader.CreateInstance(_transaction, keyBytes, kvtr); } object IEnumerator.Current => Current!; public void Reset() { _pos = 0; _seekNeeded = true; } public void Dispose() { } public IEnumerator<T> GetEnumerator() { Reset(); return this; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } class RelationPrimaryKeyEnumerator<T> : RelationEnumerator<T> { public RelationPrimaryKeyEnumerator(IInternalObjectDBTransaction tr, RelationInfo relationInfo, in ReadOnlySpan<byte> keyBytes, IRelationModificationCounter modificationCounter, int loaderIndex) : base(tr, relationInfo, keyBytes, modificationCounter, loaderIndex) { } } class RelationSecondaryKeyEnumerator<T> : RelationEnumerator<T> { readonly uint _secondaryKeyIndex; readonly uint _fieldCountInKey; readonly IRelationDbManipulator _manipulator; public RelationSecondaryKeyEnumerator(IInternalObjectDBTransaction tr, RelationInfo relationInfo, in ReadOnlySpan<byte> keyBytes, uint secondaryKeyIndex, uint fieldCountInKey, IRelationDbManipulator manipulator, int loaderIndex) : base(tr, relationInfo, keyBytes, manipulator, loaderIndex) { _secondaryKeyIndex = secondaryKeyIndex; _fieldCountInKey = fieldCountInKey; _manipulator = manipulator; } protected override T CreateInstance(in ReadOnlySpan<byte> keyBytes, in IKeyValueDBTransaction valueBytes) { return (T)_manipulator.CreateInstanceFromSecondaryKey(ItemLoader, _secondaryKeyIndex, _fieldCountInKey, KeyBytes, keyBytes.Slice(KeyBytes.Length)); } } public class RelationAdvancedEnumerator<T> : IEnumerator<T>, IEnumerable<T> { protected readonly uint PrefixFieldCount; protected readonly IRelationDbManipulator Manipulator; protected readonly RelationInfo.ItemLoaderInfo ItemLoader; readonly IInternalObjectDBTransaction _tr; readonly IKeyValueDBTransaction _keyValueTr; long _prevProtectionCounter; readonly uint _startPos; readonly uint _count; uint _pos; bool _seekNeeded; readonly bool _ascending; protected readonly byte[] KeyBytes; readonly int _prevModificationCounter; public RelationAdvancedEnumerator( IRelationDbManipulator manipulator, uint prefixFieldCount, EnumerationOrder order, KeyProposition startKeyProposition, int prefixLen, in ReadOnlySpan<byte> startKeyBytes, KeyProposition endKeyProposition, in ReadOnlySpan<byte> endKeyBytes, int loaderIndex) { PrefixFieldCount = prefixFieldCount; Manipulator = manipulator; ItemLoader = Manipulator.RelationInfo.ItemLoaderInfos[loaderIndex]; _ascending = order == EnumerationOrder.Ascending; _tr = manipulator.Transaction; _keyValueTr = _tr.KeyValueDBTransaction; _prevProtectionCounter = _keyValueTr.CursorMovedCounter; KeyBytes = startKeyBytes.Slice(0, prefixLen).ToArray(); var realEndKeyBytes = endKeyBytes; if (endKeyProposition == KeyProposition.Included) realEndKeyBytes = FindLastKeyWithPrefix(endKeyBytes, _keyValueTr); _keyValueTr.FindFirstKey(startKeyBytes.Slice(0, prefixLen)); var prefixIndex = _keyValueTr.GetKeyIndex(); if (prefixIndex == -1) { _count = 0; _startPos = 0; _pos = 0; _seekNeeded = true; return; } _prevModificationCounter = manipulator.ModificationCounter; long startIndex; long endIndex; if (endKeyProposition == KeyProposition.Ignored) { _keyValueTr.FindLastKey(startKeyBytes.Slice(0, prefixLen)); endIndex = _keyValueTr.GetKeyIndex() - prefixIndex; } else { switch (_keyValueTr.Find(realEndKeyBytes, (uint)prefixLen)) { case FindResult.Exact: endIndex = _keyValueTr.GetKeyIndex() - prefixIndex; if (endKeyProposition == KeyProposition.Excluded) { endIndex--; } break; case FindResult.Previous: endIndex = _keyValueTr.GetKeyIndex() - prefixIndex; break; case FindResult.Next: endIndex = _keyValueTr.GetKeyIndex() - prefixIndex - 1; break; case FindResult.NotFound: endIndex = -1; break; default: throw new ArgumentOutOfRangeException(); } } if (startKeyProposition == KeyProposition.Ignored) { startIndex = 0; } else { switch (_keyValueTr.Find(startKeyBytes, (uint)prefixLen)) { case FindResult.Exact: startIndex = _keyValueTr.GetKeyIndex() - prefixIndex; if (startKeyProposition == KeyProposition.Excluded) { startIndex++; } break; case FindResult.Previous: startIndex = _keyValueTr.GetKeyIndex() - prefixIndex + 1; break; case FindResult.Next: startIndex = _keyValueTr.GetKeyIndex() - prefixIndex; break; case FindResult.NotFound: startIndex = 0; break; default: throw new ArgumentOutOfRangeException(); } } _count = (uint)Math.Max(0, endIndex - startIndex + 1); _startPos = (uint)(_ascending ? startIndex : endIndex); _pos = 0; _seekNeeded = true; } public RelationAdvancedEnumerator( IRelationDbManipulator manipulator, in ReadOnlySpan<byte> prefixBytes, uint prefixFieldCount, int loaderIndex) { PrefixFieldCount = prefixFieldCount; Manipulator = manipulator; ItemLoader = Manipulator.RelationInfo.ItemLoaderInfos[loaderIndex]; _ascending = true; _tr = manipulator.Transaction; _keyValueTr = _tr.KeyValueDBTransaction; _prevProtectionCounter = _keyValueTr.CursorMovedCounter; KeyBytes = prefixBytes.ToArray(); _prevModificationCounter = manipulator.ModificationCounter; _count = (uint)_keyValueTr.GetKeyValueCount(prefixBytes); _startPos = _ascending ? 0 : _count - 1; _pos = 0; _seekNeeded = true; } internal static ReadOnlySpan<byte> FindLastKeyWithPrefix(in ReadOnlySpan<byte> endKeyBytes, IKeyValueDBTransaction keyValueTr) { if (!keyValueTr.FindLastKey(endKeyBytes)) return endKeyBytes; return keyValueTr.GetKey(); } public bool MoveNext() { if (!_seekNeeded) _pos++; if (_pos >= _count) return false; if (_keyValueTr.CursorMovedCounter != _prevProtectionCounter) { Manipulator.CheckModifiedDuringEnum(_prevModificationCounter); Seek(); } else if (_seekNeeded) { Seek(); } else { if (_ascending) { _keyValueTr.FindNextKey(KeyBytes); } else { _keyValueTr.FindPreviousKey(KeyBytes); } } _prevProtectionCounter = _keyValueTr.CursorMovedCounter; return true; } public void Reset() { _pos = 0; _seekNeeded = true; } public T Current { [SkipLocalsInit] get { if (_pos >= _count) throw new IndexOutOfRangeException(); if (_seekNeeded) throw new BTDBException("Invalid access to uninitialized Current."); if (_keyValueTr.CursorMovedCounter != _prevProtectionCounter) { Manipulator.CheckModifiedDuringEnum(_prevModificationCounter); Seek(); } _prevProtectionCounter = _keyValueTr.CursorMovedCounter; Span<byte> buffer = stackalloc byte[512]; var keyBytes = _keyValueTr.GetKey(ref MemoryMarshal.GetReference(buffer), buffer.Length); return CreateInstance(keyBytes); } } protected virtual T CreateInstance(in ReadOnlySpan<byte> keyBytes) { return (T)ItemLoader.CreateInstance(_tr, keyBytes, _keyValueTr); } public byte[] GetKeyBytes() { return _keyValueTr.GetKeyToArray(); } void Seek() { if (_ascending) _keyValueTr.SetKeyIndex(KeyBytes, _startPos + _pos); else _keyValueTr.SetKeyIndex(KeyBytes, _startPos - _pos); _seekNeeded = false; } object IEnumerator.Current => Current!; public void Dispose() { } public IEnumerator<T> GetEnumerator() { Reset(); return this; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class RelationAdvancedSecondaryKeyEnumerator<T> : RelationAdvancedEnumerator<T> { readonly uint _secondaryKeyIndex; // ReSharper disable once UnusedMember.Global public RelationAdvancedSecondaryKeyEnumerator( IRelationDbManipulator manipulator, uint prefixFieldCount, EnumerationOrder order, KeyProposition startKeyProposition, int prefixLen, in ReadOnlySpan<byte> startKeyBytes, KeyProposition endKeyProposition, in ReadOnlySpan<byte> endKeyBytes, uint secondaryKeyIndex, int loaderIndex) : base(manipulator, prefixFieldCount, order, startKeyProposition, prefixLen, startKeyBytes, endKeyProposition, endKeyBytes, loaderIndex) { _secondaryKeyIndex = secondaryKeyIndex; } // ReSharper disable once UnusedMember.Global public RelationAdvancedSecondaryKeyEnumerator( IRelationDbManipulator manipulator, in ReadOnlySpan<byte> prefixBytes, uint prefixFieldCount, uint secondaryKeyIndex, int loaderIndex) : base(manipulator, prefixBytes, prefixFieldCount, loaderIndex) { _secondaryKeyIndex = secondaryKeyIndex; } protected override T CreateInstance(in ReadOnlySpan<byte> keyBytes) { return (T)Manipulator.CreateInstanceFromSecondaryKey(ItemLoader, _secondaryKeyIndex, PrefixFieldCount, KeyBytes, keyBytes.Slice(KeyBytes.Length)); } } public class RelationAdvancedOrderedEnumerator<TKey, TValue> : IOrderedDictionaryEnumerator<TKey, TValue> { protected readonly uint PrefixFieldCount; protected readonly IRelationDbManipulator Manipulator; protected readonly RelationInfo.ItemLoaderInfo ItemLoader; readonly IInternalObjectDBTransaction _tr; readonly IKeyValueDBTransaction _keyValueTr; long _prevProtectionCounter; readonly uint _startPos; readonly uint _count; uint _pos; SeekState _seekState; readonly bool _ascending; protected readonly byte[] KeyBytes; protected ReaderFun<TKey>? KeyReader; public RelationAdvancedOrderedEnumerator(IRelationDbManipulator manipulator, uint prefixFieldCount, EnumerationOrder order, KeyProposition startKeyProposition, int prefixLen, in ReadOnlySpan<byte> startKeyBytes, KeyProposition endKeyProposition, in ReadOnlySpan<byte> endKeyBytes, bool initKeyReader, int loaderIndex) { PrefixFieldCount = prefixFieldCount; Manipulator = manipulator; ItemLoader = Manipulator.RelationInfo.ItemLoaderInfos[loaderIndex]; _ascending = order == EnumerationOrder.Ascending; _tr = manipulator.Transaction; _keyValueTr = _tr.KeyValueDBTransaction; _prevProtectionCounter = _keyValueTr.CursorMovedCounter; KeyBytes = startKeyBytes.Slice(0, prefixLen).ToArray(); var realEndKeyBytes = endKeyBytes; if (endKeyProposition == KeyProposition.Included) realEndKeyBytes = RelationAdvancedEnumerator<TValue>.FindLastKeyWithPrefix(endKeyBytes, _keyValueTr); _keyValueTr.FindFirstKey(startKeyBytes.Slice(0, prefixLen)); var prefixIndex = _keyValueTr.GetKeyIndex(); if (prefixIndex == -1) { _count = 0; _startPos = 0; _pos = 0; _seekState = SeekState.Undefined; return; } long startIndex; long endIndex; if (endKeyProposition == KeyProposition.Ignored) { _keyValueTr.FindLastKey(startKeyBytes.Slice(0, prefixLen)); endIndex = _keyValueTr.GetKeyIndex() - prefixIndex; } else { switch (_keyValueTr.Find(realEndKeyBytes, (uint)prefixLen)) { case FindResult.Exact: endIndex = _keyValueTr.GetKeyIndex() - prefixIndex; if (endKeyProposition == KeyProposition.Excluded) { endIndex--; } break; case FindResult.Previous: endIndex = _keyValueTr.GetKeyIndex() - prefixIndex; break; case FindResult.Next: endIndex = _keyValueTr.GetKeyIndex() - prefixIndex - 1; break; case FindResult.NotFound: endIndex = -1; break; default: throw new ArgumentOutOfRangeException(); } } if (startKeyProposition == KeyProposition.Ignored) { startIndex = 0; } else { switch (_keyValueTr.Find(startKeyBytes, (uint)prefixLen)) { case FindResult.Exact: startIndex = _keyValueTr.GetKeyIndex() - prefixIndex; if (startKeyProposition == KeyProposition.Excluded) { startIndex++; } break; case FindResult.Previous: startIndex = _keyValueTr.GetKeyIndex() - prefixIndex + 1; break; case FindResult.Next: startIndex = _keyValueTr.GetKeyIndex() - prefixIndex; break; case FindResult.NotFound: startIndex = 0; break; default: throw new ArgumentOutOfRangeException(); } } _count = (uint)Math.Max(0, endIndex - startIndex + 1); _startPos = (uint)(_ascending ? startIndex : endIndex); _pos = 0; _seekState = SeekState.Undefined; if (initKeyReader) { var primaryKeyFields = manipulator.RelationInfo.ClientRelationVersionInfo.PrimaryKeyFields; var advancedEnumParamField = primaryKeyFields.Span[(int)PrefixFieldCount]; if (advancedEnumParamField.Handler!.NeedsCtx()) throw new BTDBException("Not supported."); KeyReader = (ReaderFun<TKey>)manipulator.RelationInfo .GetSimpleLoader(new RelationInfo.SimpleLoaderType(advancedEnumParamField.Handler, typeof(TKey))); } } public uint Count => _count; protected virtual TValue CreateInstance(in ReadOnlySpan<byte> keyBytes) { return (TValue)ItemLoader.CreateInstance(_tr, keyBytes, _keyValueTr); } public TValue CurrentValue { get { if (_pos >= _count) throw new IndexOutOfRangeException(); if (_seekState == SeekState.Undefined) throw new BTDBException("Invalid access to uninitialized CurrentValue."); if (_keyValueTr.CursorMovedCounter != _prevProtectionCounter) { Seek(); } else if (_seekState != SeekState.Ready) { Seek(); } _prevProtectionCounter = _keyValueTr.CursorMovedCounter; var keyBytes = _keyValueTr.GetKey(); return CreateInstance(keyBytes); } set => throw new NotSupportedException(); } void Seek() { if (_ascending) _keyValueTr.SetKeyIndex(KeyBytes, _startPos + _pos); else _keyValueTr.SetKeyIndex(KeyBytes, _startPos - _pos); _seekState = SeekState.Ready; } public uint Position { get => _pos; set { _pos = value > _count ? _count : value; _seekState = SeekState.SeekNeeded; } } [SkipLocalsInit] public bool NextKey(out TKey key) { if (_seekState == SeekState.Ready) _pos++; if (_pos >= _count) { key = default; return false; } if (_keyValueTr.CursorMovedCounter != _prevProtectionCounter) { Seek(); } else if (_seekState != SeekState.Ready) { Seek(); } else { if (_ascending) { _keyValueTr.FindNextKey(KeyBytes); } else { _keyValueTr.FindPreviousKey(KeyBytes); } } _prevProtectionCounter = _keyValueTr.CursorMovedCounter; Span<byte> keyBuffer = stackalloc byte[512]; var reader = new SpanReader(_keyValueTr.GetKey(ref MemoryMarshal.GetReference(keyBuffer), keyBuffer.Length).Slice(KeyBytes.Length)); key = KeyReader!(ref reader, null); return true; } } public class RelationAdvancedOrderedSecondaryKeyEnumerator<TKey, TValue> : RelationAdvancedOrderedEnumerator<TKey, TValue> { readonly uint _secondaryKeyIndex; public RelationAdvancedOrderedSecondaryKeyEnumerator(IRelationDbManipulator manipulator, uint prefixFieldCount, EnumerationOrder order, KeyProposition startKeyProposition, int prefixLen, in ReadOnlySpan<byte> startKeyBytes, KeyProposition endKeyProposition, in ReadOnlySpan<byte> endKeyBytes, uint secondaryKeyIndex, int loaderIndex) : base(manipulator, prefixFieldCount, order, startKeyProposition, prefixLen, startKeyBytes, endKeyProposition, endKeyBytes, false, loaderIndex) { _secondaryKeyIndex = secondaryKeyIndex; var secKeyFields = manipulator.RelationInfo.ClientRelationVersionInfo.GetSecondaryKeyFields(secondaryKeyIndex); var advancedEnumParamField = secKeyFields[(int)PrefixFieldCount]; if (advancedEnumParamField.Handler!.NeedsCtx()) throw new BTDBException("Not supported."); KeyReader = (ReaderFun<TKey>)manipulator.RelationInfo .GetSimpleLoader(new RelationInfo.SimpleLoaderType(advancedEnumParamField.Handler, typeof(TKey))); } protected override TValue CreateInstance(in ReadOnlySpan<byte> keyBytes) { return (TValue)Manipulator.CreateInstanceFromSecondaryKey(ItemLoader, _secondaryKeyIndex, PrefixFieldCount, KeyBytes, keyBytes.Slice(KeyBytes.Length)); } } }
using fyiReporting.RDL; /* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections.Generic; using System.ComponentModel; // need this for the properties metadata using System.Globalization; using System.Xml; namespace fyiReporting.RdlDesign { /// <summary> /// PropertyChart - The Chart Properties /// </summary> internal class PropertyChart : PropertyDataRegion { internal PropertyChart(DesignXmlDraw d, DesignCtl dc, List<XmlNode> ris) : base(d, dc, ris) { } [LocalizedCategory("Chart")] [TypeConverter(typeof(ChartTypeConverter))] [LocalizedDisplayName("Chart_Type")] [LocalizedDescription("Chart_Type")] public string Type { get { return this.GetValue("Type", "Column"); } set { this.SetValue("Type", value); } } [LocalizedCategory("Chart")] [TypeConverter(typeof(PaletteTypeConverter))] [LocalizedDisplayName("Chart_Palette")] [LocalizedDescription("Chart_Palette")] public string Palette { get { return this.GetValue("Palette", "Default"); } set { this.SetValue("Palette", value); } } [LocalizedCategory("Chart")] [LocalizedDisplayName("Chart_PointWidth")] [LocalizedDescription("Chart_PointWidth")] public int PointWidth { get { int pw = 100; try { string spw = this.GetValue("PointWidth", "100"); pw = Convert.ToInt32(spw); } catch { } return pw; } set { if (value <= 0) throw new ArgumentException("PointWidth must be greater than 0."); this.SetValue("PointWidth", value.ToString()); } } [LocalizedCategory("Chart")] [LocalizedDisplayName("Chart_ChartData")] [LocalizedDescription("Chart_ChartData")] public PropertyChartData ChartData { get { return new PropertyChartData(this);} } [LocalizedCategory("Chart")] [TypeConverter(typeof(ChartTitleTypeConverter))] [LocalizedDisplayName("Chart_Title")] [LocalizedDescription("Chart_Title")] public PropertyChartTitle Title { get { return new PropertyChartTitle(this); } } [LocalizedCategory("Chart")] [TypeConverter(typeof(ChartLegendTypeConverter))] [LocalizedDisplayName("Chart_Legend")] [LocalizedDescription("Chart_Legend")] public PropertyChartLegend Legend { get { return new PropertyChartLegend(this); } } [LocalizedCategory("Chart")] [TypeConverter(typeof(ChartAxisTypeConverter))] [LocalizedDisplayName("Chart_CategoryAxis")] [LocalizedDescription("Chart_CategoryAxis")] public PropertyChartAxis CategoryAxis { get { return new PropertyChartAxis(this, "CategoryAxis"); } } [LocalizedCategory("Chart")] [TypeConverter(typeof(ChartAxisTypeConverter))] [LocalizedDisplayName("Chart_ValueAxis")] [LocalizedDescription("Chart_ValueAxis")] public PropertyChartAxis ValueAxis { get { return new PropertyChartAxis(this, "ValueAxis"); } } } #region ChartAxis [TypeConverter(typeof(ChartAxisTypeConverter))] [LocalizedDescription("ChartAxis")] internal class PropertyChartAxis : IReportItem { PropertyChart _pt; string _Axis; internal PropertyChartAxis(PropertyChart pt, string axis) { _pt = pt; _Axis = axis; } [LocalizedDisplayName("ChartAxis_Visible")] [LocalizedDescription("ChartAxis_Visible")] public bool Visible { get { string v = _pt.GetWithList("true", _Axis, "Axis", "Visible"); return v == "true"; } set { _pt.SetWithList(value ? "true" : "false", _Axis, "Axis", "Visible"); } } [LocalizedDisplayName("ChartAxis_Margin")] [LocalizedDescription("ChartAxis_Margin")] public bool Margin { get { string v = _pt.GetWithList("false", _Axis, "Axis", "Margin"); return v == "true"; } set { _pt.SetWithList(value ? "true" : "false", _Axis, "Axis", "Margin"); } } [LocalizedDisplayName("ChartAxis_MajorTickMarks")] [LocalizedDescription("ChartAxis_MajorTickMarks")] public AxisTickMarksEnum MajorTickMarks { get { string v = _pt.GetWithList("None", _Axis, "Axis", "MajorTickMarks"); return AxisTickMarks.GetStyle(v); } set { _pt.SetWithList(value.ToString(), _Axis, "Axis", "MajorTickMarks"); } } [LocalizedDisplayName("ChartAxis_MinorTickMarks")] [LocalizedDescription("ChartAxis_MinorTickMarks")] public AxisTickMarksEnum MinorTickMarks { get { string v = _pt.GetWithList("None", _Axis, "Axis", "MinorTickMarks"); return AxisTickMarks.GetStyle(v); } set { _pt.SetWithList(value.ToString(), _Axis, "Axis", "MinorTickMarks"); } } [LocalizedDisplayName("ChartAxis_MajorInterval")] [LocalizedDescription("ChartAxis_MajorInterval")] public PropertyExpr MajorInterval { get { string v = _pt.GetWithList("", _Axis, "Axis", "MajorInterval"); return new PropertyExpr(v); } set { _pt.SetWithList(value.Expression, _Axis, "Axis", "MajorInterval"); } } [LocalizedDisplayName("ChartAxis_MinorInterval")] [LocalizedDescription("ChartAxis_MinorInterval")] public PropertyExpr MinorInterval { get { string v = _pt.GetWithList("", _Axis, "Axis", "MinorInterval"); return new PropertyExpr(v); } set { _pt.SetWithList(value.Expression, _Axis, "Axis", "MinorInterval"); } } [LocalizedDisplayName("ChartAxis_CrossAt")] [LocalizedDescription("ChartAxis_CrossAt")] public PropertyExpr CrossAt { get { string v = _pt.GetWithList("", _Axis, "Axis", "CrossAt"); return new PropertyExpr(v); } set { _pt.SetWithList(value.Expression, _Axis, "Axis", "CrossAt"); } } [LocalizedDisplayName("ChartAxis_Min")] [LocalizedDescription("ChartAxis_Min")] public PropertyExpr Min { get { string v = _pt.GetWithList("", _Axis, "Axis", "Min"); return new PropertyExpr(v); } set { _pt.SetWithList(value.Expression, _Axis, "Axis", "Min"); } } [LocalizedDisplayName("ChartAxis_Max")] [LocalizedDescription("ChartAxis_Max")] public PropertyExpr Max { get { string v = _pt.GetWithList("", _Axis, "Axis", "Max"); return new PropertyExpr(v); } set { _pt.SetWithList(value.Expression, _Axis, "Axis", "Max"); } } [LocalizedDisplayName("ChartAxis_Reverse")] [LocalizedDescription("ChartAxis_Reverse")] public bool Reverse { get { string v = _pt.GetWithList("false", _Axis, "Axis", "Reverse"); return v == "true"; } set { _pt.SetWithList(value ? "true" : "false", _Axis, "Axis", "Reverse"); } } [LocalizedDisplayName("ChartAxis_Interlaced")] [LocalizedDescription("ChartAxis_Interlaced")] public bool Interlaced { get { string v = _pt.GetWithList("false", _Axis, "Axis", "Interlaced"); return v == "true"; } set { _pt.SetWithList(value ? "true" : "false", _Axis, "Axis", "Interlaced"); } } [LocalizedDisplayName("ChartAxis_Scalar")] [LocalizedDescription("ChartAxis_Scalar")] public bool Scalar { get { string v = _pt.GetWithList("false", _Axis, "Axis", "Scalar"); return v == "true"; } set { _pt.SetWithList(value ? "true" : "false", _Axis, "Axis", "Scalar"); } } [LocalizedDisplayName("ChartAxis_LogScale")] [LocalizedDescription("ChartAxis_LogScale")] public bool LogScale { get { string v = _pt.GetWithList("false", _Axis, "Axis", "LogScale"); return v == "true"; } set { _pt.SetWithList(value ? "true" : "false", _Axis, "Axis", "LogScale"); } } [LocalizedDisplayName("ChartAxis_Title")] [LocalizedDescription("ChartAxis_Title")] public PropertyChartTitle Title { get { return new PropertyChartTitle(_pt, _Axis, "Axis"); } } [LocalizedDisplayName("ChartAxis_Appearance")] [LocalizedDescription("ChartAxis_Appearance")] public PropertyAppearance Appearance { get { return new PropertyAppearance(_pt, _Axis, "Axis"); } } [LocalizedDisplayName("ChartAxis_Background")] [LocalizedDescription("ChartAxis_Background")] public PropertyBackground Background { get { return new PropertyBackground(_pt, _Axis, "Axis"); } } [LocalizedDisplayName("ChartAxis_Border")] [LocalizedDescription("ChartAxis_Border")] public PropertyBorder Border { get { return new PropertyBorder(_pt, _Axis, "Axis"); } } [LocalizedDisplayName("ChartAxis_Padding")] [LocalizedDescription("ChartAxis_Padding")] public PropertyPadding Padding { get { return new PropertyPadding(_pt, _Axis, "Axis"); } } [LocalizedDisplayName("ChartAxis_MajorGridLines")] [LocalizedDescription("ChartAxis_MajorGridLines")] public PropertyChartGridLines MajorGridLines { get { return new PropertyChartGridLines(_pt, _Axis, "Axis", "MajorGridLines"); } } [LocalizedDisplayName("ChartAxis_MinorGridLines")] [LocalizedDescription("ChartAxis_MinorGridLines")] public PropertyChartGridLines MinorGridLines { get { return new PropertyChartGridLines(_pt, _Axis, "Axis", "MinorGridLines"); } } public override string ToString() { if (!this.Visible) return "hidden"; else return this.Title.Caption.Expression; } #region IReportItem Members public PropertyReportItem GetPRI() { return this._pt; } #endregion } internal class ChartAxisTypeConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyChartAxis)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyChartAxis) { PropertyChartAxis pa = value as PropertyChartAxis; return pa.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } #endregion #region ChartData [LocalizedCategory("ChartData")] [TypeConverter(typeof(ChartDataTypeConverter))] [LocalizedDescription("ChartData")] [ReadOnly(true)]//Doesn't work with static rows so we have disabled it... 05122007 AJM & GJL internal class PropertyChartData : IReportItem { PropertyChart _pt; internal PropertyChartData(PropertyChart pt) { _pt = pt; } [LocalizedDisplayName("ChartData_LabelAppearance")] [LocalizedDescription("ChartData_LabelAppearance")] public PropertyAppearance LabelAppearance { get { return new PropertyAppearance(_pt, "ChartData", "ChartSeries", "DataPoints", "DataPoint", "DataLabel"); } } [LocalizedDisplayName("ChartData_LabelVisible")] [LocalizedDescription("ChartData_LabelVisible")] public bool LabelVisible { get { string cdata = _pt.GetWithList("false", "ChartData", "ChartSeries", "DataPoints", "DataPoint", "DataLabel", "Visible"); return cdata.ToLower() == "true"; } set { _pt.SetWithList(value? "true": "false", "ChartData", "ChartSeries", "DataPoints", "DataPoint", "DataLabel", "Visible"); } } [LocalizedDisplayName("ChartData_DataValue")] [LocalizedDescription("ChartData_DataValue")] public PropertyExpr DataValue { get { // Chart data-- this is a simplification of what is possible (TODO) // <ChartData> // <ChartSeries> // <DataPoints> // <DataPoint> // <DataValues> // <DataValue> // <Value>=Sum(Fields!Sales.Value)</Value> // </DataValue> // </DataValues> // <DataLabel> // <Style> // <Format>c</Format> // </Style> // </DataLabel> // <Marker /> // </DataPoint> // </DataPoints> // </ChartSeries> // </ChartData> string cdata = _pt.GetWithList("", "ChartData", "ChartSeries", "DataPoints", "DataPoint", "DataValues", "DataValue", "Value"); return new PropertyExpr(cdata); } set { _pt.SetWithList(value.Expression, "ChartData", "ChartSeries", "DataPoints", "DataPoint", "DataValues", "DataValue", "Value"); } } [LocalizedDisplayName("ChartData_DataValue2")] [LocalizedDescription("ChartData_DataValue2")] public PropertyExpr DataValue2 { get { // Chart data-- this is a simplification of what is possible (TODO) // <ChartData> // <ChartSeries> // <DataPoints> // <DataPoint> // <DataValues> // <DataValue> // <Value>=Sum(Fields!Sales.Value)</Value> // </DataValue> // <DataValue> ---- this is the second data value // <Value>=Sum(Fields!Sales.Value)</Value> // </DataValue> // </DataValues> // <DataLabel> // <Style> // <Format>c</Format> // </Style> // </DataLabel> // <Marker /> // </DataPoint> // </DataPoints> // </ChartSeries> // </ChartData> string type = _pt.Type.ToLowerInvariant(); if (!(type == "scatter" || type == "bubble")) return new PropertyExpr(""); return new PropertyExpr(GetChartDataValue(2)); } set { string type = _pt.Type.ToLowerInvariant(); if (!(type == "scatter" || type == "bubble")) throw new ArgumentException("Chart type must be 'Scatter' or 'Bubble' to set DataValue2."); ; SetChartDataValue(2, value.Expression); } } [LocalizedDisplayName("ChartData_DataValue3")] [LocalizedDescription("ChartData_DataValue3")] public PropertyExpr DataValue3 { get { // Chart data-- this is a simplification of what is possible // <ChartData> // <ChartSeries> // <DataPoints> // <DataPoint> // <DataValues> // <DataValue> // <Value>=Sum(Fields!Sales.Value)</Value> // </DataValue> // <DataValue> // <Value>=Sum(Fields!Sales.Value)</Value> // </DataValue> // <DataValue> ---- this is the third data value-- bubble size // <Value>=Sum(Fields!Sales.Value)</Value> // </DataValue> // </DataValues> // <DataLabel> // <Style> // <Format>c</Format> // </Style> // </DataLabel> // <Marker /> // </DataPoint> // </DataPoints> // </ChartSeries> // </ChartData> string type = _pt.Type.ToLowerInvariant(); if (type != "bubble") return new PropertyExpr(""); return new PropertyExpr(GetChartDataValue(3)); } set { string type = _pt.Type.ToLowerInvariant(); if (type != "bubble") throw new ArgumentException("Chart type must be 'Bubble' to set DataValue3."); ; SetChartDataValue(3, value.Expression); } } private string GetChartDataValue(int i) { XmlNode dvs = DesignXmlDraw.FindNextInHierarchy(_pt.Node, "ChartData", "ChartSeries", "DataPoints", "DataPoint", "DataValues"); XmlNode cnode; foreach (XmlNode dv in dvs.ChildNodes) { if (dv.Name != "DataValue") continue; i--; cnode = DesignXmlDraw.FindNextInHierarchy(dv, "Value"); if (cnode == null) continue; if (i <= 0) return cnode.InnerText; } return ""; } private void SetChartDataValue(int i, string expr) { DesignXmlDraw dr = _pt.Draw; string expr1 = i == 1 ? expr : _pt.ChartData.DataValue.Expression; string expr2 = i == 2 ? expr : _pt.ChartData.DataValue2.Expression; string expr3 = i == 3 ? expr : _pt.ChartData.DataValue3.Expression; foreach (XmlNode node in _pt.Nodes) { XmlNode chartdata = dr.SetElement(node, "ChartData", null); XmlNode chartseries = dr.SetElement(chartdata, "ChartSeries", null); XmlNode datapoints = dr.SetElement(chartseries, "DataPoints", null); XmlNode datapoint = dr.SetElement(datapoints, "DataPoint", null); XmlNode datavalues = dr.SetElement(datapoint, "DataValues", null); dr.RemoveElementAll(datavalues, "DataValue"); XmlNode datavalue = dr.SetElement(datavalues, "DataValue", null); dr.SetElement(datavalue, "Value", expr1); string type = _pt.Type.ToLowerInvariant(); if (type == "scatter" || type == "bubble") { datavalue = dr.CreateElement(datavalues, "DataValue", null); dr.SetElement(datavalue, "Value", expr2); if (type == "bubble") { datavalue = dr.CreateElement(datavalues, "DataValue", null); dr.SetElement(datavalue, "Value", expr3); } } } } public override string ToString() { return _pt.GetWithList("", "ChartData", "ChartSeries", "DataPoints", "DataPoint", "DataValues", "DataValue", "Value"); } #region IReportItem Members public PropertyReportItem GetPRI() { return this._pt; } #endregion } internal class ChartDataTypeConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyChartData)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyChartData) { PropertyChartData pc = value as PropertyChartData; return pc.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } #endregion #region ChartGridLines [TypeConverter(typeof(ChartGridLinesTypeConverter))] internal class PropertyChartGridLines : IReportItem { PropertyChart _pt; string[] _names; internal PropertyChartGridLines(PropertyChart pt, params string[] names) { _pt = pt; _names = names; } [RefreshProperties(RefreshProperties.Repaint)] [LocalizedDisplayName("ChartGridLines_ShowGridLines")] [LocalizedDescription("ChartGridLines_ShowGridLines")] public bool ShowGridLines { get { List<string> l = new List<string>(_names); l.Add("ShowGridLines"); string s = _pt.GetWithList("false", l.ToArray()); return s == "true"; } set { List<string> l = new List<string>(_names); l.Add("ShowGridLines"); _pt.SetWithList(value?"true":"false", l.ToArray()); } } [TypeConverter(typeof(ColorConverter))] [LocalizedDisplayName("ChartGridLines_Color")] [LocalizedDescription("ChartGridLines_Color")] public string Color { get { List<string> l = new List<string>(_names); l.Add("Style"); l.Add("BorderColor"); l.Add("Default"); return _pt.GetWithList("Black", l.ToArray()); } set { List<string> l = new List<string>(_names); l.Add("Style"); l.Add("BorderColor"); l.Add("Default"); _pt.SetWithList(value, l.ToArray()); } } [LocalizedDisplayName("ChartGridLines_LineStyle")] [LocalizedDescription("ChartGridLines_LineStyle")] public LineStyleEnum LineStyle { get { List<string> l = new List<string>(_names); l.Add("Style"); l.Add("BorderStyle"); l.Add("Default"); string s = _pt.GetWithList("Solid", l.ToArray()); switch (s) { case "Solid": return LineStyleEnum.Solid; case "Dotted": return LineStyleEnum.Dotted; case "Dashed": return LineStyleEnum.Dashed; default: return LineStyleEnum.Solid; } } set { List<string> l = new List<string>(_names); l.Add("Style"); l.Add("BorderStyle"); l.Add("Default"); _pt.SetWithList(value.ToString(), l.ToArray()); } } [LocalizedDisplayName("ChartGridLines_Width")] [LocalizedDescription("ChartGridLines_Width")] public PropertyExpr Width { get { List<string> l = new List<string>(_names); l.Add("Style"); l.Add("BorderWidth"); l.Add("Default"); return new PropertyExpr(_pt.GetWithList("1pt", l.ToArray())); } set { List<string> l = new List<string>(_names); l.Add("Style"); l.Add("BorderWidth"); l.Add("Default"); _pt.SetWithList(value.Expression, l.ToArray()); } } public override string ToString() { return this.ShowGridLines?"visible":"hidden"; } #region IReportItem Members public PropertyReportItem GetPRI() { return this._pt; } #endregion } internal class ChartGridLinesTypeConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyChartGridLines)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyChartGridLines) { PropertyChartGridLines pf = value as PropertyChartGridLines; return pf.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } #endregion #region ChartLegend [LocalizedCategory("ChartLegend")] [TypeConverter(typeof(ChartLegendTypeConverter))] [LocalizedDescription("ChartLegend")] internal class PropertyChartLegend : IReportItem { PropertyChart _pt; internal PropertyChartLegend(PropertyChart pt) { _pt = pt; } [LocalizedDisplayName("ChartLegend_Visible")] [LocalizedDescription("ChartLegend_Visible")] public bool Visible { get { string v = _pt.GetWithList("true", "Legend", "Visible"); return v == "true"; } set { _pt.SetWithList(value ? "true" : "false", "Legend", "Visible"); } } [LocalizedDisplayName("ChartLegend_Position")] [LocalizedDescription("ChartLegend_Position")] public LegendPositionEnum Position { get { string v = _pt.GetWithList("RightTop", "Legend", "Position"); return LegendPosition.GetStyle(v); } set { _pt.SetWithList(value.ToString(), "Legend", "Position"); } } [LocalizedDisplayName("ChartLegend_Layout")] [LocalizedDescription("ChartLegend_Layout")] public LegendLayoutEnum Layout { get { string v = _pt.GetWithList("Column", "Legend", "Layout"); return LegendLayout.GetStyle(v); } set { _pt.SetWithList(value.ToString(), "Legend", "Layout"); } } [LocalizedDisplayName("ChartLegend_InsidePlotArea")] [LocalizedDescription("ChartLegend_InsidePlotArea")] public bool InsidePlotArea { get { string v = _pt.GetWithList("true", "Legend", "InsidePlotArea"); return v.ToLower() == "true"; } set { _pt.SetWithList(value ? "true" : "false", "Legend", "InsidePlotArea"); } } [LocalizedDisplayName("ChartLegend_Appearance")] [LocalizedDescription("ChartLegend_Appearance")] public PropertyAppearance Appearance { get { return new PropertyAppearance(_pt, "Legend"); } } [LocalizedDisplayName("ChartLegend_Background")] [LocalizedDescription("ChartLegend_Background")] public PropertyBackground Background { get { return new PropertyBackground(_pt, "Legend"); } } [LocalizedDisplayName("ChartLegend_Border")] [LocalizedDescription("ChartLegend_Border")] public PropertyBorder Border { get { return new PropertyBorder(_pt, "Legend"); } } [LocalizedDisplayName("ChartLegend_Padding")] [LocalizedDescription("ChartLegend_Padding")] public PropertyPadding Padding { get { return new PropertyPadding(_pt, "Legend"); } } public override string ToString() { //return _pt.GetWithList("", "Title", "Caption"); if (!this.Visible) return "hidden"; else return this.Position.ToString(); } #region IReportItem Members public PropertyReportItem GetPRI() { return this._pt; } #endregion } internal class ChartLegendTypeConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyChartLegend)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyChartLegend) { PropertyChartLegend pf = value as PropertyChartLegend; return pf.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } #endregion #region ChartTitle [LocalizedCategory("ChartTitle")] [TypeConverter(typeof(ChartTitleTypeConverter))] [LocalizedDescription("ChartTitle")] internal class PropertyChartTitle : IReportItem { PropertyChart _pt; string[] _subitems; string[] _names; internal PropertyChartTitle(PropertyChart pt) { _pt = pt; _names = null; _subitems = new string[] { "Title"}; } internal PropertyChartTitle(PropertyChart pt, params string[] names) { _pt = pt; _names = names; // now build the array used to get/set values _subitems = new string[names.Length + 1]; int i = 0; foreach (string s in names) _subitems[i++] = s; _subitems[i++] = "Title"; } [RefreshProperties(RefreshProperties.Repaint)] [LocalizedDisplayName("ChartTitle_Caption")] [LocalizedDescription("ChartTitle_Caption")] public PropertyExpr Caption { get { List<string> l = new List<string>(_subitems); l.Add("Caption"); return new PropertyExpr(_pt.GetWithList("", l.ToArray())); } set { List<string> l = new List<string>(_subitems); l.Add("Caption"); _pt.SetWithList(value.Expression, l.ToArray()); } } [LocalizedDisplayName("ChartTitle_Appearance")] [LocalizedDescription("ChartTitle_Appearance")] public PropertyAppearance Appearance { get { return new PropertyAppearance(_pt, _subitems); } } [LocalizedDisplayName("ChartTitle_Background")] [LocalizedDescription("ChartTitle_Background")] public PropertyBackground Background { get { return new PropertyBackground(_pt, _subitems); } } [LocalizedDisplayName("ChartTitle_Border")] [LocalizedDescription("ChartTitle_Border")] public PropertyBorder Border { get { return new PropertyBorder(_pt, _subitems); } } [LocalizedDisplayName("ChartTitle_Padding")] [LocalizedDescription("ChartTitle_Padding")] public PropertyPadding Padding { get { return new PropertyPadding(_pt, _subitems); } } public override string ToString() { return this.Caption.Expression; } #region IReportItem Members public PropertyReportItem GetPRI() { return this._pt; } #endregion } internal class ChartTitleTypeConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyChartTitle)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyChartTitle) { PropertyChartTitle pf = value as PropertyChartTitle; return pf.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } #endregion #region ChartType internal class ChartTypeConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new string[] { "Column", "Bar", "Line", "Map", "Pie", "Area", "Doughnut", "Bubble", "Scatter"}); } } #endregion #region PaletteType internal class PaletteTypeConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new string[] { "Default", "EarthTones", "Excel", "GrayScale", "Light", "Pastel", "SemiTransparent","Patterned","PatternedBlack","Custom"}); } } #endregion internal enum LineStyleEnum {Solid, Dotted, Dashed }; }
using UnityEngine; [ExecuteInEditMode] public class MegaAttach : MonoBehaviour { public MegaModifiers target; [HideInInspector] public Vector3 BaryCoord = Vector3.zero; [HideInInspector] public int[] BaryVerts = new int[3]; [HideInInspector] public bool attached = false; [HideInInspector] public Vector3 BaryCoord1 = Vector3.zero; [HideInInspector] public int[] BaryVerts1 = new int[3]; public Vector3 attachforward = Vector3.forward; public Vector3 AxisRot = Vector3.zero; public float radius = 0.1f; public Vector3 up = Vector3.up; public bool worldSpace = false; Vector3 pt = Vector3.zero; Vector3 norm = Vector3.zero; public bool skinned; #if UNITY_5_OR_NEWER public bool usebakedmesh = true; #endif [ContextMenu("Help")] public void Help() { Application.OpenURL("http://www.west-racing.com/mf/?page_id=2645"); } public void DetachIt() { attached = false; } public void AttachIt() { if ( target ) { attached = true; if ( !InitSkin() ) { Mesh mesh = target.mesh; Vector3 objSpacePt = target.transform.InverseTransformPoint(pt); Vector3[] verts = target.sverts; int[] tris = mesh.triangles; int index = -1; MegaNearestPointTest.NearestPointOnMesh1(objSpacePt, verts, tris, ref index, ref BaryCoord); if ( index >= 0 ) { BaryVerts[0] = tris[index]; BaryVerts[1] = tris[index + 1]; BaryVerts[2] = tris[index + 2]; } MegaNearestPointTest.NearestPointOnMesh1(objSpacePt + attachforward, verts, tris, ref index, ref BaryCoord1); if ( index >= 0 ) { BaryVerts1[0] = tris[index]; BaryVerts1[1] = tris[index + 1]; BaryVerts1[2] = tris[index + 2]; } } } } public void AttachIt(Vector3 pos) { pt = pos; AttachIt(); } void OnDrawGizmosSelected() { pt = transform.position; Gizmos.color = Color.white; Gizmos.DrawSphere(pt, radius); if ( target ) { if ( attached ) { SkinnedMeshRenderer skin = target.GetComponent<SkinnedMeshRenderer>(); if ( skin ) { Vector3 pos = transform.position; Vector3 worldPt = pos; Gizmos.color = Color.green; Gizmos.DrawSphere(worldPt, radius); } else { Vector3 pos = GetCoordMine(target.sverts[BaryVerts[0]], target.sverts[BaryVerts[1]], target.sverts[BaryVerts[2]], BaryCoord); Vector3 worldPt = target.transform.TransformPoint(pos); Gizmos.color = Color.green; Gizmos.DrawSphere(worldPt, radius); Vector3 nw = target.transform.TransformDirection(norm * 40.0f); Gizmos.DrawLine(worldPt, worldPt + nw); } } else { SkinnedMeshRenderer skin = target.GetComponent<SkinnedMeshRenderer>(); if ( skin ) { CalcSkinVerts(); Mesh mesh = target.mesh; Vector3 objSpacePt = pt; Vector3[] verts = calcskinverts; int[] tris = mesh.triangles; int index = -1; Vector3 tribary = Vector3.zero; Vector3 meshPt = MegaNearestPointTest.NearestPointOnMesh1(objSpacePt, verts, tris, ref index, ref tribary); Vector3 worldPt = target.transform.TransformPoint(meshPt); if ( index >= 0 ) { Vector3 cp2 = GetCoordMine(verts[tris[index]], verts[tris[index + 1]], verts[tris[index + 2]], tribary); worldPt = cp2; } Gizmos.color = Color.red; Gizmos.DrawSphere(worldPt, radius); Gizmos.color = Color.blue; meshPt = MegaNearestPointTest.NearestPointOnMesh1(objSpacePt + attachforward, verts, tris, ref index, ref tribary); Vector3 worldPt1 = meshPt; Gizmos.DrawSphere(worldPt1, radius); Gizmos.color = Color.yellow; Gizmos.DrawLine(worldPt, worldPt1); } else { Mesh mesh = target.mesh; Vector3 objSpacePt = target.transform.InverseTransformPoint(pt); Vector3[] verts = target.sverts; int[] tris = mesh.triangles; int index = -1; Vector3 tribary = Vector3.zero; Vector3 meshPt = MegaNearestPointTest.NearestPointOnMesh1(objSpacePt, verts, tris, ref index, ref tribary); Vector3 worldPt = target.transform.TransformPoint(meshPt); if ( index >= 0 ) { Vector3 cp2 = GetCoordMine(verts[tris[index]], verts[tris[index + 1]], verts[tris[index + 2]], tribary); worldPt = target.transform.TransformPoint(cp2); } Gizmos.color = Color.red; Gizmos.DrawSphere(worldPt, radius); Gizmos.color = Color.blue; meshPt = MegaNearestPointTest.NearestPointOnMesh1(objSpacePt + attachforward, verts, tris, ref index, ref tribary); Vector3 worldPt1 = target.transform.TransformPoint(meshPt); Gizmos.DrawSphere(worldPt1, radius); Gizmos.color = Color.yellow; Gizmos.DrawLine(worldPt, worldPt1); } } } } void LateUpdate() { if ( attached ) { if ( skinned ) { GetSkinPos1(); return; } if ( worldSpace ) { Vector3 v0 = target.sverts[BaryVerts[0]]; Vector3 v1 = target.sverts[BaryVerts[1]]; Vector3 v2 = target.sverts[BaryVerts[2]]; Vector3 pos = target.transform.localToWorldMatrix.MultiplyPoint(GetCoordMine(v0, v1, v2, BaryCoord)); transform.position = pos; // Rotation Vector3 va = v1 - v0; Vector3 vb = v2 - v1; norm = Vector3.Cross(va, vb); v0 = target.sverts[BaryVerts1[0]]; v1 = target.sverts[BaryVerts1[1]]; v2 = target.sverts[BaryVerts1[2]]; Vector3 fwd = target.transform.localToWorldMatrix.MultiplyPoint(GetCoordMine(v0, v1, v2, BaryCoord1)) - pos; Quaternion erot = Quaternion.Euler(AxisRot); Quaternion rot = Quaternion.LookRotation(fwd, norm) * erot; transform.rotation = rot; } else { Vector3 v0 = target.sverts[BaryVerts[0]]; Vector3 v1 = target.sverts[BaryVerts[1]]; Vector3 v2 = target.sverts[BaryVerts[2]]; Vector3 pos = GetCoordMine(v0, v1, v2, BaryCoord); transform.localPosition = pos; // Rotation Vector3 va = v1 - v0; Vector3 vb = v2 - v1; norm = Vector3.Cross(va, vb); v0 = target.sverts[BaryVerts1[0]]; v1 = target.sverts[BaryVerts1[1]]; v2 = target.sverts[BaryVerts1[2]]; Vector3 fwd = GetCoordMine(v0, v1, v2, BaryCoord1) - pos; Quaternion erot = Quaternion.Euler(AxisRot); Quaternion rot = Quaternion.LookRotation(fwd, norm) * erot; transform.localRotation = rot; } } } Vector3 GetCoordMine(Vector3 A, Vector3 B, Vector3 C, Vector3 bary) { Vector3 p = Vector3.zero; p.x = (bary.x * A.x) + (bary.y * B.x) + (bary.z * C.x); p.y = (bary.x * A.y) + (bary.y * B.y) + (bary.z * C.y); p.z = (bary.x * A.z) + (bary.y * B.z) + (bary.z * C.z); return p; } [System.Serializable] public class MegaSkinVert { public MegaSkinVert() { weights = new float[4]; bones = new Transform[4]; bindposes = new Matrix4x4[4]; } public float[] weights; public Transform[] bones; public Matrix4x4[] bindposes; public int vert; } public MegaSkinVert[] skinverts; bool InitSkin() { if ( target ) { SkinnedMeshRenderer skin = target.GetComponent<SkinnedMeshRenderer>(); if ( skin ) { Quaternion rot = transform.rotation; attachrot = Quaternion.identity; skinned = true; Mesh ms = skin.sharedMesh; Vector3 pt = transform.position; CalcSkinVerts(); Vector3 objSpacePt = pt; Vector3[] verts = calcskinverts; int[] tris = ms.triangles; int index = -1; MegaNearestPointTest.NearestPointOnMesh1(objSpacePt, verts, tris, ref index, ref BaryCoord); //ref tribary); if ( index >= 0 ) { BaryVerts[0] = tris[index]; BaryVerts[1] = tris[index + 1]; BaryVerts[2] = tris[index + 2]; } MegaNearestPointTest.NearestPointOnMesh1(objSpacePt + attachforward, verts, tris, ref index, ref BaryCoord1); if ( index >= 0 ) { BaryVerts1[0] = tris[index]; BaryVerts1[1] = tris[index + 1]; BaryVerts1[2] = tris[index + 2]; } skinverts = new MegaSkinVert[6]; for ( int i = 0; i < 3; i++ ) { int vert = BaryVerts[i]; BoneWeight bw = ms.boneWeights[vert]; skinverts[i] = new MegaSkinVert(); skinverts[i].vert = vert; skinverts[i].weights[0] = bw.weight0; skinverts[i].weights[1] = bw.weight1; skinverts[i].weights[2] = bw.weight2; skinverts[i].weights[3] = bw.weight3; skinverts[i].bones[0] = skin.bones[bw.boneIndex0]; skinverts[i].bones[1] = skin.bones[bw.boneIndex1]; skinverts[i].bones[2] = skin.bones[bw.boneIndex2]; skinverts[i].bones[3] = skin.bones[bw.boneIndex3]; skinverts[i].bindposes[0] = ms.bindposes[bw.boneIndex0]; skinverts[i].bindposes[1] = ms.bindposes[bw.boneIndex1]; skinverts[i].bindposes[2] = ms.bindposes[bw.boneIndex2]; skinverts[i].bindposes[3] = ms.bindposes[bw.boneIndex3]; } for ( int i = 3; i < 6; i++ ) { int vert = BaryVerts1[i - 3]; BoneWeight bw = ms.boneWeights[vert]; skinverts[i] = new MegaSkinVert(); skinverts[i].vert = vert; skinverts[i].weights[0] = bw.weight0; skinverts[i].weights[1] = bw.weight1; skinverts[i].weights[2] = bw.weight2; skinverts[i].weights[3] = bw.weight3; skinverts[i].bones[0] = skin.bones[bw.boneIndex0]; skinverts[i].bones[1] = skin.bones[bw.boneIndex1]; skinverts[i].bones[2] = skin.bones[bw.boneIndex2]; skinverts[i].bones[3] = skin.bones[bw.boneIndex3]; skinverts[i].bindposes[0] = ms.bindposes[bw.boneIndex0]; skinverts[i].bindposes[1] = ms.bindposes[bw.boneIndex1]; skinverts[i].bindposes[2] = ms.bindposes[bw.boneIndex2]; skinverts[i].bindposes[3] = ms.bindposes[bw.boneIndex3]; } GetSkinPos1(); attachrot = Quaternion.Inverse(transform.rotation) * rot; return true; } else skinned = false; } return false; } public Quaternion attachrot = Quaternion.identity; Vector3 GetSkinPos(int i) { Vector3 pos = target.sverts[skinverts[i].vert]; Vector3 bpos = skinverts[i].bindposes[0].MultiplyPoint(pos); Vector3 p = skinverts[i].bones[0].TransformPoint(bpos) * skinverts[i].weights[0]; bpos = skinverts[i].bindposes[1].MultiplyPoint(pos); p += skinverts[i].bones[1].TransformPoint(bpos) * skinverts[i].weights[1]; bpos = skinverts[i].bindposes[2].MultiplyPoint(pos); p += skinverts[i].bones[2].TransformPoint(bpos) * skinverts[i].weights[2]; bpos = skinverts[i].bindposes[3].MultiplyPoint(pos); p += skinverts[i].bones[3].TransformPoint(bpos) * skinverts[i].weights[3]; return p; } Vector3[] calcskinverts; void CalcSkinVerts() { if ( calcskinverts == null || calcskinverts.Length != target.sverts.Length ) calcskinverts = new Vector3[target.sverts.Length]; SkinnedMeshRenderer skin = target.GetComponent<SkinnedMeshRenderer>(); Mesh mesh = target.mesh; Matrix4x4[] bindposes = mesh.bindposes; BoneWeight[] boneweights = mesh.boneWeights; for ( int i = 0; i < target.sverts.Length; i++ ) { Vector3 p = Vector3.zero; Vector3 pos = target.sverts[i]; Vector3 bpos = bindposes[boneweights[i].boneIndex0].MultiplyPoint(pos); p += skin.bones[boneweights[i].boneIndex0].TransformPoint(bpos) * boneweights[i].weight0; bpos = bindposes[boneweights[i].boneIndex1].MultiplyPoint(pos); p += skin.bones[boneweights[i].boneIndex1].TransformPoint(bpos) * boneweights[i].weight1; bpos = bindposes[boneweights[i].boneIndex2].MultiplyPoint(pos); p += skin.bones[boneweights[i].boneIndex2].TransformPoint(bpos) * boneweights[i].weight2; bpos = bindposes[boneweights[i].boneIndex3].MultiplyPoint(pos); p += skin.bones[boneweights[i].boneIndex3].TransformPoint(bpos) * boneweights[i].weight3; calcskinverts[i] = p; } } void GetSkinPos1() { Vector3 v0 = GetSkinPos(0); Vector3 v1 = GetSkinPos(1); Vector3 v2 = GetSkinPos(2); Vector3 pos = GetCoordMine(v0, v1, v2, BaryCoord); transform.position = pos; Vector3 va = v1 - v0; Vector3 vb = v2 - v1; norm = Vector3.Cross(va, vb); v0 = GetSkinPos(3); v1 = GetSkinPos(4); v2 = GetSkinPos(5); Vector3 fwd = GetCoordMine(v0, v1, v2, BaryCoord1) - pos; Quaternion erot = Quaternion.Euler(AxisRot); Quaternion rot = Quaternion.LookRotation(fwd, norm) * erot * attachrot; transform.rotation = rot; } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Profiling; using Grpc.Core.Utils; using NUnit.Framework; namespace Grpc.Core.Tests { public class ClientServerTest { const string Host = "127.0.0.1"; MockServiceHelper helper; Server server; Channel channel; [SetUp] public void Init() { helper = new MockServiceHelper(Host); server = helper.GetServer(); server.Start(); channel = helper.GetChannel(); } [TearDown] public void Cleanup() { channel.ShutdownAsync().Wait(); server.ShutdownAsync().Wait(); } [Test] public async Task UnaryCall() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return request; }); Assert.AreEqual("ABC", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "ABC")); Assert.AreEqual("ABC", await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "ABC")); } [Test] public void UnaryCall_ServerHandlerThrows() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { throw new Exception("This was thrown on purpose by a test"); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unknown, ex2.Status.StatusCode); } [Test] public void UnaryCall_ServerHandlerThrowsRpcException() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { throw new RpcException(new Status(StatusCode.Unauthenticated, "")); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode); } [Test] public void UnaryCall_ServerHandlerSetsStatus() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { context.Status = new Status(StatusCode.Unauthenticated, ""); return ""; }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode); } [Test] public async Task ClientStreamingCall() { helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { string result = ""; await requestStream.ForEachAsync(async (request) => { result += request; }); await Task.Delay(100); return result; }); var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall()); await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" }); Assert.AreEqual("ABC", await call.ResponseAsync); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.IsNotNull(call.GetTrailers()); } [Test] public async Task ServerStreamingCall() { helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { await responseStream.WriteAllAsync(request.Split(new []{' '})); context.ResponseTrailers.Add("xyz", ""); }); var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "A B C"); CollectionAssert.AreEqual(new string[] { "A", "B", "C" }, await call.ResponseStream.ToListAsync()); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.IsNotNull("xyz", call.GetTrailers()[0].Key); } [Test] public async Task ServerStreamingCall_EndOfStreamIsIdempotent() { helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { }); var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), ""); Assert.IsFalse(await call.ResponseStream.MoveNext()); Assert.IsFalse(await call.ResponseStream.MoveNext()); } [Test] public async Task ServerStreamingCall_ErrorCanBeAwaitedTwice() { helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { context.Status = new Status(StatusCode.InvalidArgument, ""); }); var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), ""); var ex = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext()); Assert.AreEqual(StatusCode.InvalidArgument, ex.Status.StatusCode); // attempting MoveNext again should result in throwing the same exception. var ex2 = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext()); Assert.AreEqual(StatusCode.InvalidArgument, ex2.Status.StatusCode); } [Test] public async Task DuplexStreamingCall() { helper.DuplexStreamingHandler = new DuplexStreamingServerMethod<string, string>(async (requestStream, responseStream, context) => { while (await requestStream.MoveNext()) { await responseStream.WriteAsync(requestStream.Current); } context.ResponseTrailers.Add("xyz", "xyz-value"); }); var call = Calls.AsyncDuplexStreamingCall(helper.CreateDuplexStreamingCall()); await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" }); CollectionAssert.AreEqual(new string[] { "A", "B", "C" }, await call.ResponseStream.ToListAsync()); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.IsNotNull("xyz-value", call.GetTrailers()[0].Value); } [Test] public async Task ClientStreamingCall_CancelAfterBegin() { var barrier = new TaskCompletionSource<object>(); helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { barrier.SetResult(null); await requestStream.ToListAsync(); return ""; }); var cts = new CancellationTokenSource(); var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token))); await barrier.Task; // make sure the handler has started. cts.Cancel(); try { // cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock. await call.ResponseAsync; Assert.Fail(); } catch (RpcException ex) { Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } } [Test] public async Task ClientStreamingCall_ServerSideReadAfterCancelNotificationReturnsNull() { var handlerStartedBarrier = new TaskCompletionSource<object>(); var cancelNotificationReceivedBarrier = new TaskCompletionSource<object>(); var successTcs = new TaskCompletionSource<string>(); helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { handlerStartedBarrier.SetResult(null); // wait for cancellation to be delivered. context.CancellationToken.Register(() => cancelNotificationReceivedBarrier.SetResult(null)); await cancelNotificationReceivedBarrier.Task; var moveNextResult = await requestStream.MoveNext(); successTcs.SetResult(!moveNextResult ? "SUCCESS" : "FAIL"); return ""; }); var cts = new CancellationTokenSource(); var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token))); await handlerStartedBarrier.Task; cts.Cancel(); try { await call.ResponseAsync; Assert.Fail(); } catch (RpcException ex) { Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } Assert.AreEqual("SUCCESS", await successTcs.Task); } [Test] public async Task AsyncUnaryCall_EchoMetadata() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { foreach (Metadata.Entry metadataEntry in context.RequestHeaders) { if (metadataEntry.Key != "user-agent") { context.ResponseTrailers.Add(metadataEntry); } } return ""; }); var headers = new Metadata { { "ascii-header", "abcdefg" }, { "binary-header-bin", new byte[] { 1, 2, 3, 0, 0xff } } }; var call = Calls.AsyncUnaryCall(helper.CreateUnaryCall(new CallOptions(headers: headers)), "ABC"); await call; Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); var trailers = call.GetTrailers(); Assert.AreEqual(2, trailers.Count); Assert.AreEqual(headers[0].Key, trailers[0].Key); Assert.AreEqual(headers[0].Value, trailers[0].Value); Assert.AreEqual(headers[1].Key, trailers[1].Key); CollectionAssert.AreEqual(headers[1].ValueBytes, trailers[1].ValueBytes); } [Test] public void UnknownMethodHandler() { var nonexistentMethod = new Method<string, string>( MethodType.Unary, MockServiceHelper.ServiceName, "NonExistentMethod", Marshallers.StringMarshaller, Marshallers.StringMarshaller); var callDetails = new CallInvocationDetails<string, string>(channel, nonexistentMethod, new CallOptions()); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(callDetails, "abc")); Assert.AreEqual(StatusCode.Unimplemented, ex.Status.StatusCode); } [Test] public void StatusDetailIsUtf8() { // some japanese and chinese characters var nonAsciiString = "\u30a1\u30a2\u30a3 \u62b5\u6297\u662f\u5f92\u52b3\u7684"; helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { context.Status = new Status(StatusCode.Unknown, nonAsciiString); return ""; }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode); Assert.AreEqual(nonAsciiString, ex.Status.Detail); } [Test] public void ServerCallContext_PeerInfoPresent() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return context.Peer; }); string peer = Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"); Assert.IsTrue(peer.Contains(Host)); } [Test] public void ServerCallContext_HostAndMethodPresent() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { Assert.IsTrue(context.Host.Contains(Host)); Assert.AreEqual("/tests.Test/Unary", context.Method); return "PASS"; }); Assert.AreEqual("PASS", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); } [Test] public void ServerCallContext_AuthContextNotPopulated() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { Assert.IsFalse(context.AuthContext.IsPeerAuthenticated); Assert.AreEqual(0, context.AuthContext.Properties.Count()); return "PASS"; }); Assert.AreEqual("PASS", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); } [Test] public async Task Channel_WaitForStateChangedAsync() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return request; }); Assert.ThrowsAsync(typeof(TaskCanceledException), async () => await channel.WaitForStateChangedAsync(channel.State, DateTime.UtcNow.AddMilliseconds(10))); var stateChangedTask = channel.WaitForStateChangedAsync(channel.State); await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"); await stateChangedTask; Assert.AreEqual(ChannelState.Ready, channel.State); } [Test] public async Task Channel_ConnectAsync() { await channel.ConnectAsync(); Assert.AreEqual(ChannelState.Ready, channel.State); await channel.ConnectAsync(DateTime.UtcNow.AddMilliseconds(1000)); Assert.AreEqual(ChannelState.Ready, channel.State); } } }
/* * DataTableConverter.cs * * Copyright ?2007 Michael Schwarz (http://www.ajaxpro.info). * All Rights Reserved. * * 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. */ /* * MS 06-04-25 removed unnecessarily used cast * MS 06-04-26 fixed null values to DBNull.Value (thanks to allex@as.ro) * MS 06-05-23 using local variables instead of "new Type()" for get De-/SerializableTypes * MS 06-06-09 removed addNamespace use * MS 06-06-22 added AllowInheritance=true * MS 06-09-24 use QuoteString instead of Serialize * MS 06-09-26 improved performance using StringBuilder * MS 07-04-24 added renderJsonCompliant serialization * MS 08-03-21 fixed DataTable client-side script * * * */ using System; using System.Text; using System.Data; namespace AjaxPro { /// <summary> /// Provides methods to serialize and deserialize a DataTable object. /// </summary> public class DataTableConverter : IJavaScriptConverter { private string clientType = "Ajax.Web.DataTable"; /// <summary> /// Initializes a new instance of the <see cref="DataTableConverter"/> class. /// </summary> public DataTableConverter() : base() { m_AllowInheritance = true; m_serializableTypes = new Type[] { typeof(DataTable) }; m_deserializableTypes = new Type[] { typeof(DataTable) }; } /// <summary> /// Render the JavaScript code for prototypes or any other JavaScript method needed from this converter /// on the client-side. /// </summary> /// <returns>Returns JavaScript code.</returns> public override string GetClientScript() { if (AjaxPro.Utility.Settings.OldStyle.Contains("renderJsonCompliant")) return ""; return JavaScriptUtil.GetClientNamespaceRepresentation(clientType) + @" " + clientType + @" = function(c, r) { this.__type = ""System.Data.DataTable,System.Data""; this.Columns = []; this.Rows = []; this.addColumn = function(name, type) { this.Columns.push({Name:name,__type:type}); }; this.toJSON = function() { var dt = {}; var i; dt.Columns = []; for(i=0; i<this.Columns.length; i++) dt.Columns.push([this.Columns[i].Name, this.Columns[i].__type]); dt.Rows = []; for(i=0; i<this.Rows.length; i++) { var row = []; for(var j=0; j<this.Columns.length; j++) row.push(this.Rows[i][this.Columns[j].Name]); dt.Rows.push(row); } return AjaxPro.toJSON(dt); }; this.addRow = function(row) { this.Rows.push(row); }; if(c != null) { for(var i=0; i<c.length; i++) this.addColumn(c[i][0], c[i][1]); } if(r != null) { for(var y=0; y<r.length; y++) { var row = {}; for(var z=0; z<this.Columns.length && z<r[y].length; z++) row[this.Columns[z].Name] = r[y][z]; this.addRow(row); } } }; "; } /// <summary> /// Converts an IJavaScriptObject into an NET object. /// </summary> /// <param name="o">The IJavaScriptObject object to convert.</param> /// <param name="t"></param> /// <returns>Returns a .NET object.</returns> public override object Deserialize(IJavaScriptObject o, Type t) { JavaScriptObject ht = o as JavaScriptObject; if (ht == null) throw new NotSupportedException(); if (!ht.Contains("Columns") || !(ht["Columns"] is JavaScriptArray) || !ht.Contains("Rows") || !(ht["Rows"] is JavaScriptArray)) { throw new NotSupportedException(); } JavaScriptArray columns = (JavaScriptArray)ht["Columns"]; JavaScriptArray rows = (JavaScriptArray)ht["Rows"]; DataTable dt = new DataTable(); DataRow row = null; Type colType; JavaScriptArray column; if (ht.Contains("TableName") && ht["TableName"] is JavaScriptString) dt.TableName = ht["TableName"].ToString(); for (int i = 0; i < columns.Count; i++) { column = (JavaScriptArray)columns[i]; colType = Type.GetType(column[1].ToString(), true); dt.Columns.Add(column[0].ToString(), colType); } JavaScriptArray cols = null; object obj; for (int y = 0; y < rows.Count; y++) { // if(!(r is JavaScriptArray)) // continue; cols = (JavaScriptArray)rows[y]; row = dt.NewRow(); for (int i = 0; i < cols.Count; i++) { //row[i] = JavaScriptDeserializer.Deserialize((IJavaScriptObject)cols[i], dt.Columns[i].DataType); obj = JavaScriptDeserializer.Deserialize((IJavaScriptObject)cols[i], dt.Columns[i].DataType); row[i] = (obj == null) ? DBNull.Value : obj; } dt.Rows.Add(row); } return dt; } /// <summary> /// Converts a .NET object into a JSON string. /// </summary> /// <param name="o">The object to convert.</param> /// <returns>Returns a JSON string.</returns> public override string Serialize(object o) { StringBuilder sb = new StringBuilder(); Serialize(o, sb); return sb.ToString(); } /// <summary> /// Serializes the specified o. /// </summary> /// <param name="o">The o.</param> /// <param name="sb">The sb.</param> public override void Serialize(object o, StringBuilder sb) { DataTable dt = o as DataTable; if (dt == null) throw new NotSupportedException(); DataColumnCollection cols = dt.Columns; DataRowCollection rows = dt.Rows; bool b = true; if (!AjaxPro.Utility.Settings.OldStyle.Contains("renderJsonCompliant")) { sb.Append("new "); sb.Append(clientType); sb.Append("(["); foreach (DataColumn col in cols) { if (b) { b = false; } else { sb.Append(","); } sb.Append('['); JavaScriptUtil.QuoteString(col.ColumnName, sb); sb.Append(','); JavaScriptUtil.QuoteString(col.DataType.FullName, sb); sb.Append(']'); } sb.Append("],["); b = true; foreach (DataRow row in rows) { if (!b) sb.Append(","); JavaScriptSerializer.Serialize(row, sb); b = false; } sb.Append("])"); } else { sb.Append('['); foreach (DataRow row in rows) { if (b) { b = false; } else { sb.Append(","); } sb.Append('{'); bool bc = true; foreach (DataColumn col in dt.Columns) { if (bc) { bc = false; } else { sb.Append(","); } JavaScriptUtil.QuoteString(col.ColumnName, sb); sb.Append(':'); JavaScriptSerializer.Serialize(row[col], sb); } sb.Append('}'); } sb.Append(']'); } } } }
namespace Meziantou.Framework.CodeDom; public partial class CSharpCodeGenerator { protected class WriteStatementOptions { public bool EndStatement { get; set; } = true; public void WriteEnd(IndentedTextWriter writer) { if (EndStatement) { writer.WriteLine(";"); } } } private readonly WriteStatementOptions _defaultWriteStatementOptions = new(); private readonly WriteStatementOptions _inlineStatementWriteStatementOptions = new() { EndStatement = false }; protected virtual void WriteStatement(IndentedTextWriter writer, Statement statement) { WriteStatement(writer, statement, _defaultWriteStatementOptions); } protected virtual void WriteStatement(IndentedTextWriter writer, Statement? statement, WriteStatementOptions options!!) { if (statement == null) return; WriteNullableContextBefore(writer, statement); WriteBeforeComments(writer, statement); switch (statement) { case ConditionStatement o: WriteConditionStatement(writer, o, options); break; case ReturnStatement o: WriteReturnStatement(writer, o, options); break; case YieldReturnStatement o: WriteYieldReturnStatement(writer, o, options); break; case YieldBreakStatement o: WriteYieldBreakStatement(writer, o, options); break; case AssignStatement o: WriteAssignStatement(writer, o, options); break; case ExpressionStatement o: WriteExpressionStatement(writer, o, options); break; case ThrowStatement o: WriteThrowStatement(writer, o, options); break; case UsingStatement o: WriteUsingStatement(writer, o, options); break; case VariableDeclarationStatement o: WriteVariableDeclarationStatement(writer, o, options); break; case WhileStatement o: WriteWhileStatement(writer, o, options); break; case IterationStatement o: WriteIterationStatement(writer, o, options); break; case ExpressionCollectionStatement o: WriteExpressionCollectionStatement(writer, o, options); break; case GotoNextLoopIterationStatement o: WriteGotoNextLoopIterationStatement(writer, o, options); break; case ExitLoopStatement o: WriteExitLoopStatement(writer, o, options); break; case SnippetStatement o: WriteSnippetStatement(writer, o, options); break; case TryCatchFinallyStatement o: WriteTryCatchFinallyStatement(writer, o, options); break; case AddEventHandlerStatement o: WriteAddEventHandlerStatement(writer, o, options); break; case RemoveEventHandlerStatement o: WriteRemoveEventHandlerStatement(writer, o, options); break; case CommentStatement o: WriteCommentStatement(writer, o, options); break; default: throw new NotSupportedException(); } WriteAfterComments(writer, statement); WriteNullableContextAfter(writer, statement); } protected virtual void WriteTryCatchFinallyStatement(IndentedTextWriter writer, TryCatchFinallyStatement statement, WriteStatementOptions options) { writer.WriteLine("try"); WriteStatements(writer, statement.Try); if (statement.Catch != null) { WriteCatchClauseCollection(writer, statement.Catch); } if (statement.Finally != null) { writer.WriteLine("finally"); WriteStatements(writer, statement.Finally); } } protected virtual void WriteSnippetStatement(IndentedTextWriter writer, SnippetStatement statement, WriteStatementOptions options) { writer.WriteLine(statement.Statement); } protected virtual void WriteGotoNextLoopIterationStatement(IndentedTextWriter writer, GotoNextLoopIterationStatement statement, WriteStatementOptions options) { writer.WriteLine("continue;"); } protected virtual void WriteExitLoopStatement(IndentedTextWriter writer, ExitLoopStatement statement, WriteStatementOptions options) { writer.WriteLine("break;"); } protected virtual void WriteReturnStatement(IndentedTextWriter writer, ReturnStatement statement, WriteStatementOptions options) { writer.Write("return"); if (statement.Expression != null) { writer.Write(" "); WriteExpression(writer, statement.Expression); } writer.WriteLine(";"); } protected virtual void WriteYieldReturnStatement(IndentedTextWriter writer, YieldReturnStatement statement, WriteStatementOptions options) { writer.Write("yield return"); if (statement.Expression != null) { writer.Write(" "); WriteExpression(writer, statement.Expression); } writer.WriteLine(";"); } protected virtual void WriteYieldBreakStatement(IndentedTextWriter writer, YieldBreakStatement statement, WriteStatementOptions options) { writer.WriteLine("yield break;"); } protected virtual void WriteConditionStatement(IndentedTextWriter writer, ConditionStatement statement, WriteStatementOptions options) { writer.Write("if ("); WriteExpression(writer, statement.Condition); writer.WriteLine(")"); WriteStatements(writer, statement.TrueStatements); if (statement.FalseStatements != null) { writer.WriteLine("else"); WriteStatements(writer, statement.FalseStatements); } } protected virtual void WriteAssignStatement(IndentedTextWriter writer, AssignStatement statement, WriteStatementOptions options) { WriteExpression(writer, statement.LeftExpression); writer.Write(" = "); WriteExpression(writer, statement.RightExpression); options.WriteEnd(writer); } protected virtual void WriteExpressionStatement(IndentedTextWriter writer, ExpressionStatement statement, WriteStatementOptions options) { WriteExpression(writer, statement.Expression); options.WriteEnd(writer); } protected virtual void WriteThrowStatement(IndentedTextWriter writer, ThrowStatement statement, WriteStatementOptions options) { writer.Write("throw"); if (statement.Expression != null) { writer.Write(" "); WriteExpression(writer, statement.Expression); } writer.WriteLine(";"); } protected virtual void WriteUsingStatement(IndentedTextWriter writer, UsingStatement statement, WriteStatementOptions options) { writer.Write("using ("); WriteStatement(writer, statement.Statement, _inlineStatementWriteStatementOptions); writer.Write(")"); writer.WriteLine(); WriteStatements(writer, statement.Body); } protected virtual void WriteVariableDeclarationStatement(IndentedTextWriter writer, VariableDeclarationStatement statement, WriteStatementOptions options) { if (statement.Type != null) { WriteTypeReference(writer, statement.Type); writer.Write(" "); } else { writer.Write("var "); } WriteIdentifier(writer, statement.Name); if (statement.InitExpression != null) { writer.Write(" = "); WriteExpression(writer, statement.InitExpression); } options.WriteEnd(writer); } protected virtual void WriteWhileStatement(IndentedTextWriter writer, WhileStatement statement, WriteStatementOptions options) { writer.Write("while ("); WriteExpression(writer, statement.Condition); writer.Write(")"); writer.WriteLine(); WriteStatements(writer, statement.Body); } protected virtual void WriteIterationStatement(IndentedTextWriter writer, IterationStatement statement, WriteStatementOptions options) { writer.Write("for ("); if (statement.Initialization != null) { WriteStatement(writer, statement.Initialization, _inlineStatementWriteStatementOptions); } writer.Write("; "); if (statement.Condition != null) { WriteExpression(writer, statement.Condition); } writer.Write("; "); if (statement.IncrementStatement != null) { WriteStatement(writer, statement.IncrementStatement, _inlineStatementWriteStatementOptions); } writer.Write(")"); writer.WriteLine(); WriteStatements(writer, statement.Body); } protected virtual void WriteAddEventHandlerStatement(IndentedTextWriter writer, AddEventHandlerStatement statement, WriteStatementOptions options) { if (statement.LeftExpression != null) { WriteExpression(writer, statement.LeftExpression); } writer.Write(" += "); if (statement.RightExpression != null) { WriteExpression(writer, statement.RightExpression); } writer.WriteLine(";"); } protected virtual void WriteRemoveEventHandlerStatement(IndentedTextWriter writer, RemoveEventHandlerStatement statement, WriteStatementOptions options) { if (statement.LeftExpression != null) { WriteExpression(writer, statement.LeftExpression); } writer.Write(" -= "); if (statement.RightExpression != null) { WriteExpression(writer, statement.RightExpression); } writer.WriteLine(";"); } protected virtual void WriteExpressionCollectionStatement(IndentedTextWriter writer, ExpressionCollectionStatement statement, WriteStatementOptions options) { Write(writer, statement, ", "); } protected virtual void WriteCommentStatement(IndentedTextWriter writer, CommentStatement statement, WriteStatementOptions options) { WriteLineComment(writer, statement.Content); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Reflection; using System.IO; using System.Data; using MySql.Data.MySqlClient; using System.Diagnostics; using classes; using System.Configuration; using System.Drawing; namespace kzstats { public partial class wr : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Panel4.EnableViewState = false; if (Page.IsPostBack == false) { SetUpDropDown(); } if (HttpContext.Current.Request.UserAgent.Contains("Chrome") == true || HttpContext.Current.Request.UserAgent.Contains("Firefox") == true) { gcBody.Attributes.Add("style", tcBgStyler.Instance.GetBgImageStyle()); } DoPageLoad(); } private void DoPageLoad() { Stopwatch lcStopWatch = new Stopwatch(); lcStopWatch.Reset(); lcStopWatch.Start(); tcGridViewType lcGridViewType = new tcGridViewType(teGridViewType.eeWrPage, teSubPageType.eeSubPageNone); string lpanQuery = GetQueryFromDropDownState(); lcGridViewType.meSub = GetGridTypeFromDropDownState(); tcMySqlDataSource lcMySqlDataSource = new tcMySqlDataSource(lpanQuery); DataTable lcDataTable = lcMySqlDataSource.GetDataTable(); if (lcDataTable != null && lcDataTable.Rows.Count > 0) { tcGridView lcGridView = GridViewFactory.Create(lcDataTable, lcGridViewType); Panel4.Controls.AddAt(0, lcGridView); } tcLinkPanel.AddLinkPanel(this); //Refresh all the gridviews with data contents Page.DataBind(); Page.MaintainScrollPositionOnPostBack = true; lcStopWatch.Stop(); gcPageLoad.Text = lcStopWatch.ElapsedMilliseconds.ToString(); } private void SetUpDropDown() { string[] lacText = { "World records by course", "World records by player", "World records by country" }; string[] lacKeyword = { "all", "player", "country" }; gcDropDown.AutoPostBack = true; gcDropDown.SelectedIndexChanged += new EventHandler(cb_DropDownTextChange); //Add options to dropdown for (int i = 0; i < lacText.Length; i++) { gcDropDown.Items.Add(new ListItem(lacText[i], lacKeyword[i])); } string lpanSel = Request.QueryString["sel"]; if (HttpContext.Current.Request.UserAgent.Contains("Chrome") == false && HttpContext.Current.Request.UserAgent.Contains("Firefox") == false) { gcDropDown.Visible = false; Panel3.Height = 425; Panel3.ScrollBars = ScrollBars.Vertical; if (lpanSel == null) { lpanSel = lacKeyword[0]; } } if (lpanSel != null) { gcDropDown.SelectedValue = lpanSel; Panel3.Controls.Remove(gcDropDown); for (int i = 0; i < lacText.Length; i++) { HyperLink lcLink = new HyperLink(); lcLink.Text = lacText[i]; lcLink.NavigateUrl = "~/wr.aspx?sel=" + lacKeyword[i]; lcLink.Font.Name = "Arial"; lcLink.Font.Size = 11; lcLink.Font.Bold = true; lcLink.ForeColor = teColors.eeLink; gcLinks.Controls.Add(lcLink); if (i + 1 < lacText.Length) { gcLinks.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")); } else { gcLinks.Controls.Add(new LiteralControl("<br><br>")); } } } } private void cb_DropDownTextChange(object acSender, EventArgs e) { while (Panel4.Controls.Count > 0) { Panel4.Controls.RemoveAt(0); } DoPageLoad(); } private teSubPageType GetGridTypeFromDropDownState() { switch (gcDropDown.SelectedValue) { case "country": return teSubPageType.eeWrPageCountry; case "player": return teSubPageType.eeWrPagePlayer; default: return teSubPageType.eeWrPageAll; } } private string GetQueryFromDropDownState() { switch (gcDropDown.SelectedValue) { case "player": return @"SELECT @rank := @rank + 1 AS Rank, FF.Player, FF.SteamId, FF.Country, FF.CurrentWR, FF.TotalWR, FF.TotalCourses FROM (SELECT PlayerId,F.Player,SteamId,Country,COUNT(*) AS TotalWR, invert, IFNULL(CURWR.CurrWR,0) AS CurrentWR, NN.TotalCourses FROM (SELECT P.id AS PlayerId, P.name AS Player, P.auth AS SteamId, P.country AS Country,M.id AS MapId,C.id AS CourseId,WR.time,WR.date,C.invert FROM (SELECT player,map,course,time,date FROM kzs_wrs) AS WR LEFT JOIN (SELECT id,invert,name FROM kzs_courses) AS C ON C.id = WR.course LEFT JOIN (SELECT name,id,auth,country FROM kzs_players) AS P ON P.id = WR.player LEFT JOIN (SELECT name,id FROM kzs_maps) AS M ON M.id = WR.map ORDER BY map,course,CASE 1 WHEN C.invert THEN Time ELSE -Time END DESC) AS F LEFT JOIN (SELECT player AS TWRplayer,COUNT(*) AS CurrWR FROM (SELECT * FROM (SELECT player,course,invert,date,time FROM (SELECT player,course,time,date FROM kzs_wrs ORDER BY course) AS WRR LEFT JOIN (SELECT invert,id FROM kzs_courses) AS CC ON CC.id = WRR.course ORDER BY course,date DESC, CASE 1 WHEN CC.invert THEN Time ELSE -Time END DESC) AS TT GROUP BY course) AS PP GROUP BY player) AS CURWR ON F.PlayerId = CURWR.TWRplayer LEFT JOIN (SELECT player, COUNT(*) AS TotalCourses FROM (SELECT player, course FROM (SELECT player,course FROM kzs_wrs ORDER BY player,course) AS N GROUP BY player,course ORDER BY player,course) AS A GROUP BY player) AS NN ON NN.player = F.PlayerId GROUP BY PlayerId ORDER BY CurrentWR DESC) AS FF, (SELECT @rank := 0) AS RNK"; case "country": return @"SELECT FIN.*, CNTT.full AS CountryFull FROM (SELECT @rank := @rank + 1 AS Rank, FF.Country, FF.CurrentWR, FF.TotalWR, FF.TotalCourses FROM (SELECT PlayerId,F.Country,COUNT(*) AS TotalWR, invert, IFNULL(CURWR.CurrWR,0) AS CurrentWR, NN.TotalCourses FROM (SELECT P.id AS PlayerId, P.country AS Country,M.id AS MapId,C.id AS CourseId,WR.time, WR.date,C.invert FROM (SELECT player,map,course,time,date FROM kzs_wrs) AS WR LEFT JOIN (SELECT id,invert FROM kzs_courses) AS C ON C.id = WR.course LEFT JOIN (SELECT id,country FROM kzs_players) AS P ON P.id = WR.player LEFT JOIN (SELECT id FROM kzs_maps) AS M ON M.id = WR.map ORDER BY map,course,CASE 1 WHEN C.invert THEN Time ELSE -Time END DESC) AS F LEFT JOIN (SELECT country AS TWRcountry,COUNT(*) AS CurrWR FROM (SELECT * FROM (SELECT country,course,invert,date,time FROM (SELECT player,course,time,date FROM kzs_wrs ORDER BY course) AS WRR LEFT JOIN(SELECT id,country FROM kzs_players) AS PPP ON PPP.id = WRR.player LEFT JOIN (SELECT invert,id FROM kzs_courses) AS CC ON CC.id = WRR.course ORDER BY course,date DESC, CASE 1 WHEN CC.invert THEN Time ELSE -Time END DESC) AS TT GROUP BY course) AS PP GROUP BY country) AS CURWR ON F.Country = CURWR.TWRcountry LEFT JOIN (SELECT country, COUNT(*) AS TotalCourses FROM (SELECT country, course FROM (SELECT country,course FROM (SELECT player,course FROM kzs_wrs) AS E LEFT JOIN(SELECT id,country FROM kzs_players)AS W ON W.id = E.player ORDER BY country,course) AS N GROUP BY country,course ORDER BY country,course) AS A GROUP BY country) AS NN ON NN.country = F.country GROUP BY Country ORDER BY CurrentWR DESC) AS FF, (SELECT @rank := 0) AS RNK) AS FIN LEFT JOIN (SELECT full,code FROM kzs_countries) AS CNTT ON CNTT.code = FIN.country"; default: return @"SELECT F.* FROM (SELECT M.name AS Map, C.name AS Course, C.id AS CourseId, P.name AS Player, P.auth AS SteamId, P.country AS Country, WR.time AS Time, DATE_FORMAT(WR.date,'%Y-%m-%d') AS Date FROM (SELECT player,map,course,time,date FROM kzs_wrs) AS WR LEFT JOIN (SELECT name,id,auth,country FROM kzs_players) AS P ON P.id = WR.player LEFT JOIN (SELECT name,id FROM kzs_maps) AS M ON M.id = WR.map LEFT JOIN (SELECT name,id,invert FROM kzs_courses) AS C ON C.id = WR.course ORDER BY Map,Course,Date DESC, CASE 1 WHEN C.invert THEN Time ELSE -Time END DESC) AS F GROUP BY Map,Course ORDER BY map,course"; } } } }
using System; using ShadowrunLogic; using System.Collections.Generic; namespace ShadowrunGui { [System.ComponentModel.ToolboxItem(true)] public partial class CombatPageWidget : Gtk.Bin { private List<Character> characters; private int selectedIndex = -1; public CombatPageWidget () { this.Build (); this.Reload_Button.Clicked += Reload_Clicked; this.NewInitiative_Button.Clicked += NewInitiative_Clicked; this.NextCharacter_Button.Clicked+= NextCharacter_Clicked; this.PreviousCharacter_Button.Clicked += PreviousCharacter_Clicked; this.NextPass_Button.Clicked += NextPass_Clicked; this.SetCharacterInitiative_Button.Clicked += SetCharacterInitiative_Clicked; this.DefendRanged_Button.Clicked += DefendRanged_Clicked; this.DefendMelee_Button.Clicked += DefendMelee_Clicked; this.AttackRanged_Button.Clicked += AttackRanged_Clicked; this.AttackMelee_Button.Clicked += AttackMelee_Clicked; } public void SetCharacters (List<Character> characters) { this.characters = characters; this.RenderInitiativeTree(); this.RenderStatusTree(); } #region display protected void RenderStatusTree () { Gtk.ListStore list = new Gtk.ListStore (typeof(string), typeof(string)); if (CharacterStatus_TreeView.Columns.Length != 2) { CharacterStatus_TreeView.AppendColumn ("Name", new Gtk.CellRendererText (), "text", 0); CharacterStatus_TreeView.AppendColumn ("Value", new Gtk.CellRendererText (), "text", 1); } if (selectedIndex >= 0 && selectedIndex < characters.Count) { var character = characters [selectedIndex]; var attributes = character.attributes; list.AppendValues ("Name", attributes.Name ()); list.AppendValues ("Stun Boxes", attributes.MaxStunDamage().ToString()); list.AppendValues ("Stun Damage Taken", attributes.StunDamageTaken.ToString()); list.AppendValues ("Physical Boxes" , attributes.MaxPhysixalDamage().ToString()); list.AppendValues ("Physical Damage Taken", attributes.PhysicalDamageTaken.ToString()); list.AppendValues ("Injury Dice Pool Modifier", attributes.GetDamageModifier().ToString()); } CharacterStatus_TreeView.Model = list; } public void RenderInitiativeTree () { Gtk.ListStore list = new Gtk.ListStore (typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string)); if (Initiative_TreeView.Columns.Length != 6) { Initiative_TreeView.AppendColumn ("IsTurn", new Gtk.CellRendererText(), "text", 0); Initiative_TreeView.AppendColumn ("AbleToAct", new Gtk.CellRendererText(), "text", 1); Initiative_TreeView.AppendColumn ("Initiative", new Gtk.CellRendererText(), "text", 2); Initiative_TreeView.AppendColumn ("Character Name", new Gtk.CellRendererText (), "text", 3); Initiative_TreeView.AppendColumn ("Ranged Weapon", new Gtk.CellRendererText (), "text", 4); Initiative_TreeView.AppendColumn ("Melee Weapon", new Gtk.CellRendererText (), "text", 5); } characters.Sort (new InitiativeComparer()); for (int i = 0; i < characters.Count; i++) { var character = characters[i]; list.AppendValues ( (i == selectedIndex ? "*" : " "), (character.initiative > 0 ? "True" : "False"), character.initiative.ToString(), character.attributes.Name (), character.rangedWeapon.Name (), character.meleeWeapon.Name (), i.ToString() ); } Initiative_TreeView.Model = list; } protected void Log (string message) { Log_Textview.Buffer.InsertAtCursor(message + "\n"); } #endregion #region logic protected Character GetSelectedTreeCharacter () { Gtk.TreeIter selected; Initiative_TreeView.Selection.GetSelected (out selected); string index = Initiative_TreeView.Model.GetValue (selected, 0).ToString(); return characters[Int32.Parse(index)]; } protected Character GetSelectedInitiativeCharacter () { return characters[selectedIndex]; } #endregion #region events protected void Reload_Clicked (object sender, EventArgs e) { RenderStatusTree(); RenderInitiativeTree(); } protected void SetCharacterInitiative_Clicked (object sender, EventArgs e) { try { var iw = new InputWindow("Set Character Initiative","Enter the rolled initiative"); iw.Destroyed += delegate { int initiative = Int32.Parse(iw.input); if(initiative <= 0) throw new ArgumentException(); characters[selectedIndex].initiative = initiative; RenderInitiativeTree(); RenderStatusTree(); }; } catch (Exception ex) { new MessageWindow("Error","Error: " + ex.Message); } } protected void NewInitiative_Clicked (object sender, EventArgs e) { Log ("Rolling Initiatives"); foreach (var character in characters) { character.initiative = Initiative.Roll (character.attributes); Log (character.attributes.Name() + " Rolled " + character.initiative.ToString()); } selectedIndex = 0; RenderInitiativeTree(); RenderStatusTree(); } protected void NextCharacter_Clicked (object sender, EventArgs e) { NextCharacter(); } private void NextPass(){ selectedIndex = 0; foreach (var character in characters) { character.initiative -= 10; if(character.initiative < 0) character.initiative = 0; } RenderInitiativeTree(); RenderStatusTree(); } protected void PreviousCharacter_Clicked(object sender,EventArgs e){ if(selectedIndex > 0) selectedIndex--; RenderInitiativeTree(); RenderStatusTree(); } protected void NextPass_Clicked (object sender, EventArgs e) { NextPass(); } protected void DefendRanged_Clicked(object sender, EventArgs e){ } protected void DefendMelee_Clicked(object sender, EventArgs e){ } void NextCharacter () { selectedIndex++; RenderInitiativeTree (); RenderStatusTree (); if (selectedIndex >= characters.Count) NextPass (); } protected void AttackRanged_Clicked (object sender, EventArgs e) { try { var f = new List<Character> (characters); f.Remove (GetSelectedInitiativeCharacter ()); var csw = new CharacterSelectWindow (f); csw.Destroyed += delegate { new CombatSequence(GetSelectedInitiativeCharacter(),csw.character,new CallBack(AfterAttack)); }; } catch { new MessageWindow("Error","Make sure you have started the initiative"); } } protected void AfterAttack () { NextCharacter(); } protected void AttackMelee_Clicked(object sender, EventArgs e){ var csw = new CharacterSelectWindow(characters); csw.Destroyed += delegate { }; } #endregion } }
// // System.Drawing.Drawing2D.GraphicsPath.cs // // Authors: // // Miguel de Icaza (miguel@ximian.com) // Duncan Mak (duncan@ximian.com) // Jordi Mas i Hernandez (jordi@ximian.com) // Ravindra (rkumar@novell.com) // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2004,2006-2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.ComponentModel; using System.Runtime.InteropServices; namespace System.Drawing.Drawing2D { public sealed class GraphicsPath : MarshalByRefObject, ICloneable, IDisposable { // 1/4 is the FlatnessDefault as defined in GdiPlusEnums.h private const float FlatnessDefault = 1.0f / 4.0f; internal IntPtr nativePath = IntPtr.Zero; GraphicsPath(IntPtr ptr) { nativePath = ptr; } public GraphicsPath() { int status = SafeNativeMethods.Gdip.GdipCreatePath(FillMode.Alternate, out nativePath); SafeNativeMethods.Gdip.CheckStatus(status); } public GraphicsPath(FillMode fillMode) { int status = SafeNativeMethods.Gdip.GdipCreatePath(fillMode, out nativePath); SafeNativeMethods.Gdip.CheckStatus(status); } public GraphicsPath(Point[] pts, byte[] types) : this(pts, types, FillMode.Alternate) { } public GraphicsPath(PointF[] pts, byte[] types) : this(pts, types, FillMode.Alternate) { } public GraphicsPath(Point[] pts, byte[] types, FillMode fillMode) { if (pts == null) throw new ArgumentNullException("pts"); if (pts.Length != types.Length) throw new ArgumentException("Invalid parameter passed. Number of points and types must be same."); int status = SafeNativeMethods.Gdip.GdipCreatePath2I(pts, types, pts.Length, fillMode, out nativePath); SafeNativeMethods.Gdip.CheckStatus(status); } public GraphicsPath(PointF[] pts, byte[] types, FillMode fillMode) { if (pts == null) throw new ArgumentNullException("pts"); if (pts.Length != types.Length) throw new ArgumentException("Invalid parameter passed. Number of points and types must be same."); int status = SafeNativeMethods.Gdip.GdipCreatePath2(pts, types, pts.Length, fillMode, out nativePath); SafeNativeMethods.Gdip.CheckStatus(status); } public object Clone() { IntPtr clone; int status = SafeNativeMethods.Gdip.GdipClonePath(nativePath, out clone); SafeNativeMethods.Gdip.CheckStatus(status); return new GraphicsPath(clone); } public void Dispose() { Dispose(true); System.GC.SuppressFinalize(this); } ~GraphicsPath() { Dispose(false); } void Dispose(bool disposing) { int status; if (nativePath != IntPtr.Zero) { status = SafeNativeMethods.Gdip.GdipDeletePath(nativePath); SafeNativeMethods.Gdip.CheckStatus(status); nativePath = IntPtr.Zero; } } public FillMode FillMode { get { FillMode mode; int status = SafeNativeMethods.Gdip.GdipGetPathFillMode(nativePath, out mode); SafeNativeMethods.Gdip.CheckStatus(status); return mode; } set { if ((value < FillMode.Alternate) || (value > FillMode.Winding)) throw new InvalidEnumArgumentException("FillMode", (int)value, typeof(FillMode)); int status = SafeNativeMethods.Gdip.GdipSetPathFillMode(nativePath, value); SafeNativeMethods.Gdip.CheckStatus(status); } } public PathData PathData { get { int count; int status = SafeNativeMethods.Gdip.GdipGetPointCount(nativePath, out count); SafeNativeMethods.Gdip.CheckStatus(status); PointF[] points = new PointF[count]; byte[] types = new byte[count]; // status would fail if we ask points or types with a 0 count // anyway that would only mean two unrequired unmanaged calls if (count > 0) { status = SafeNativeMethods.Gdip.GdipGetPathPoints(nativePath, points, count); SafeNativeMethods.Gdip.CheckStatus(status); status = SafeNativeMethods.Gdip.GdipGetPathTypes(nativePath, types, count); SafeNativeMethods.Gdip.CheckStatus(status); } PathData pdata = new PathData(); pdata.Points = points; pdata.Types = types; return pdata; } } public PointF[] PathPoints { get { int count; int status = SafeNativeMethods.Gdip.GdipGetPointCount(nativePath, out count); SafeNativeMethods.Gdip.CheckStatus(status); if (count == 0) throw new ArgumentException("PathPoints"); PointF[] points = new PointF[count]; status = SafeNativeMethods.Gdip.GdipGetPathPoints(nativePath, points, count); SafeNativeMethods.Gdip.CheckStatus(status); return points; } } public byte[] PathTypes { get { int count; int status = SafeNativeMethods.Gdip.GdipGetPointCount(nativePath, out count); SafeNativeMethods.Gdip.CheckStatus(status); if (count == 0) throw new ArgumentException("PathTypes"); byte[] types = new byte[count]; status = SafeNativeMethods.Gdip.GdipGetPathTypes(nativePath, types, count); SafeNativeMethods.Gdip.CheckStatus(status); return types; } } public int PointCount { get { int count; int status = SafeNativeMethods.Gdip.GdipGetPointCount(nativePath, out count); SafeNativeMethods.Gdip.CheckStatus(status); return count; } } internal IntPtr NativeObject { get { return nativePath; } set { nativePath = value; } } // // AddArc // public void AddArc(Rectangle rect, float startAngle, float sweepAngle) { int status = SafeNativeMethods.Gdip.GdipAddPathArcI(nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddArc(RectangleF rect, float startAngle, float sweepAngle) { int status = SafeNativeMethods.Gdip.GdipAddPathArc(nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddArc(int x, int y, int width, int height, float startAngle, float sweepAngle) { int status = SafeNativeMethods.Gdip.GdipAddPathArcI(nativePath, x, y, width, height, startAngle, sweepAngle); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddArc(float x, float y, float width, float height, float startAngle, float sweepAngle) { int status = SafeNativeMethods.Gdip.GdipAddPathArc(nativePath, x, y, width, height, startAngle, sweepAngle); SafeNativeMethods.Gdip.CheckStatus(status); } // // AddBezier // public void AddBezier(Point pt1, Point pt2, Point pt3, Point pt4) { int status = SafeNativeMethods.Gdip.GdipAddPathBezierI(nativePath, pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddBezier(PointF pt1, PointF pt2, PointF pt3, PointF pt4) { int status = SafeNativeMethods.Gdip.GdipAddPathBezier(nativePath, pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddBezier(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { int status = SafeNativeMethods.Gdip.GdipAddPathBezierI(nativePath, x1, y1, x2, y2, x3, y3, x4, y4); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddBezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { int status = SafeNativeMethods.Gdip.GdipAddPathBezier(nativePath, x1, y1, x2, y2, x3, y3, x4, y4); SafeNativeMethods.Gdip.CheckStatus(status); } // // AddBeziers // public void AddBeziers(params Point[] points) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathBeziersI(nativePath, points, points.Length); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddBeziers(PointF[] points) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathBeziers(nativePath, points, points.Length); SafeNativeMethods.Gdip.CheckStatus(status); } // // AddEllipse // public void AddEllipse(RectangleF rect) { int status = SafeNativeMethods.Gdip.GdipAddPathEllipse(nativePath, rect.X, rect.Y, rect.Width, rect.Height); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddEllipse(float x, float y, float width, float height) { int status = SafeNativeMethods.Gdip.GdipAddPathEllipse(nativePath, x, y, width, height); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddEllipse(Rectangle rect) { int status = SafeNativeMethods.Gdip.GdipAddPathEllipseI(nativePath, rect.X, rect.Y, rect.Width, rect.Height); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddEllipse(int x, int y, int width, int height) { int status = SafeNativeMethods.Gdip.GdipAddPathEllipseI(nativePath, x, y, width, height); SafeNativeMethods.Gdip.CheckStatus(status); } // // AddLine // public void AddLine(Point pt1, Point pt2) { int status = SafeNativeMethods.Gdip.GdipAddPathLineI(nativePath, pt1.X, pt1.Y, pt2.X, pt2.Y); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddLine(PointF pt1, PointF pt2) { int status = SafeNativeMethods.Gdip.GdipAddPathLine(nativePath, pt1.X, pt1.Y, pt2.X, pt2.Y); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddLine(int x1, int y1, int x2, int y2) { int status = SafeNativeMethods.Gdip.GdipAddPathLineI(nativePath, x1, y1, x2, y2); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddLine(float x1, float y1, float x2, float y2) { int status = SafeNativeMethods.Gdip.GdipAddPathLine(nativePath, x1, y1, x2, y2); SafeNativeMethods.Gdip.CheckStatus(status); } // // AddLines // public void AddLines(Point[] points) { if (points == null) throw new ArgumentNullException("points"); if (points.Length == 0) throw new ArgumentException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathLine2I(nativePath, points, points.Length); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddLines(PointF[] points) { if (points == null) throw new ArgumentNullException("points"); if (points.Length == 0) throw new ArgumentException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathLine2(nativePath, points, points.Length); SafeNativeMethods.Gdip.CheckStatus(status); } // // AddPie // public void AddPie(Rectangle rect, float startAngle, float sweepAngle) { int status = SafeNativeMethods.Gdip.GdipAddPathPie( nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddPie(int x, int y, int width, int height, float startAngle, float sweepAngle) { int status = SafeNativeMethods.Gdip.GdipAddPathPieI(nativePath, x, y, width, height, startAngle, sweepAngle); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddPie(float x, float y, float width, float height, float startAngle, float sweepAngle) { int status = SafeNativeMethods.Gdip.GdipAddPathPie(nativePath, x, y, width, height, startAngle, sweepAngle); SafeNativeMethods.Gdip.CheckStatus(status); } // // AddPolygon // public void AddPolygon(Point[] points) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathPolygonI(nativePath, points, points.Length); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddPolygon(PointF[] points) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathPolygon(nativePath, points, points.Length); SafeNativeMethods.Gdip.CheckStatus(status); } // // AddRectangle // public void AddRectangle(Rectangle rect) { int status = SafeNativeMethods.Gdip.GdipAddPathRectangleI(nativePath, rect.X, rect.Y, rect.Width, rect.Height); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddRectangle(RectangleF rect) { int status = SafeNativeMethods.Gdip.GdipAddPathRectangle(nativePath, rect.X, rect.Y, rect.Width, rect.Height); SafeNativeMethods.Gdip.CheckStatus(status); } // // AddRectangles // public void AddRectangles(Rectangle[] rects) { if (rects == null) throw new ArgumentNullException("rects"); if (rects.Length == 0) throw new ArgumentException("rects"); int status = SafeNativeMethods.Gdip.GdipAddPathRectanglesI(nativePath, rects, rects.Length); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddRectangles(RectangleF[] rects) { if (rects == null) throw new ArgumentNullException("rects"); if (rects.Length == 0) throw new ArgumentException("rects"); int status = SafeNativeMethods.Gdip.GdipAddPathRectangles(nativePath, rects, rects.Length); SafeNativeMethods.Gdip.CheckStatus(status); } // // AddPath // public void AddPath(GraphicsPath addingPath, bool connect) { if (addingPath == null) throw new ArgumentNullException("addingPath"); int status = SafeNativeMethods.Gdip.GdipAddPathPath(nativePath, addingPath.nativePath, connect); SafeNativeMethods.Gdip.CheckStatus(status); } public PointF GetLastPoint() { PointF pt; int status = SafeNativeMethods.Gdip.GdipGetPathLastPoint(nativePath, out pt); SafeNativeMethods.Gdip.CheckStatus(status); return pt; } // // AddClosedCurve // public void AddClosedCurve(Point[] points) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathClosedCurveI(nativePath, points, points.Length); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddClosedCurve(PointF[] points) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathClosedCurve(nativePath, points, points.Length); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddClosedCurve(Point[] points, float tension) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathClosedCurve2I(nativePath, points, points.Length, tension); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddClosedCurve(PointF[] points, float tension) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathClosedCurve2(nativePath, points, points.Length, tension); SafeNativeMethods.Gdip.CheckStatus(status); } // // AddCurve // public void AddCurve(Point[] points) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathCurveI(nativePath, points, points.Length); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddCurve(PointF[] points) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathCurve(nativePath, points, points.Length); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddCurve(Point[] points, float tension) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathCurve2I(nativePath, points, points.Length, tension); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddCurve(PointF[] points, float tension) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathCurve2(nativePath, points, points.Length, tension); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddCurve(Point[] points, int offset, int numberOfSegments, float tension) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathCurve3I(nativePath, points, points.Length, offset, numberOfSegments, tension); SafeNativeMethods.Gdip.CheckStatus(status); } public void AddCurve(PointF[] points, int offset, int numberOfSegments, float tension) { if (points == null) throw new ArgumentNullException("points"); int status = SafeNativeMethods.Gdip.GdipAddPathCurve3(nativePath, points, points.Length, offset, numberOfSegments, tension); SafeNativeMethods.Gdip.CheckStatus(status); } public void Reset() { int status = SafeNativeMethods.Gdip.GdipResetPath(nativePath); SafeNativeMethods.Gdip.CheckStatus(status); } public void Reverse() { int status = SafeNativeMethods.Gdip.GdipReversePath(nativePath); SafeNativeMethods.Gdip.CheckStatus(status); } public void Transform(Matrix matrix) { if (matrix == null) throw new ArgumentNullException("matrix"); int status = SafeNativeMethods.Gdip.GdipTransformPath(nativePath, matrix.nativeMatrix); SafeNativeMethods.Gdip.CheckStatus(status); } [MonoTODO("The StringFormat parameter is ignored when using libgdiplus.")] public void AddString(string s, FontFamily family, int style, float emSize, Point origin, StringFormat format) { Rectangle layout = new Rectangle(); layout.X = origin.X; layout.Y = origin.Y; AddString(s, family, style, emSize, layout, format); } [MonoTODO("The StringFormat parameter is ignored when using libgdiplus.")] public void AddString(string s, FontFamily family, int style, float emSize, PointF origin, StringFormat format) { RectangleF layout = new RectangleF(); layout.X = origin.X; layout.Y = origin.Y; AddString(s, family, style, emSize, layout, format); } [MonoTODO("The layoutRect and StringFormat parameters are ignored when using libgdiplus.")] public void AddString(string s, FontFamily family, int style, float emSize, Rectangle layoutRect, StringFormat format) { if (family == null) throw new ArgumentException("family"); IntPtr sformat = (format == null) ? IntPtr.Zero : format.nativeFormat; // note: the NullReferenceException on s.Length is the expected (MS) exception int status = SafeNativeMethods.Gdip.GdipAddPathStringI(nativePath, s, s.Length, family.NativeFamily, style, emSize, ref layoutRect, sformat); SafeNativeMethods.Gdip.CheckStatus(status); } [MonoTODO("The layoutRect and StringFormat parameters are ignored when using libgdiplus.")] public void AddString(string s, FontFamily family, int style, float emSize, RectangleF layoutRect, StringFormat format) { if (family == null) throw new ArgumentException("family"); IntPtr sformat = (format == null) ? IntPtr.Zero : format.nativeFormat; // note: the NullReferenceException on s.Length is the expected (MS) exception int status = SafeNativeMethods.Gdip.GdipAddPathString(nativePath, s, s.Length, family.NativeFamily, style, emSize, ref layoutRect, sformat); SafeNativeMethods.Gdip.CheckStatus(status); } public void ClearMarkers() { int s = SafeNativeMethods.Gdip.GdipClearPathMarkers(nativePath); SafeNativeMethods.Gdip.CheckStatus(s); } public void CloseAllFigures() { int s = SafeNativeMethods.Gdip.GdipClosePathFigures(nativePath); SafeNativeMethods.Gdip.CheckStatus(s); } public void CloseFigure() { int s = SafeNativeMethods.Gdip.GdipClosePathFigure(nativePath); SafeNativeMethods.Gdip.CheckStatus(s); } public void Flatten() { Flatten(null, FlatnessDefault); } public void Flatten(Matrix matrix) { Flatten(matrix, FlatnessDefault); } public void Flatten(Matrix matrix, float flatness) { IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.nativeMatrix; int status = SafeNativeMethods.Gdip.GdipFlattenPath(nativePath, m, flatness); SafeNativeMethods.Gdip.CheckStatus(status); } public RectangleF GetBounds() { return GetBounds(null, null); } public RectangleF GetBounds(Matrix matrix) { return GetBounds(matrix, null); } public RectangleF GetBounds(Matrix matrix, Pen pen) { RectangleF retval; IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.nativeMatrix; IntPtr p = (pen == null) ? IntPtr.Zero : pen.NativePen; int s = SafeNativeMethods.Gdip.GdipGetPathWorldBounds(nativePath, out retval, m, p); SafeNativeMethods.Gdip.CheckStatus(s); return retval; } public bool IsOutlineVisible(Point point, Pen pen) { return IsOutlineVisible(point.X, point.Y, pen, null); } public bool IsOutlineVisible(PointF point, Pen pen) { return IsOutlineVisible(point.X, point.Y, pen, null); } public bool IsOutlineVisible(int x, int y, Pen pen) { return IsOutlineVisible(x, y, pen, null); } public bool IsOutlineVisible(float x, float y, Pen pen) { return IsOutlineVisible(x, y, pen, null); } public bool IsOutlineVisible(Point pt, Pen pen, Graphics graphics) { return IsOutlineVisible(pt.X, pt.Y, pen, graphics); } public bool IsOutlineVisible(PointF pt, Pen pen, Graphics graphics) { return IsOutlineVisible(pt.X, pt.Y, pen, graphics); } public bool IsOutlineVisible(int x, int y, Pen pen, Graphics graphics) { if (pen == null) throw new ArgumentNullException("pen"); bool result; IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.nativeObject; int s = SafeNativeMethods.Gdip.GdipIsOutlineVisiblePathPointI(nativePath, x, y, pen.NativePen, g, out result); SafeNativeMethods.Gdip.CheckStatus(s); return result; } public bool IsOutlineVisible(float x, float y, Pen pen, Graphics graphics) { if (pen == null) throw new ArgumentNullException("pen"); bool result; IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.nativeObject; int s = SafeNativeMethods.Gdip.GdipIsOutlineVisiblePathPoint(nativePath, x, y, pen.NativePen, g, out result); SafeNativeMethods.Gdip.CheckStatus(s); return result; } public bool IsVisible(Point point) { return IsVisible(point.X, point.Y, null); } public bool IsVisible(PointF point) { return IsVisible(point.X, point.Y, null); } public bool IsVisible(int x, int y) { return IsVisible(x, y, null); } public bool IsVisible(float x, float y) { return IsVisible(x, y, null); } public bool IsVisible(Point pt, Graphics graphics) { return IsVisible(pt.X, pt.Y, graphics); } public bool IsVisible(PointF pt, Graphics graphics) { return IsVisible(pt.X, pt.Y, graphics); } public bool IsVisible(int x, int y, Graphics graphics) { bool retval; IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.nativeObject; int s = SafeNativeMethods.Gdip.GdipIsVisiblePathPointI(nativePath, x, y, g, out retval); SafeNativeMethods.Gdip.CheckStatus(s); return retval; } public bool IsVisible(float x, float y, Graphics graphics) { bool retval; IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.nativeObject; int s = SafeNativeMethods.Gdip.GdipIsVisiblePathPoint(nativePath, x, y, g, out retval); SafeNativeMethods.Gdip.CheckStatus(s); return retval; } public void SetMarkers() { int s = SafeNativeMethods.Gdip.GdipSetPathMarker(nativePath); SafeNativeMethods.Gdip.CheckStatus(s); } public void StartFigure() { int s = SafeNativeMethods.Gdip.GdipStartPathFigure(nativePath); SafeNativeMethods.Gdip.CheckStatus(s); } [MonoTODO("GdipWarpPath isn't implemented in libgdiplus")] public void Warp(PointF[] destPoints, RectangleF srcRect) { Warp(destPoints, srcRect, null, WarpMode.Perspective, FlatnessDefault); } [MonoTODO("GdipWarpPath isn't implemented in libgdiplus")] public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix matrix) { Warp(destPoints, srcRect, matrix, WarpMode.Perspective, FlatnessDefault); } [MonoTODO("GdipWarpPath isn't implemented in libgdiplus")] public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix matrix, WarpMode warpMode) { Warp(destPoints, srcRect, matrix, warpMode, FlatnessDefault); } [MonoTODO("GdipWarpPath isn't implemented in libgdiplus")] public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix matrix, WarpMode warpMode, float flatness) { if (destPoints == null) throw new ArgumentNullException("destPoints"); IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.nativeMatrix; int s = SafeNativeMethods.Gdip.GdipWarpPath(nativePath, m, destPoints, destPoints.Length, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, warpMode, flatness); SafeNativeMethods.Gdip.CheckStatus(s); } [MonoTODO("GdipWidenPath isn't implemented in libgdiplus")] public void Widen(Pen pen) { Widen(pen, null, FlatnessDefault); } [MonoTODO("GdipWidenPath isn't implemented in libgdiplus")] public void Widen(Pen pen, Matrix matrix) { Widen(pen, matrix, FlatnessDefault); } [MonoTODO("GdipWidenPath isn't implemented in libgdiplus")] public void Widen(Pen pen, Matrix matrix, float flatness) { if (pen == null) throw new ArgumentNullException("pen"); if (PointCount == 0) return; IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.nativeMatrix; int s = SafeNativeMethods.Gdip.GdipWidenPath(nativePath, pen.NativePen, m, flatness); SafeNativeMethods.Gdip.CheckStatus(s); } } }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ // @Generated by gentest/gentest.rb from gentest/fixtures/YGFlexWrapTest.html using System; using NUnit.Framework; namespace Facebook.Yoga { [TestFixture] public class YGFlexWrapTest { [Test] public void Test_wrap_column() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Wrap = YogaWrap.Wrap; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 30; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 30; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 30; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(60f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(30f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(30f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(60f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(30f, root_child3.LayoutX); Assert.AreEqual(0f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(60f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(30f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(30f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(30f, root_child1.LayoutHeight); Assert.AreEqual(30f, root_child2.LayoutX); Assert.AreEqual(60f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(0f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); } [Test] public void Test_wrap_row() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Wrap = YogaWrap.Wrap; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 30; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 30; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 30; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(60f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(30f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(30f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(30f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(60f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(30f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(30f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(30f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); } [Test] public void Test_wrap_row_align_items_flex_end() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.FlexEnd; root.Wrap = YogaWrap.Wrap; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 30; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(60f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(20f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(30f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(60f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(20f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(30f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); } [Test] public void Test_wrap_row_align_items_center() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Center; root.Wrap = YogaWrap.Wrap; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 30; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(60f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(5f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(30f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(60f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(5f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(30f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); } [Test] public void Test_flex_wrap_children_with_min_main_overriding_flex_basis() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Wrap = YogaWrap.Wrap; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.FlexBasis = 50; root_child0.MinWidth = 55; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.FlexBasis = 50; root_child1.MinWidth = 55; root_child1.Height = 50; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(55f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(55f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(45f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(55f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(45f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(55f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); } [Test] public void Test_flex_wrap_wrap_to_child_height() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.AlignItems = YogaAlign.FlexStart; root_child0.Wrap = YogaWrap.Wrap; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.Width = 100; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child0_child0 = new YogaNode(config); root_child0_child0_child0.Width = 100; root_child0_child0_child0.Height = 100; root_child0_child0.Insert(0, root_child0_child0_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 100; root_child1.Height = 100; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(100f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(100f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); } [Test] public void Test_flex_wrap_align_stretch_fits_one_row() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Wrap = YogaWrap.Wrap; root.Width = 150; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 50; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(150f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(0f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(0f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(150f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(100f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(0f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(0f, root_child1.LayoutHeight); } [Test] public void Test_wrap_reverse_row_align_content_flex_start() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Wrap = YogaWrap.WrapReverse; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 40; root.Insert(3, root_child3); YogaNode root_child4 = new YogaNode(config); root_child4.Width = 30; root_child4.Height = 50; root.Insert(4, root_child4); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(30f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(40f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); } [Test] public void Test_wrap_reverse_row_align_content_center() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignContent = YogaAlign.Center; root.Wrap = YogaWrap.WrapReverse; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 40; root.Insert(3, root_child3); YogaNode root_child4 = new YogaNode(config); root_child4.Width = 30; root_child4.Height = 50; root.Insert(4, root_child4); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(30f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(40f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); } [Test] public void Test_wrap_reverse_row_single_line_different_size() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Wrap = YogaWrap.WrapReverse; root.Width = 300; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 40; root.Insert(3, root_child3); YogaNode root_child4 = new YogaNode(config); root_child4.Width = 30; root_child4.Height = 50; root.Insert(4, root_child4); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(300f, root.LayoutWidth); Assert.AreEqual(50f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(40f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(20f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(90f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(120f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(300f, root.LayoutWidth); Assert.AreEqual(50f, root.LayoutHeight); Assert.AreEqual(270f, root_child0.LayoutX); Assert.AreEqual(40f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(240f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(210f, root_child2.LayoutX); Assert.AreEqual(20f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(180f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(150f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); } [Test] public void Test_wrap_reverse_row_align_content_stretch() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignContent = YogaAlign.Stretch; root.Wrap = YogaWrap.WrapReverse; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 40; root.Insert(3, root_child3); YogaNode root_child4 = new YogaNode(config); root_child4.Width = 30; root_child4.Height = 50; root.Insert(4, root_child4); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(30f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(40f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); } [Test] public void Test_wrap_reverse_row_align_content_space_around() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignContent = YogaAlign.SpaceAround; root.Wrap = YogaWrap.WrapReverse; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 40; root.Insert(3, root_child3); YogaNode root_child4 = new YogaNode(config); root_child4.Width = 30; root_child4.Height = 50; root.Insert(4, root_child4); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(30f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(40f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); } [Test] public void Test_wrap_reverse_column_fixed_size() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.Center; root.Wrap = YogaWrap.WrapReverse; root.Width = 200; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 40; root.Insert(3, root_child3); YogaNode root_child4 = new YogaNode(config); root_child4.Width = 30; root_child4.Height = 50; root.Insert(4, root_child4); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(170f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(170f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(170f, root_child2.LayoutX); Assert.AreEqual(30f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(170f, root_child3.LayoutX); Assert.AreEqual(60f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(140f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(30f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(60f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(30f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); } [Test] public void Test_wrapped_row_within_align_items_center() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.Center; root.Width = 200; root.Height = 200; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.Wrap = YogaWrap.Wrap; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.Width = 150; root_child0_child0.Height = 80; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child1 = new YogaNode(config); root_child0_child1.Width = 80; root_child0_child1.Height = 80; root_child0.Insert(1, root_child0_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(160f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(150f, root_child0_child0.LayoutWidth); Assert.AreEqual(80f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child1.LayoutX); Assert.AreEqual(80f, root_child0_child1.LayoutY); Assert.AreEqual(80f, root_child0_child1.LayoutWidth); Assert.AreEqual(80f, root_child0_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(160f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(150f, root_child0_child0.LayoutWidth); Assert.AreEqual(80f, root_child0_child0.LayoutHeight); Assert.AreEqual(120f, root_child0_child1.LayoutX); Assert.AreEqual(80f, root_child0_child1.LayoutY); Assert.AreEqual(80f, root_child0_child1.LayoutWidth); Assert.AreEqual(80f, root_child0_child1.LayoutHeight); } [Test] public void Test_wrapped_row_within_align_items_flex_start() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.FlexStart; root.Width = 200; root.Height = 200; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.Wrap = YogaWrap.Wrap; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.Width = 150; root_child0_child0.Height = 80; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child1 = new YogaNode(config); root_child0_child1.Width = 80; root_child0_child1.Height = 80; root_child0.Insert(1, root_child0_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(160f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(150f, root_child0_child0.LayoutWidth); Assert.AreEqual(80f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child1.LayoutX); Assert.AreEqual(80f, root_child0_child1.LayoutY); Assert.AreEqual(80f, root_child0_child1.LayoutWidth); Assert.AreEqual(80f, root_child0_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(160f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(150f, root_child0_child0.LayoutWidth); Assert.AreEqual(80f, root_child0_child0.LayoutHeight); Assert.AreEqual(120f, root_child0_child1.LayoutX); Assert.AreEqual(80f, root_child0_child1.LayoutY); Assert.AreEqual(80f, root_child0_child1.LayoutWidth); Assert.AreEqual(80f, root_child0_child1.LayoutHeight); } [Test] public void Test_wrapped_row_within_align_items_flex_end() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.FlexEnd; root.Width = 200; root.Height = 200; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.Wrap = YogaWrap.Wrap; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.Width = 150; root_child0_child0.Height = 80; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child1 = new YogaNode(config); root_child0_child1.Width = 80; root_child0_child1.Height = 80; root_child0.Insert(1, root_child0_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(160f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(150f, root_child0_child0.LayoutWidth); Assert.AreEqual(80f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child1.LayoutX); Assert.AreEqual(80f, root_child0_child1.LayoutY); Assert.AreEqual(80f, root_child0_child1.LayoutWidth); Assert.AreEqual(80f, root_child0_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(160f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(150f, root_child0_child0.LayoutWidth); Assert.AreEqual(80f, root_child0_child0.LayoutHeight); Assert.AreEqual(120f, root_child0_child1.LayoutX); Assert.AreEqual(80f, root_child0_child1.LayoutY); Assert.AreEqual(80f, root_child0_child1.LayoutWidth); Assert.AreEqual(80f, root_child0_child1.LayoutHeight); } [Test] public void Test_wrapped_column_max_height() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignContent = YogaAlign.Center; root.AlignItems = YogaAlign.Center; root.Wrap = YogaWrap.Wrap; root.Width = 700; root.Height = 500; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 100; root_child0.Height = 500; root_child0.MaxHeight = 200; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.MarginLeft = 20; root_child1.MarginTop = 20; root_child1.MarginRight = 20; root_child1.MarginBottom = 20; root_child1.Width = 200; root_child1.Height = 200; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 100; root_child2.Height = 100; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(700f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(250f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(200f, root_child0.LayoutHeight); Assert.AreEqual(200f, root_child1.LayoutX); Assert.AreEqual(250f, root_child1.LayoutY); Assert.AreEqual(200f, root_child1.LayoutWidth); Assert.AreEqual(200f, root_child1.LayoutHeight); Assert.AreEqual(420f, root_child2.LayoutX); Assert.AreEqual(200f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(700f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(350f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(200f, root_child0.LayoutHeight); Assert.AreEqual(300f, root_child1.LayoutX); Assert.AreEqual(250f, root_child1.LayoutY); Assert.AreEqual(200f, root_child1.LayoutWidth); Assert.AreEqual(200f, root_child1.LayoutHeight); Assert.AreEqual(180f, root_child2.LayoutX); Assert.AreEqual(200f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); } [Test] public void Test_wrapped_column_max_height_flex() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignContent = YogaAlign.Center; root.AlignItems = YogaAlign.Center; root.Wrap = YogaWrap.Wrap; root.Width = 700; root.Height = 500; YogaNode root_child0 = new YogaNode(config); root_child0.FlexGrow = 1; root_child0.FlexShrink = 1; root_child0.FlexBasis = 0.Percent(); root_child0.Width = 100; root_child0.Height = 500; root_child0.MaxHeight = 200; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.FlexGrow = 1; root_child1.FlexShrink = 1; root_child1.FlexBasis = 0.Percent(); root_child1.MarginLeft = 20; root_child1.MarginTop = 20; root_child1.MarginRight = 20; root_child1.MarginBottom = 20; root_child1.Width = 200; root_child1.Height = 200; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 100; root_child2.Height = 100; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(700f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(300f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(180f, root_child0.LayoutHeight); Assert.AreEqual(250f, root_child1.LayoutX); Assert.AreEqual(200f, root_child1.LayoutY); Assert.AreEqual(200f, root_child1.LayoutWidth); Assert.AreEqual(180f, root_child1.LayoutHeight); Assert.AreEqual(300f, root_child2.LayoutX); Assert.AreEqual(400f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(700f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(300f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(180f, root_child0.LayoutHeight); Assert.AreEqual(250f, root_child1.LayoutX); Assert.AreEqual(200f, root_child1.LayoutY); Assert.AreEqual(200f, root_child1.LayoutWidth); Assert.AreEqual(180f, root_child1.LayoutHeight); Assert.AreEqual(300f, root_child2.LayoutX); Assert.AreEqual(400f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); } [Test] public void Test_wrap_nodes_with_content_sizing_overflowing_margin() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 500; root.Height = 500; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.Wrap = YogaWrap.Wrap; root_child0.Width = 85; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child0_child0 = new YogaNode(config); root_child0_child0_child0.Width = 40; root_child0_child0_child0.Height = 40; root_child0_child0.Insert(0, root_child0_child0_child0); YogaNode root_child0_child1 = new YogaNode(config); root_child0_child1.MarginRight = 10; root_child0.Insert(1, root_child0_child1); YogaNode root_child0_child1_child0 = new YogaNode(config); root_child0_child1_child0.Width = 40; root_child0_child1_child0.Height = 40; root_child0_child1.Insert(0, root_child0_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(85f, root_child0.LayoutWidth); Assert.AreEqual(80f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child1.LayoutX); Assert.AreEqual(40f, root_child0_child1.LayoutY); Assert.AreEqual(40f, root_child0_child1.LayoutWidth); Assert.AreEqual(40f, root_child0_child1.LayoutHeight); Assert.AreEqual(0f, root_child0_child1_child0.LayoutX); Assert.AreEqual(0f, root_child0_child1_child0.LayoutY); Assert.AreEqual(40f, root_child0_child1_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(415f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(85f, root_child0.LayoutWidth); Assert.AreEqual(80f, root_child0.LayoutHeight); Assert.AreEqual(45f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0_child0.LayoutHeight); Assert.AreEqual(35f, root_child0_child1.LayoutX); Assert.AreEqual(40f, root_child0_child1.LayoutY); Assert.AreEqual(40f, root_child0_child1.LayoutWidth); Assert.AreEqual(40f, root_child0_child1.LayoutHeight); Assert.AreEqual(0f, root_child0_child1_child0.LayoutX); Assert.AreEqual(0f, root_child0_child1_child0.LayoutY); Assert.AreEqual(40f, root_child0_child1_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child1_child0.LayoutHeight); } [Test] public void Test_wrap_nodes_with_content_sizing_margin_cross() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 500; root.Height = 500; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.Wrap = YogaWrap.Wrap; root_child0.Width = 70; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child0_child0 = new YogaNode(config); root_child0_child0_child0.Width = 40; root_child0_child0_child0.Height = 40; root_child0_child0.Insert(0, root_child0_child0_child0); YogaNode root_child0_child1 = new YogaNode(config); root_child0_child1.MarginTop = 10; root_child0.Insert(1, root_child0_child1); YogaNode root_child0_child1_child0 = new YogaNode(config); root_child0_child1_child0.Width = 40; root_child0_child1_child0.Height = 40; root_child0_child1.Insert(0, root_child0_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(70f, root_child0.LayoutWidth); Assert.AreEqual(90f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child1.LayoutX); Assert.AreEqual(50f, root_child0_child1.LayoutY); Assert.AreEqual(40f, root_child0_child1.LayoutWidth); Assert.AreEqual(40f, root_child0_child1.LayoutHeight); Assert.AreEqual(0f, root_child0_child1_child0.LayoutX); Assert.AreEqual(0f, root_child0_child1_child0.LayoutY); Assert.AreEqual(40f, root_child0_child1_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(430f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(70f, root_child0.LayoutWidth); Assert.AreEqual(90f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0_child0.LayoutHeight); Assert.AreEqual(30f, root_child0_child1.LayoutX); Assert.AreEqual(50f, root_child0_child1.LayoutY); Assert.AreEqual(40f, root_child0_child1.LayoutWidth); Assert.AreEqual(40f, root_child0_child1.LayoutHeight); Assert.AreEqual(0f, root_child0_child1_child0.LayoutX); Assert.AreEqual(0f, root_child0_child1_child0.LayoutY); Assert.AreEqual(40f, root_child0_child1_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child1_child0.LayoutHeight); } } }
// 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: Define HResult constants. Every exception has one of these. // // //===========================================================================*/ using System; namespace System { // Note: FACILITY_URT is defined as 0x13 (0x8013xxxx). Within that // range, 0x1yyy is for Runtime errors (used for Security, Metadata, etc). // In that subrange, 0x15zz and 0x16zz have been allocated for classlib-type // HResults. Also note that some of our HResults have to map to certain // COM HR's, etc. // Another arbitrary decision... Feel free to change this, as long as you // renumber the HResults yourself (and update rexcep.h). // Reflection will use 0x1600 -> 0x161f. IO will use 0x1620 -> 0x163f. // Security will use 0x1640 -> 0x165f // There are HResults files in the IO, Remoting, Reflection & // Security/Util directories as well, so choose your HResults carefully. internal static class HResults { internal const int APPMODEL_ERROR_NO_PACKAGE = unchecked((int)0x80073D54); internal const int CLDB_E_FILE_CORRUPT = unchecked((int)0x8013110e); internal const int CLDB_E_FILE_OLDVER = unchecked((int)0x80131107); internal const int CLDB_E_INDEX_NOTFOUND = unchecked((int)0x80131124); internal const int CLR_E_BIND_ASSEMBLY_NOT_FOUND = unchecked((int)0x80132004); internal const int CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH = unchecked((int)0x80132001); internal const int CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW = unchecked((int)0x80132000); internal const int CLR_E_BIND_TYPE_NOT_FOUND = unchecked((int)0x80132005); internal const int CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT = unchecked((int)0x80132003); internal const int COR_E_ABANDONEDMUTEX = unchecked((int)0x8013152D); internal const int COR_E_AMBIGUOUSMATCH = unchecked((int)0x8000211D); internal const int COR_E_APPDOMAINUNLOADED = unchecked((int)0x80131014); internal const int COR_E_APPLICATION = unchecked((int)0x80131600); internal const int COR_E_ARGUMENT = unchecked((int)0x80070057); internal const int COR_E_ARGUMENTOUTOFRANGE = unchecked((int)0x80131502); internal const int COR_E_ARITHMETIC = unchecked((int)0x80070216); internal const int COR_E_ARRAYTYPEMISMATCH = unchecked((int)0x80131503); internal const int COR_E_ASSEMBLYEXPECTED = unchecked((int)0x80131018); internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000B); internal const int COR_E_CANNOTUNLOADAPPDOMAIN = unchecked((int)0x80131015); internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); internal const int COR_E_CONTEXTMARSHAL = unchecked((int)0x80131504); internal const int COR_E_CUSTOMATTRIBUTEFORMAT = unchecked((int)0x80131605); internal const int COR_E_DATAMISALIGNED = unchecked((int)0x80131541); internal const int COR_E_DIVIDEBYZERO = unchecked((int)0x80020012); // DISP_E_DIVBYZERO internal const int COR_E_DLLNOTFOUND = unchecked((int)0x80131524); internal const int COR_E_DUPLICATEWAITOBJECT = unchecked((int)0x80131529); internal const int COR_E_ENTRYPOINTNOTFOUND = unchecked((int)0x80131523); internal const int COR_E_EXCEPTION = unchecked((int)0x80131500); internal const int COR_E_EXECUTIONENGINE = unchecked((int)0x80131506); internal const int COR_E_FIELDACCESS = unchecked((int)0x80131507); internal const int COR_E_FIXUPSINEXE = unchecked((int)0x80131019); internal const int COR_E_FORMAT = unchecked((int)0x80131537); internal const int COR_E_INDEXOUTOFRANGE = unchecked((int)0x80131508); internal const int COR_E_INSUFFICIENTEXECUTIONSTACK = unchecked((int)0x80131578); internal const int COR_E_INVALIDCAST = unchecked((int)0x80004002); internal const int COR_E_INVALIDCOMOBJECT = unchecked((int)0x80131527); internal const int COR_E_INVALIDFILTERCRITERIA = unchecked((int)0x80131601); internal const int COR_E_INVALIDOLEVARIANTTYPE = unchecked((int)0x80131531); internal const int COR_E_INVALIDOPERATION = unchecked((int)0x80131509); internal const int COR_E_INVALIDPROGRAM = unchecked((int)0x8013153a); internal const int COR_E_KEYNOTFOUND = unchecked((int)0x80131577); internal const int COR_E_MARSHALDIRECTIVE = unchecked((int)0x80131535); internal const int COR_E_MEMBERACCESS = unchecked((int)0x8013151A); internal const int COR_E_METHODACCESS = unchecked((int)0x80131510); internal const int COR_E_MISSINGFIELD = unchecked((int)0x80131511); internal const int COR_E_MISSINGMANIFESTRESOURCE = unchecked((int)0x80131532); internal const int COR_E_MISSINGMEMBER = unchecked((int)0x80131512); internal const int COR_E_MISSINGMETHOD = unchecked((int)0x80131513); internal const int COR_E_MISSINGSATELLITEASSEMBLY = unchecked((int)0x80131536); internal const int COR_E_MODULE_HASH_CHECK_FAILED = unchecked((int)0x80131039); internal const int COR_E_MULTICASTNOTSUPPORTED = unchecked((int)0x80131514); internal const int COR_E_NEWER_RUNTIME = unchecked((int)0x8013101b); internal const int COR_E_NOTFINITENUMBER = unchecked((int)0x80131528); internal const int COR_E_NOTSUPPORTED = unchecked((int)0x80131515); internal const int COR_E_NULLREFERENCE = unchecked((int)0x80004003); internal const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622); internal const int COR_E_OPERATIONCANCELED = unchecked((int)0x8013153B); internal const int COR_E_OUTOFMEMORY = unchecked((int)0x8007000E); internal const int COR_E_OVERFLOW = unchecked((int)0x80131516); internal const int COR_E_PLATFORMNOTSUPPORTED = unchecked((int)0x80131539); internal const int COR_E_RANK = unchecked((int)0x80131517); internal const int COR_E_REFLECTIONTYPELOAD = unchecked((int)0x80131602); internal const int COR_E_REMOTING = unchecked((int)0x8013150b); internal const int COR_E_RUNTIMEWRAPPED = unchecked((int)0x8013153e); internal const int COR_E_SAFEARRAYRANKMISMATCH = unchecked((int)0x80131538); internal const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked((int)0x80131533); internal const int COR_E_SECURITY = unchecked((int)0x8013150A); internal const int COR_E_SERIALIZATION = unchecked((int)0x8013150C); internal const int COR_E_SERVER = unchecked((int)0x8013150e); internal const int COR_E_STACKOVERFLOW = unchecked((int)0x800703E9); internal const int COR_E_SYNCHRONIZATIONLOCK = unchecked((int)0x80131518); internal const int COR_E_SYSTEM = unchecked((int)0x80131501); internal const int COR_E_TARGET = unchecked((int)0x80131603); internal const int COR_E_TARGETINVOCATION = unchecked((int)0x80131604); internal const int COR_E_TARGETPARAMCOUNT = unchecked((int)0x8002000e); internal const int COR_E_THREADABORTED = unchecked((int)0x80131530); internal const int COR_E_THREADINTERRUPTED = unchecked((int)0x80131519); internal const int COR_E_THREADSTART = unchecked((int)0x80131525); internal const int COR_E_THREADSTATE = unchecked((int)0x80131520); internal const int COR_E_TIMEOUT = unchecked((int)0x80131505); internal const int COR_E_TYPEACCESS = unchecked((int)0x80131543); internal const int COR_E_TYPEINITIALIZATION = unchecked((int)0x80131534); internal const int COR_E_TYPELOAD = unchecked((int)0x80131522); internal const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013); internal const int COR_E_UNAUTHORIZEDACCESS = unchecked((int)0x80070005); internal const int COR_E_VERIFICATION = unchecked((int)0x8013150D); internal const int COR_E_WAITHANDLECANNOTBEOPENED = unchecked((int)0x8013152C); internal const int CORSEC_E_CRYPTO = unchecked((int)0x80131430); internal const int CORSEC_E_CRYPTO_UNEX_OPER = unchecked((int)0x80131431); internal const int CORSEC_E_INVALID_IMAGE_FORMAT = unchecked((int)0x8013141d); internal const int CORSEC_E_INVALID_PUBLICKEY = unchecked((int)0x8013141e); internal const int CORSEC_E_INVALID_STRONGNAME = unchecked((int)0x8013141a); internal const int CORSEC_E_MIN_GRANT_FAIL = unchecked((int)0x80131417); internal const int CORSEC_E_MISSING_STRONGNAME = unchecked((int)0x8013141b); internal const int CORSEC_E_NO_EXEC_PERM = unchecked((int)0x80131418); internal const int CORSEC_E_POLICY_EXCEPTION = unchecked((int)0x80131416); internal const int CORSEC_E_SIGNATURE_MISMATCH = unchecked((int)0x80131420); internal const int CORSEC_E_XMLSYNTAX = unchecked((int)0x80131419); internal const int CTL_E_DEVICEIOERROR = unchecked((int)0x800A0039); internal const int CTL_E_DIVISIONBYZERO = unchecked((int)0x800A000B); internal const int CTL_E_FILENOTFOUND = unchecked((int)0x800A0035); internal const int CTL_E_OUTOFMEMORY = unchecked((int)0x800A0007); internal const int CTL_E_OUTOFSTACKSPACE = unchecked((int)0x800A001C); internal const int CTL_E_OVERFLOW = unchecked((int)0x800A0006); internal const int CTL_E_PATHFILEACCESSERROR = unchecked((int)0x800A004B); internal const int CTL_E_PATHNOTFOUND = unchecked((int)0x800A004C); internal const int CTL_E_PERMISSIONDENIED = unchecked((int)0x800A0046); internal const int E_ELEMENTNOTAVAILABLE = unchecked((int)0x802B001F); internal const int E_ELEMENTNOTENABLED = unchecked((int)0x802B001E); internal const int E_FAIL = unchecked((int)0x80004005); internal const int E_HANDLE = unchecked((int)0x80070006); internal const int E_ILLEGAL_DELEGATE_ASSIGNMENT = unchecked((int)0x80000018); internal const int E_ILLEGAL_METHOD_CALL = unchecked((int)0x8000000E); internal const int E_ILLEGAL_STATE_CHANGE = unchecked((int)0x8000000D); internal const int E_INVALIDARG = unchecked((int)0x80070057); internal const int E_LAYOUTCYCLE = unchecked((int)0x802B0014); internal const int E_NOTIMPL = unchecked((int)0x80004001); internal const int E_OUTOFMEMORY = unchecked((int)0x8007000E); internal const int E_POINTER = unchecked((int)0x80004003L); internal const int E_XAMLPARSEFAILED = unchecked((int)0x802B000A); internal const int ERROR_BAD_EXE_FORMAT = unchecked((int)0x800700C1); internal const int ERROR_BAD_NET_NAME = unchecked((int)0x80070043); internal const int ERROR_BAD_NETPATH = unchecked((int)0x80070035); internal const int ERROR_DISK_CORRUPT = unchecked((int)0x80070571); internal const int ERROR_DLL_INIT_FAILED = unchecked((int)0x8007045A); internal const int ERROR_DLL_NOT_FOUND = unchecked((int)0x80070485); internal const int ERROR_EXE_MARKED_INVALID = unchecked((int)0x800700C0); internal const int ERROR_FILE_CORRUPT = unchecked((int)0x80070570); internal const int ERROR_FILE_INVALID = unchecked((int)0x800703EE); internal const int ERROR_FILE_NOT_FOUND = unchecked((int)0x80070002); internal const int ERROR_INVALID_DLL = unchecked((int)0x80070482); internal const int ERROR_INVALID_NAME = unchecked((int)0x8007007B); internal const int ERROR_INVALID_ORDINAL = unchecked((int)0x800700B6); internal const int ERROR_INVALID_PARAMETER = unchecked((int)0x80070057); internal const int ERROR_LOCK_VIOLATION = unchecked((int)0x80070021); internal const int ERROR_MOD_NOT_FOUND = unchecked((int)0x8007007E); internal const int ERROR_NO_UNICODE_TRANSLATION = unchecked((int)0x80070459); internal const int ERROR_NOACCESS = unchecked((int)0x800703E6); internal const int ERROR_NOT_READY = unchecked((int)0x80070015); internal const int ERROR_OPEN_FAILED = unchecked((int)0x8007006E); internal const int ERROR_PATH_NOT_FOUND = unchecked((int)0x80070003); internal const int ERROR_SHARING_VIOLATION = unchecked((int)0x80070020); internal const int ERROR_TOO_MANY_OPEN_FILES = unchecked((int)0x80070004); internal const int ERROR_UNRECOGNIZED_VOLUME = unchecked((int)0x800703ED); internal const int ERROR_WRONG_TARGET_NAME = unchecked((int)0x80070574); internal const int FUSION_E_ASM_MODULE_MISSING = unchecked((int)0x80131042); internal const int FUSION_E_CACHEFILE_FAILED = unchecked((int)0x80131052); internal const int FUSION_E_CODE_DOWNLOAD_DISABLED = unchecked((int)0x80131048); internal const int FUSION_E_HOST_GAC_ASM_MISMATCH = unchecked((int)0x80131050); internal const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047); internal const int FUSION_E_INVALID_PRIVATE_ASM_LOCATION = unchecked((int)0x80131041); internal const int FUSION_E_LOADFROM_BLOCKED = unchecked((int)0x80131051); internal const int FUSION_E_PRIVATE_ASM_DISALLOWED = unchecked((int)0x80131044); internal const int FUSION_E_REF_DEF_MISMATCH = unchecked((int)0x80131040); internal const int FUSION_E_SIGNATURE_CHECK_FAILED = unchecked((int)0x80131045); internal const int INET_E_CANNOT_CONNECT = unchecked((int)0x800C0004); internal const int INET_E_CONNECTION_TIMEOUT = unchecked((int)0x800C000B); internal const int INET_E_DATA_NOT_AVAILABLE = unchecked((int)0x800C0007); internal const int INET_E_DOWNLOAD_FAILURE = unchecked((int)0x800C0008); internal const int INET_E_OBJECT_NOT_FOUND = unchecked((int)0x800C0006); internal const int INET_E_RESOURCE_NOT_FOUND = unchecked((int)0x800C0005); internal const int INET_E_UNKNOWN_PROTOCOL = unchecked((int)0x800C000D); internal const int ISS_E_ALLOC_TOO_LARGE = unchecked((int)0x80131484); internal const int ISS_E_BLOCK_SIZE_TOO_SMALL = unchecked((int)0x80131483); internal const int ISS_E_CALLER = unchecked((int)0x801314A1); internal const int ISS_E_CORRUPTED_STORE_FILE = unchecked((int)0x80131480); internal const int ISS_E_CREATE_DIR = unchecked((int)0x80131468); internal const int ISS_E_CREATE_MUTEX = unchecked((int)0x80131464); internal const int ISS_E_DEPRECATE = unchecked((int)0x801314A0); internal const int ISS_E_FILE_NOT_MAPPED = unchecked((int)0x80131482); internal const int ISS_E_FILE_WRITE = unchecked((int)0x80131466); internal const int ISS_E_GET_FILE_SIZE = unchecked((int)0x80131463); internal const int ISS_E_ISOSTORE = unchecked((int)0x80131450); internal const int ISS_E_LOCK_FAILED = unchecked((int)0x80131465); internal const int ISS_E_MACHINE = unchecked((int)0x801314A3); internal const int ISS_E_MACHINE_DACL = unchecked((int)0x801314A4); internal const int ISS_E_MAP_VIEW_OF_FILE = unchecked((int)0x80131462); internal const int ISS_E_OPEN_FILE_MAPPING = unchecked((int)0x80131461); internal const int ISS_E_OPEN_STORE_FILE = unchecked((int)0x80131460); internal const int ISS_E_PATH_LENGTH = unchecked((int)0x801314A2); internal const int ISS_E_SET_FILE_POINTER = unchecked((int)0x80131467); internal const int ISS_E_STORE_NOT_OPEN = unchecked((int)0x80131469); internal const int ISS_E_STORE_VERSION = unchecked((int)0x80131481); internal const int ISS_E_TABLE_ROW_NOT_FOUND = unchecked((int)0x80131486); internal const int ISS_E_USAGE_WILL_EXCEED_QUOTA = unchecked((int)0x80131485); internal const int META_E_BAD_SIGNATURE = unchecked((int)0x80131192); internal const int META_E_CA_FRIENDS_SN_REQUIRED = unchecked((int)0x801311e6); internal const int MSEE_E_ASSEMBLYLOADINPROGRESS = unchecked((int)0x80131016); internal const int RO_E_CLOSED = unchecked((int)0x80000013); internal const int E_BOUNDS = unchecked((int)0x8000000B); internal const int RO_E_METADATA_NAME_NOT_FOUND = unchecked((int)0x8000000F); internal const int SECURITY_E_INCOMPATIBLE_EVIDENCE = unchecked((int)0x80131403); internal const int SECURITY_E_INCOMPATIBLE_SHARE = unchecked((int)0x80131401); internal const int SECURITY_E_UNVERIFIABLE = unchecked((int)0x80131402); internal const int STG_E_PATHNOTFOUND = unchecked((int)0x80030003); public const int COR_E_DIRECTORYNOTFOUND = unchecked((int)0x80070003); public const int COR_E_ENDOFSTREAM = unchecked((int)0x80070026); // OS defined public const int COR_E_FILELOAD = unchecked((int)0x80131621); public const int COR_E_FILENOTFOUND = unchecked((int)0x80070002); public const int COR_E_IO = unchecked((int)0x80131620); public const int COR_E_PATHTOOLONG = unchecked((int)0x800700CE); } }
using System; namespace Versioning { public class NominalData : Sage_Container, IData { /* Autogenerated by sage_wrapper_generator.pl */ SageDataObject110.NominalData nd11; SageDataObject120.NominalData nd12; SageDataObject130.NominalData nd13; SageDataObject140.NominalData nd14; SageDataObject150.NominalData nd15; SageDataObject160.NominalData nd16; SageDataObject170.NominalData nd17; public NominalData(object inner, int version) : base(version) { switch (m_version) { case 11: { nd11 = (SageDataObject110.NominalData)inner; m_fields = new Fields(nd11.Fields,m_version); return; } case 12: { nd12 = (SageDataObject120.NominalData)inner; m_fields = new Fields(nd12.Fields,m_version); return; } case 13: { nd13 = (SageDataObject130.NominalData)inner; m_fields = new Fields(nd13.Fields,m_version); return; } case 14: { nd14 = (SageDataObject140.NominalData)inner; m_fields = new Fields(nd14.Fields,m_version); return; } case 15: { nd15 = (SageDataObject150.NominalData)inner; m_fields = new Fields(nd15.Fields,m_version); return; } case 16: { nd16 = (SageDataObject160.NominalData)inner; m_fields = new Fields(nd16.Fields,m_version); return; } case 17: { nd17 = (SageDataObject170.NominalData)inner; m_fields = new Fields(nd17.Fields,m_version); return; } default: throw new InvalidOperationException("ver"); } } /* Autogenerated with data_generator.pl */ const string ACCOUNT_REF = "ACCOUNT_REF"; const string NOMINALDATA = "NominalData"; public bool Open(OpenMode mode) { bool ret; switch (m_version) { case 11: { ret = nd11.Open((SageDataObject110.OpenMode)mode); break; } case 12: { ret = nd12.Open((SageDataObject120.OpenMode)mode); break; } case 13: { ret = nd13.Open((SageDataObject130.OpenMode)mode); break; } case 14: { ret = nd14.Open((SageDataObject140.OpenMode)mode); break; } case 15: { ret = nd15.Open((SageDataObject150.OpenMode)mode); break; } case 16: { ret = nd16.Open((SageDataObject160.OpenMode)mode); break; } case 17: { ret = nd17.Open((SageDataObject170.OpenMode)mode); break; } default: throw new InvalidOperationException("ver"); } return ret; } public void Close() { switch (m_version) { case 11: { nd11.Close(); break; } case 12: { nd12.Close(); break; } case 13: { nd13.Close(); break; } case 14: { nd14.Close(); break; } case 15: { nd15.Close(); break; } case 16: { nd16.Close(); break; } case 17: { nd17.Close(); break; } default: throw new InvalidOperationException("ver"); } } public bool Read(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = nd11.Read(IRecNo); break; } case 12: { ret = nd12.Read(IRecNo); break; } case 13: { ret = nd13.Read(IRecNo); break; } case 14: { ret = nd14.Read(IRecNo); break; } case 15: { ret = nd15.Read(IRecNo); break; } case 16: { ret = nd16.Read(IRecNo); break; } case 17: { ret = nd17.Read(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool Write(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = nd11.Write(IRecNo); break; } case 12: { ret = nd12.Write(IRecNo); break; } case 13: { ret = nd13.Write(IRecNo); break; } case 14: { ret = nd14.Write(IRecNo); break; } case 15: { ret = nd15.Write(IRecNo); break; } case 16: { ret = nd16.Write(IRecNo); break; } case 17: { ret = nd17.Write(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool Seek(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = nd11.Seek(IRecNo); break; } case 12: { ret = nd12.Seek(IRecNo); break; } case 13: { ret = nd13.Seek(IRecNo); break; } case 14: { ret = nd14.Seek(IRecNo); break; } case 15: { ret = nd15.Seek(IRecNo); break; } case 16: { ret = nd16.Seek(IRecNo); break; } case 17: { ret = nd17.Seek(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool Lock(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = nd11.Lock(IRecNo); break; } case 12: { ret = nd12.Lock(IRecNo); break; } case 13: { ret = nd13.Lock(IRecNo); break; } case 14: { ret = nd14.Lock(IRecNo); break; } case 15: { ret = nd15.Lock(IRecNo); break; } case 16: { ret = nd16.Lock(IRecNo); break; } case 17: { ret = nd17.Lock(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool Unlock(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = nd11.Unlock(IRecNo); break; } case 12: { ret = nd12.Unlock(IRecNo); break; } case 13: { ret = nd13.Unlock(IRecNo); break; } case 14: { ret = nd14.Unlock(IRecNo); break; } case 15: { ret = nd15.Unlock(IRecNo); break; } case 16: { ret = nd16.Unlock(IRecNo); break; } case 17: { ret = nd17.Unlock(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool FindFirst(object varField, object varSearch) { bool ret; switch (m_version) { case 11: { ret = nd11.FindFirst(varField, varSearch); break; } case 12: { ret = nd12.FindFirst(varField, varSearch); break; } case 13: { ret = nd13.FindFirst(varField, varSearch); break; } case 14: { ret = nd14.FindFirst(varField, varSearch); break; } case 15: { ret = nd15.FindFirst(varField, varSearch); break; } case 16: { ret = nd16.FindFirst(varField, varSearch); break; } case 17: { ret = nd17.FindFirst(varField, varSearch); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool FindNext(object varField, object varSearch) { bool ret; switch (m_version) { case 11: { ret = nd11.FindNext(varField, varSearch); break; } case 12: { ret = nd12.FindNext(varField, varSearch); break; } case 13: { ret = nd13.FindNext(varField, varSearch); break; } case 14: { ret = nd14.FindNext(varField, varSearch); break; } case 15: { ret = nd15.FindNext(varField, varSearch); break; } case 16: { ret = nd16.FindNext(varField, varSearch); break; } case 17: { ret = nd17.FindNext(varField, varSearch); break; } default: throw new InvalidOperationException("ver"); } return ret; } public int Count { get { int ret; switch (m_version) { case 11: { ret = nd11.Count(); break; } case 12: { ret = nd12.Count(); break; } case 13: { ret = nd13.Count(); break; } case 14: { ret = nd14.Count(); break; } case 15: { ret = nd15.Count(); break; } case 16: { ret = nd16.Count(); break; } case 17: { ret = nd17.Count(); break; } default: throw new InvalidOperationException("ver"); } return ret; } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia.Controls; using Avalonia.UnitTests; using System; using Xunit; namespace Avalonia.Markup.Xaml.UnitTests.Xaml { public class BindingTests_RelativeSource { [Fact] public void Binding_To_DataContext_Works() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <Button Name='button' Content='{Binding Foo, RelativeSource={RelativeSource DataContext}}'/> </Window>"; var loader = new AvaloniaXamlLoader(); var window = (Window)loader.Load(xaml); var button = window.FindControl<Button>("button"); button.DataContext = new { Foo = "foo" }; window.ApplyTemplate(); Assert.Equal("foo", button.Content); } } [Fact] public void Binding_To_Self_Works() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <Button Name='button' Content='{Binding Name, RelativeSource={RelativeSource Self}}'/> </Window>"; var loader = new AvaloniaXamlLoader(); var window = (Window)loader.Load(xaml); var button = window.FindControl<Button>("button"); window.ApplyTemplate(); Assert.Equal("button", button.Content); } } [Fact] public void Binding_To_First_Ancestor_Works() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <Border Name='border1'> <Border Name='border2'> <Button Name='button' Content='{Binding Name, RelativeSource={RelativeSource AncestorType=Border}}'/> </Border> </Border> </Window>"; var loader = new AvaloniaXamlLoader(); var window = (Window)loader.Load(xaml); var button = window.FindControl<Button>("button"); window.ApplyTemplate(); Assert.Equal("border2", button.Content); } } [Fact] public void Binding_To_First_Ancestor_Without_AncestorType_Throws_Exception() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <Border Name='border1'> <ContentControl Name='contentControl'> <Button Name='button' Content='{Binding Name, RelativeSource={RelativeSource AncestorLevel=1}}'/> </ContentControl> </Border> </Window>"; var loader = new AvaloniaXamlLoader(); Assert.Throws<InvalidOperationException>( () => loader.Load(xaml)); } } [Fact] public void Binding_To_First_Ancestor_With_Shorthand_Works() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <Border Name='border1'> <Border Name='border2'> <Button Name='button' Content='{Binding $parent.Name}'/> </Border> </Border> </Window>"; var loader = new AvaloniaXamlLoader(); var window = (Window)loader.Load(xaml); var button = window.FindControl<Button>("button"); window.ApplyTemplate(); Assert.Equal("border2", button.Content); } } [Fact] public void Binding_To_First_Ancestor_With_Shorthand_Uses_LogicalTree() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <Border Name='border'> <ContentControl Name='contentControl'> <Button Name='button' Content='{Binding $parent.Name}'/> </ContentControl> </Border> </Window>"; var loader = new AvaloniaXamlLoader(); var window = (Window)loader.Load(xaml); var contentControl = window.FindControl<ContentControl>("contentControl"); var button = window.FindControl<Button>("button"); window.ApplyTemplate(); Assert.Equal("contentControl", button.Content); } } [Fact] public void Binding_To_Second_Ancestor_Works() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <Border Name='border1'> <Border Name='border2'> <Button Name='button' Content='{Binding Name, RelativeSource={RelativeSource AncestorType=Border, AncestorLevel=2}}'/> </Border> </Border> </Window>"; var loader = new AvaloniaXamlLoader(); var window = (Window)loader.Load(xaml); var button = window.FindControl<Button>("button"); window.ApplyTemplate(); Assert.Equal("border1", button.Content); } } [Fact] public void Binding_To_Second_Ancestor_With_Shorthand_Uses_LogicalTree() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <ContentControl Name='contentControl1'> <ContentControl Name='contentControl2'> <Button Name='button' Content='{Binding $parent[1].Name}'/> </ContentControl> </ContentControl> </Window>"; var loader = new AvaloniaXamlLoader(); var window = (Window)loader.Load(xaml); var contentControl1 = window.FindControl<ContentControl>("contentControl1"); var contentControl2 = window.FindControl<ContentControl>("contentControl2"); var button = window.FindControl<Button>("button"); window.ApplyTemplate(); Assert.Equal("contentControl1", button.Content); } } [Fact] public void Binding_To_Ancestor_Of_Type_With_Shorthand_Works() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <Border Name='border1'> <Border Name='border2'> <Button Name='button' Content='{Binding $parent[Border].Name}'/> </Border> </Border> </Window>"; var loader = new AvaloniaXamlLoader(); var window = (Window)loader.Load(xaml); var button = window.FindControl<Button>("button"); window.ApplyTemplate(); Assert.Equal("border2", button.Content); } } [Fact] public void Binding_To_Second_Ancestor_With_Shorthand_And_Type_Works() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <Border Name='border1'> <Border Name='border2'> <Button Name='button' Content='{Binding $parent[Border; 1].Name}'/> </Border> </Border> </Window>"; var loader = new AvaloniaXamlLoader(); var window = (Window)loader.Load(xaml); var button = window.FindControl<Button>("button"); window.ApplyTemplate(); Assert.Equal("border1", button.Content); } } [Fact] public void Binding_To_Second_Ancestor_With_Shorthand_Works() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <Border Name='border1'> <Border Name='border2'> <Button Name='button' Content='{Binding $parent[1].Name}'/> </Border> </Border> </Window>"; var loader = new AvaloniaXamlLoader(); var window = (Window)loader.Load(xaml); var button = window.FindControl<Button>("button"); window.ApplyTemplate(); Assert.Equal("border1", button.Content); } } [Fact] public void Binding_To_Ancestor_With_Namespace_Works() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <local:TestWindow xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests' Title='title'> <Button Name='button' Content='{Binding Title, RelativeSource={RelativeSource AncestorType=local:TestWindow}}'/> </local:TestWindow>"; var loader = new AvaloniaXamlLoader(); var window = (TestWindow)loader.Load(xaml); var button = window.FindControl<Button>("button"); window.ApplyTemplate(); Assert.Equal("title", button.Content); } } [Fact] public void Shorthand_Binding_With_Negation_Works() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <Border Name='border1'> <Border Name='border2'> <Button Name='button' Content='{Binding !$self.IsDefault}'/> </Border> </Border> </Window>"; var loader = new AvaloniaXamlLoader(); var window = (Window)loader.Load(xaml); var button = window.FindControl<Button>("button"); window.ApplyTemplate(); #pragma warning disable xUnit2004 // Diagnostic mis-firing since button.Content isn't guaranteed to be a bool. Assert.Equal(true, button.Content); #pragma warning restore xUnit2004 } } [Fact] public void Shorthand_Binding_With_Multiple_Negation_Works() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <Border Name='border1'> <Border Name='border2'> <Button Name='button' Content='{Binding !!$self.IsDefault}'/> </Border> </Border> </Window>"; var loader = new AvaloniaXamlLoader(); var window = (Window)loader.Load(xaml); var button = window.FindControl<Button>("button"); window.ApplyTemplate(); #pragma warning disable xUnit2004 // Diagnostic mis-firing since button.Content isn't guaranteed to be a bool. Assert.Equal(false, button.Content); #pragma warning restore xUnit2004 } } } public class TestWindow : Window { } }
// Copyright (c) 2014 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Win32; using SIL.PlatformUtilities; using SIL.Reporting; namespace SIL.IO { public interface IFileLocator { string LocateFile(string fileName); string LocateFile(string fileName, string descriptionForErrorMessage); string LocateOptionalFile(string fileName); string LocateFileWithThrow(string fileName); string LocateDirectory(string directoryName); string LocateDirectoryWithThrow(string directoryName); string LocateDirectory(string directoryName, string descriptionForErrorMessage); IFileLocator CloneAndCustomize(IEnumerable<string> addedSearchPaths); } public interface IChangeableFileLocator : IFileLocator { void AddPath(string path); void RemovePath(string path); } public class FileLocator : IChangeableFileLocator { private readonly List<string> _searchPaths; public FileLocator(IEnumerable<string> searchPaths) { this._searchPaths = new List<string>(searchPaths); } public string LocateFile(string fileName) { foreach (var path in GetSearchPaths()) { var fullPath = Path.Combine(path, fileName); if(File.Exists(fullPath)) return fullPath; } return string.Empty; } /// <summary> /// Subclasses (e.g. in Bloom) override this to provide a dynamic set of paths /// </summary> /// <returns></returns> virtual protected IEnumerable<string> GetSearchPaths() { return _searchPaths; } public string LocateFile(string fileName, string descriptionForErrorMessage) { var path = LocateFile(fileName); if (string.IsNullOrEmpty(path) || !File.Exists(path)) { ErrorReport.NotifyUserOfProblem( "{0} could not find the {1}. It expected to find it in one of these locations: {2}", UsageReporter.AppNameToUseInDialogs, descriptionForErrorMessage, string.Join(", ", GetSearchPaths()) ); } return path; } public string LocateDirectory(string directoryName) { foreach (var path in GetSearchPaths()) { var fullPath = Path.Combine(path, directoryName); if (Directory.Exists(fullPath)) return fullPath; } return string.Empty; } public string LocateDirectory(string directoryName, string descriptionForErrorMessage) { var path = LocateDirectory(directoryName); if (string.IsNullOrEmpty(path) || !Directory.Exists(path)) { ErrorReport.NotifyUserOfProblem( "{0} could not find the {1}. It expected to find it in one of these locations: {2}", UsageReporter.AppNameToUseInDialogs, descriptionForErrorMessage, string.Join(", ", _searchPaths) ); } return path; } public string LocateDirectoryWithThrow(string directoryName) { var path = LocateDirectory(directoryName); if (string.IsNullOrEmpty(path) || !Directory.Exists(path)) { throw new ApplicationException(String.Format("Could not find {0}. It expected to find it in one of these locations: {1}", directoryName, string.Join(Environment.NewLine, _searchPaths))); } return path; } /// <summary> /// /// </summary> /// <param name="fileName"></param> /// <returns>null if not found</returns> public string LocateOptionalFile(string fileName) { var path = LocateFile(fileName); if (string.IsNullOrEmpty(path) || !File.Exists(path)) { return null; } return path; } /// <summary> /// Throws ApplicationException if not found. /// </summary> public string LocateFileWithThrow(string fileName) { var path = LocateFile(fileName); if (string.IsNullOrEmpty(path) || !File.Exists(path)) { throw new ApplicationException("Could not find " + fileName + ". It expected to find it in one of these locations: " + Environment.NewLine + string.Join(Environment.NewLine, _searchPaths)); } return path; } [Obsolete("Use FileLocationUtilities.DirectoryOfApplicationOrSolution")] public static string DirectoryOfApplicationOrSolution => FileLocationUtilities.DirectoryOfApplicationOrSolution; [Obsolete("Use FileLocationUtilities.DirectoryOfTheApplicationExecutable")] public static string DirectoryOfTheApplicationExecutable => FileLocationUtilities.DirectoryOfTheApplicationExecutable; protected List<string> SearchPaths { get { return _searchPaths; } } [Obsolete("Use FileLocationUtilities.LocateExecutable")] public static string LocateExecutable(bool throwExceptionIfNotFound, params string[] partsOfTheSubPath) { return FileLocationUtilities.LocateExecutable(throwExceptionIfNotFound, partsOfTheSubPath); } [Obsolete("Use FileLocationUtilities.LocateExecutable")] public static string LocateExecutable(params string[] partsOfTheSubPath) { return FileLocationUtilities.LocateExecutable(partsOfTheSubPath); } [Obsolete("Use FileLocationUtilities.GetFileDistributedWithApplication")] public static string GetFileDistributedWithApplication(bool optional, params string[] partsOfTheSubPath) { return FileLocationUtilities.GetFileDistributedWithApplication(optional, partsOfTheSubPath); } [Obsolete("Use FileLocationUtilities.GetFileDistributedWithApplication")] public static string GetFileDistributedWithApplication(params string[] partsOfTheSubPath) { return FileLocationUtilities.GetFileDistributedWithApplication(partsOfTheSubPath); } [Obsolete("Use FileLocationUtilities.GetDirectoryDistributedWithApplication")] public static string GetDirectoryDistributedWithApplication(bool optional, params string[] partsOfTheSubPath) { return FileLocationUtilities.GetDirectoryDistributedWithApplication(optional, partsOfTheSubPath); } [Obsolete("Use FileLocationUtilities.GetDirectoryDistributedWithApplication")] public static string GetDirectoryDistributedWithApplication(params string[] partsOfTheSubPath) { return FileLocationUtilities.GetDirectoryDistributedWithApplication(partsOfTheSubPath); } /// <summary> /// Use this when you can't mess with the whole application's filelocator, but you want to add a path or two, e.g., the folder of the current book in Bloom. /// </summary> /// <param name="addedSearchPaths"></param> /// <returns></returns> public virtual IFileLocator CloneAndCustomize(IEnumerable<string> addedSearchPaths) { return new FileLocator(new List<string>(_searchPaths.Concat(addedSearchPaths))); } #region Methods for locating file in program files folders [Obsolete("Use FileLocationUtilities.LocateInProgramFiles")] public static string LocateInProgramFiles(string exeName, bool fallBackToDeepSearch, params string[] subFoldersToSearch) { return FileLocationUtilities.LocateInProgramFiles(exeName, fallBackToDeepSearch, subFoldersToSearch); } /// ------------------------------------------------------------------------------------ /// <summary> /// Searches the registry and returns the full path to the application program used to /// open files having the specified extention. The fileExtension can be with or without /// the preceding period. If the command cannot be found in the registry, then null is /// returned. If a command in the registry is found, but it refers to a program file /// that does not exist, null is returned. /// </summary> /// ------------------------------------------------------------------------------------ public static string GetFromRegistryProgramThatOpensFileType(string fileExtension) { if (!Platform.IsWindows) { //------------------------------------------------------------------------------------ // The following command will output the mime type of an existing file, Phil.html: // file -b --mime-type ~/Phil.html // // This command will tell you the default application to open the file Phil.html: // ext=$(grep "$(file -b --mime-type ~/Phil.html)" /etc/mime.types // | awk '{print $1}') && xdg-mime query default $ext // // This command will open the file Phil.html using the default application: // xdg-open ~/Page.html //------------------------------------------------------------------------------------ throw new NotImplementedException( "GetFromRegistryProgramThatOpensFileType not implemented on Mono yet."); } var ext = fileExtension.Trim(); if (!ext.StartsWith(".")) ext = "." + ext; var key = Registry.ClassesRoot.OpenSubKey(ext); if (key == null) return null; var value = key.GetValue(string.Empty) as string; key.Close(); if (value == null) return null; key = Registry.ClassesRoot.OpenSubKey(string.Format("{0}\\shell\\open\\command", value)); if (key == null && value.ToLower() == "ramp.package") { key = Registry.ClassesRoot.OpenSubKey(string.Format("{0}\\shell\\open\\command", "ramp")); if (key == null) return null; } value = key.GetValue(string.Empty) as string; key.Close(); if (value == null) return null; value = value.Trim('\"', '%', '1', ' '); return (!File.Exists(value) ? null : value); } #endregion public virtual void AddPath(string path) { _searchPaths.Add(path); } public void RemovePath(string path) { _searchPaths.Remove(path); } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace WeifenLuo.WinFormsUI.Docking { [ToolboxItem(false)] internal class VS2005AutoHideStrip : AutoHideStripBase { private class TabVS2005 : Tab { internal TabVS2005(IDockContent content) : base(content) { } private int m_tabX = 0; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth = 0; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } } private const int _ImageHeight = 16; private const int _ImageWidth = 16; private const int _ImageGapTop = 2; private const int _ImageGapLeft = 4; private const int _ImageGapRight = 2; private const int _ImageGapBottom = 2; private const int _TextGapLeft = 0; private const int _TextGapRight = 0; private const int _TabGapTop = 3; private const int _TabGapLeft = 4; private const int _TabGapBetween = 10; #region Customizable Properties public Font TextFont { get { return DockPanel.Theme.Skin.AutoHideStripSkin.TextFont; } } private static StringFormat _stringFormatTabHorizontal; private StringFormat StringFormatTabHorizontal { get { if (_stringFormatTabHorizontal == null) { _stringFormatTabHorizontal = new StringFormat(); _stringFormatTabHorizontal.Alignment = StringAlignment.Near; _stringFormatTabHorizontal.LineAlignment = StringAlignment.Center; _stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap; _stringFormatTabHorizontal.Trimming = StringTrimming.None; } if (RightToLeft == RightToLeft.Yes) _stringFormatTabHorizontal.FormatFlags |= StringFormatFlags.DirectionRightToLeft; else _stringFormatTabHorizontal.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; return _stringFormatTabHorizontal; } } private static StringFormat _stringFormatTabVertical; private StringFormat StringFormatTabVertical { get { if (_stringFormatTabVertical == null) { _stringFormatTabVertical = new StringFormat(); _stringFormatTabVertical.Alignment = StringAlignment.Near; _stringFormatTabVertical.LineAlignment = StringAlignment.Center; _stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical; _stringFormatTabVertical.Trimming = StringTrimming.None; } if (RightToLeft == RightToLeft.Yes) _stringFormatTabVertical.FormatFlags |= StringFormatFlags.DirectionRightToLeft; else _stringFormatTabVertical.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; return _stringFormatTabVertical; } } private static int ImageHeight { get { return _ImageHeight; } } private static int ImageWidth { get { return _ImageWidth; } } private static int ImageGapTop { get { return _ImageGapTop; } } private static int ImageGapLeft { get { return _ImageGapLeft; } } private static int ImageGapRight { get { return _ImageGapRight; } } private static int ImageGapBottom { get { return _ImageGapBottom; } } private static int TextGapLeft { get { return _TextGapLeft; } } private static int TextGapRight { get { return _TextGapRight; } } private static int TabGapTop { get { return _TabGapTop; } } private static int TabGapLeft { get { return _TabGapLeft; } } private static int TabGapBetween { get { return _TabGapBetween; } } private static Pen PenTabBorder { get { return SystemPens.GrayText; } } #endregion private static Matrix _matrixIdentity = new Matrix(); private static Matrix MatrixIdentity { get { return _matrixIdentity; } } private static DockState[] _dockStates; private static DockState[] DockStates { get { if (_dockStates == null) { _dockStates = new DockState[4]; _dockStates[0] = DockState.DockLeftAutoHide; _dockStates[1] = DockState.DockRightAutoHide; _dockStates[2] = DockState.DockTopAutoHide; _dockStates[3] = DockState.DockBottomAutoHide; } return _dockStates; } } private static GraphicsPath _graphicsPath; internal static GraphicsPath GraphicsPath { get { if (_graphicsPath == null) _graphicsPath = new GraphicsPath(); return _graphicsPath; } } public VS2005AutoHideStrip(DockPanel panel) : base(panel) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); BackColor = SystemColors.ControlLight; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics g = e.Graphics; Color startColor = DockPanel.Theme.Skin.AutoHideStripSkin.DockStripGradient.StartColor; Color endColor = DockPanel.Theme.Skin.AutoHideStripSkin.DockStripGradient.EndColor; LinearGradientMode gradientMode = DockPanel.Theme.Skin.AutoHideStripSkin.DockStripGradient.LinearGradientMode; ClientRectangle.SafelyDrawLinearGradient(startColor, endColor, gradientMode, g); DrawTabStrip(g); } protected override void OnLayout(LayoutEventArgs levent) { CalculateTabs(); base.OnLayout(levent); } private void DrawTabStrip(Graphics g) { DrawTabStrip(g, DockState.DockTopAutoHide); DrawTabStrip(g, DockState.DockBottomAutoHide); DrawTabStrip(g, DockState.DockLeftAutoHide); DrawTabStrip(g, DockState.DockRightAutoHide); } private void DrawTabStrip(Graphics g, DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return; Matrix matrixIdentity = g.Transform; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { Matrix matrixRotated = new Matrix(); matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); g.Transform = matrixRotated; } foreach (Pane pane in GetPanes(dockState)) { foreach (TabVS2005 tab in pane.AutoHideTabs) DrawTab(g, tab); } g.Transform = matrixIdentity; } private void CalculateTabs() { CalculateTabs(DockState.DockTopAutoHide); CalculateTabs(DockState.DockBottomAutoHide); CalculateTabs(DockState.DockLeftAutoHide); CalculateTabs(DockState.DockRightAutoHide); } private void CalculateTabs(DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight / ImageHeight); int x = TabGapLeft + rectTabStrip.X; foreach (Pane pane in GetPanes(dockState)) { foreach (TabVS2005 tab in pane.AutoHideTabs) { int width = imageWidth + ImageGapLeft + ImageGapRight + TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width + TextGapLeft + TextGapRight; tab.TabX = x; tab.TabWidth = width; x += width; } x += TabGapBetween; } } private Rectangle RtlTransform(Rectangle rect, DockState dockState) { Rectangle rectTransformed; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) rectTransformed = rect; else rectTransformed = DrawHelper.RtlTransform(this, rect); return rectTransformed; } private GraphicsPath GetTabOutline(TabVS2005 tab, bool transformed, bool rtlTransform) { DockState dockState = tab.Content.DockHandler.DockState; Rectangle rectTab = GetTabRectangle(tab, transformed); if (rtlTransform) rectTab = RtlTransform(rectTab, dockState); bool upTab = (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockBottomAutoHide); DrawHelper.GetRoundedCornerTab(GraphicsPath, rectTab, upTab); return GraphicsPath; } private void DrawTab(Graphics g, TabVS2005 tab) { Rectangle rectTabOrigin = GetTabRectangle(tab); if (rectTabOrigin.IsEmpty) return; DockState dockState = tab.Content.DockHandler.DockState; IDockContent content = tab.Content; GraphicsPath path = GetTabOutline(tab, false, true); Color startColor = DockPanel.Theme.Skin.AutoHideStripSkin.TabGradient.StartColor; Color endColor = DockPanel.Theme.Skin.AutoHideStripSkin.TabGradient.EndColor; LinearGradientMode gradientMode = DockPanel.Theme.Skin.AutoHideStripSkin.TabGradient.LinearGradientMode; using (LinearGradientBrush brushPath = new LinearGradientBrush(rectTabOrigin, startColor, endColor, gradientMode)) { g.FillPath(brushPath, path); } g.DrawPath(PenTabBorder, path); // Set no rotate for drawing icon and text using (Matrix matrixRotate = g.Transform) { g.Transform = MatrixIdentity; // Draw the icon Rectangle rectImage = rectTabOrigin; rectImage.X += ImageGapLeft; rectImage.Y += ImageGapTop; int imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight / ImageHeight); rectImage.Height = imageHeight; rectImage.Width = imageWidth; rectImage = GetTransformedRectangle(dockState, rectImage); if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { // The DockState is DockLeftAutoHide or DockRightAutoHide, so rotate the image 90 degrees to the right. Rectangle rectTransform = RtlTransform(rectImage, dockState); Point[] rotationPoints = { new Point(rectTransform.X + rectTransform.Width, rectTransform.Y), new Point(rectTransform.X + rectTransform.Width, rectTransform.Y + rectTransform.Height), new Point(rectTransform.X, rectTransform.Y) }; using (Icon rotatedIcon = new Icon(((Form)content).Icon, 16, 16)) { g.DrawImage(rotatedIcon.ToBitmap(), rotationPoints); } } else { // Draw the icon normally without any rotation. g.DrawIcon(((Form)content).Icon, RtlTransform(rectImage, dockState)); } // Draw the text Rectangle rectText = rectTabOrigin; rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText = RtlTransform(GetTransformedRectangle(dockState, rectText), dockState); Color textColor = DockPanel.Theme.Skin.AutoHideStripSkin.TabGradient.TextColor; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabVertical); else g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabHorizontal); // Set rotate back g.Transform = matrixRotate; } } private Rectangle GetLogicalTabStripRectangle(DockState dockState) { return GetLogicalTabStripRectangle(dockState, false); } private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed) { if (!DockHelper.IsDockStateAutoHide(dockState)) return Rectangle.Empty; int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count; int rightPanes = GetPanes(DockState.DockRightAutoHide).Count; int topPanes = GetPanes(DockState.DockTopAutoHide).Count; int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count; int x, y, width, height; height = MeasureHeight(); if (dockState == DockState.DockLeftAutoHide && leftPanes > 0) { x = 0; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); } else if (dockState == DockState.DockRightAutoHide && rightPanes > 0) { x = Width - height; if (leftPanes != 0 && x < height) x = height; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); } else if (dockState == DockState.DockTopAutoHide && topPanes > 0) { x = leftPanes == 0 ? 0 : height; y = 0; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0) { x = leftPanes == 0 ? 0 : height; y = Height - height; if (topPanes != 0 && y < height) y = height; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else return Rectangle.Empty; if (width == 0 || height == 0) { return Rectangle.Empty; } var rect = new Rectangle(x, y, width, height); return transformed ? GetTransformedRectangle(dockState, rect) : rect; } private Rectangle GetTabRectangle(TabVS2005 tab) { return GetTabRectangle(tab, false); } private Rectangle GetTabRectangle(TabVS2005 tab, bool transformed) { DockState dockState = tab.Content.DockHandler.DockState; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return Rectangle.Empty; int x = tab.TabX; int y = rectTabStrip.Y + (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ? 0 : TabGapTop); int width = tab.TabWidth; int height = rectTabStrip.Height - TabGapTop; if (!transformed) return new Rectangle(x, y, width, height); else return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); } private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect) { if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide) return rect; PointF[] pts = new PointF[1]; // the center of the rectangle pts[0].X = (float)rect.X + (float)rect.Width / 2; pts[0].Y = (float)rect.Y + (float)rect.Height / 2; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); using (var matrix = new Matrix()) { matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); matrix.TransformPoints(pts); } return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F), (int)(pts[0].Y - (float)rect.Width / 2 + .5F), rect.Height, rect.Width); } protected override IDockContent HitTest(Point point) { foreach (DockState state in DockStates) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true); if (!rectTabStrip.Contains(point)) continue; foreach (Pane pane in GetPanes(state)) { foreach (TabVS2005 tab in pane.AutoHideTabs) { GraphicsPath path = GetTabOutline(tab, true, true); if (path.IsVisible(point)) return tab.Content; } } } return null; } protected override Rectangle GetTabBounds(Tab tab) { GraphicsPath path = GetTabOutline((TabVS2005)tab, true, true); RectangleF bounds = path.GetBounds(); return new Rectangle((int)bounds.Left, (int)bounds.Top, (int)bounds.Width, (int)bounds.Height); } protected override int MeasureHeight() { return Math.Max(ImageGapBottom + ImageGapTop + ImageHeight, TextFont.Height) + TabGapTop; } protected override void OnRefreshChanges() { CalculateTabs(); Invalidate(); } protected override AutoHideStripBase.Tab CreateTab(IDockContent content) { return new TabVS2005(content); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Preview { public class PreviewWorkspaceTests { [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationDefault() { using (var previewWorkspace = new PreviewWorkspace()) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithExplicitHostServices() { var assembly = typeof(ISolutionCrawlerRegistrationService).Assembly; using (var previewWorkspace = new PreviewWorkspace(MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(assembly)))) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithSolution() { using (var custom = new AdhocWorkspace()) using (var previewWorkspace = new PreviewWorkspace(custom.CurrentSolution)) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewAddRemoveProject() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var newSolution = previewWorkspace.CurrentSolution.RemoveProject(project.Id); Assert.True(previewWorkspace.TryApplyChanges(newSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.ProjectIds.Count); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewProjectChanges() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var addedSolution = previewWorkspace.CurrentSolution.Projects.First() .AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib) .AddDocument("document", "").Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(addedSolution)); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); var text = "class C {}"; var changedSolution = previewWorkspace.CurrentSolution.Projects.First().Documents.First().WithText(SourceText.From(text)).Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(changedSolution)); Assert.Equal(previewWorkspace.CurrentSolution.Projects.First().Documents.First().GetTextAsync().Result.ToString(), text); var removedSolution = previewWorkspace.CurrentSolution.Projects.First() .RemoveMetadataReference(previewWorkspace.CurrentSolution.Projects.First().MetadataReferences[0]) .RemoveDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]).Solution; Assert.True(previewWorkspace.TryApplyChanges(removedSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); } } [WorkItem(923121)] [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewOpenCloseFile() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); var document = project.AddDocument("document", ""); Assert.True(previewWorkspace.TryApplyChanges(document.Project.Solution)); previewWorkspace.OpenDocument(document.Id); Assert.Equal(1, previewWorkspace.GetOpenDocumentIds().Count()); Assert.True(previewWorkspace.IsDocumentOpen(document.Id)); previewWorkspace.CloseDocument(document.Id); Assert.Equal(0, previewWorkspace.GetOpenDocumentIds().Count()); Assert.False(previewWorkspace.IsDocumentOpen(document.Id)); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewServices() { using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider()))) { var service = previewWorkspace.Services.GetService<ISolutionCrawlerRegistrationService>(); Assert.True(service is PreviewSolutionCrawlerRegistrationService); var persistentService = previewWorkspace.Services.GetService<IPersistentStorageService>(); Assert.NotNull(persistentService); var storage = persistentService.GetStorage(previewWorkspace.CurrentSolution); Assert.True(storage is NoOpPersistentStorage); } } [WorkItem(923196)] [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewDiagnostic() { var diagnosticService = TestExportProvider.ExportProviderWithCSharpAndVisualBasic.GetExportedValue<IDiagnosticAnalyzerService>() as IDiagnosticUpdateSource; var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a); using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider()))) { var solution = previewWorkspace.CurrentSolution .AddProject("project", "project.dll", LanguageNames.CSharp) .AddDocument("document", "class { }") .Project .Solution; Assert.True(previewWorkspace.TryApplyChanges(solution)); previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]); previewWorkspace.EnableDiagnostic(); // wait 20 seconds taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } var args = taskSource.Task.Result; Assert.True(args.Diagnostics.Length > 0); } } [Fact] public void TestPreviewDiagnosticTagger() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines("class { }")) using (var previewWorkspace = new PreviewWorkspace(workspace.CurrentSolution)) { //// preview workspace and owner of the solution now share solution and its underlying text buffer var hostDocument = workspace.Projects.First().Documents.First(); //// enable preview diagnostics previewWorkspace.EnableDiagnostic(); var spans = SquiggleUtilities.GetErrorSpans(workspace); Assert.Equal(1, spans.Count); } } [Fact] public void TestPreviewDiagnosticTaggerInPreviewPane() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines("class { }")) { // set up listener to wait until diagnostic finish running var diagnosticService = workspace.ExportProvider.GetExportedValue<IDiagnosticService>() as DiagnosticService; // no easy way to setup waiter. kind of hacky way to setup waiter var source = new CancellationTokenSource(); var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => { source.Cancel(); source = new CancellationTokenSource(); var cancellationToken = source.Token; Task.Delay(2000, cancellationToken).ContinueWith(t => taskSource.TrySetResult(a), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current); }; var hostDocument = workspace.Projects.First().Documents.First(); // make a change to remove squiggle var oldDocument = workspace.CurrentSolution.GetDocument(hostDocument.Id); var oldText = oldDocument.GetTextAsync().Result; var newDocument = oldDocument.WithText(oldText.WithChanges(new TextChange(new TextSpan(0, oldText.Length), "class C { }"))); // create a diff view var previewFactoryService = workspace.ExportProvider.GetExportedValue<IPreviewFactoryService>(); var diffView = (IWpfDifferenceViewer)previewFactoryService.CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, CancellationToken.None).PumpingWaitResult(); var foregroundService = workspace.GetService<IForegroundNotificationService>(); var optionsService = workspace.Services.GetService<IOptionService>(); var waiter = new ErrorSquiggleWaiter(); var listeners = AsynchronousOperationListener.CreateListeners(FeatureAttribute.ErrorSquiggles, waiter); // set up tagger for both buffers var leftBuffer = diffView.LeftView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var leftProvider = new DiagnosticsSquiggleTaggerProvider(optionsService, diagnosticService, foregroundService, listeners); var leftTagger = leftProvider.CreateTagger<IErrorTag>(leftBuffer); var rightBuffer = diffView.RightView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var rightProvider = new DiagnosticsSquiggleTaggerProvider(optionsService, diagnosticService, foregroundService, listeners); var rightTagger = rightProvider.CreateTagger<IErrorTag>(rightBuffer); // wait up to 20 seconds for diagnostics taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } // wait taggers waiter.CreateWaitTask().PumpingWait(); // check left buffer var leftSnapshot = leftBuffer.CurrentSnapshot; var leftSpans = leftTagger.GetTags(new NormalizedSnapshotSpanCollection(new SnapshotSpan(leftSnapshot, 0, leftSnapshot.Length))).ToList(); Assert.Equal(1, leftSpans.Count); // check right buffer var rightSnapshot = rightBuffer.CurrentSnapshot; var rightSpans = rightTagger.GetTags(new NormalizedSnapshotSpanCollection(new SnapshotSpan(rightSnapshot, 0, rightSnapshot.Length))).ToList(); Assert.Equal(0, rightSpans.Count); ((IDisposable)leftTagger).Dispose(); ((IDisposable)rightTagger).Dispose(); } } private class ErrorSquiggleWaiter : AsynchronousOperationListener { } } }
// Copyright 2020 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 // // 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 Debugger.Common; using Debugger.RemoteValueRpc; using Grpc.Core; using LldbApi; using System.Linq; using System.Threading.Tasks; using Google.Protobuf; using YetiCommon; using System.Collections.Generic; namespace DebuggerGrpcServer { // Server implementation of RemoteValue RPC. class RemoteValueRpcServiceImpl : RemoteValueRpcService.RemoteValueRpcServiceBase { readonly ObjectStore<RemoteValue> valueStore; readonly ObjectStore<SbType> typeStore; public RemoteValueRpcServiceImpl(ObjectStore<RemoteValue> valueStore, ObjectStore<SbType> typeStore) { this.valueStore = valueStore; this.typeStore = typeStore; } #region RemoteValueRpcService.RemoteValueRpcServiceBase public override Task<BulkDeleteResponse> BulkDelete(BulkDeleteRequest request, ServerCallContext context) { foreach (GrpcSbValue value in request.Values) { valueStore.RemoveObject(value.Id); } return Task.FromResult(new BulkDeleteResponse()); } public override Task<GetValueResponse> GetValue(GetValueRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); value.SetFormat(request.Format.ConvertTo<LldbApi.ValueFormat>()); return Task.FromResult(new GetValueResponse { Value = value.GetValue() }); } public override Task<GetTypeInfoResponse> GetTypeInfo( GetTypeInfoRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); var sbType = value.GetTypeInfo(); var response = new GetTypeInfoResponse(); if (sbType != null) { response.Type = GrpcFactoryUtils.CreateType(sbType, typeStore.AddObject(sbType)); } return Task.FromResult(response); } public override Task<GetTypeNameResponse> GetTypeName(GetTypeNameRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); return Task.FromResult(new GetTypeNameResponse { TypeName = value.GetTypeName() }); } public override Task<GetSummaryResponse> GetSummary(GetSummaryRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); value.SetFormat(request.Format.ConvertTo<LldbApi.ValueFormat>()); return Task.FromResult(new GetSummaryResponse { Summary = value.GetSummary() }); } public override Task<GetValueTypeResponse> GetValueType(GetValueTypeRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); var valueType = value.GetValueType() .ConvertTo<Debugger.Common.ValueType>(); return Task.FromResult(new GetValueTypeResponse { ValueType = valueType }); } public override Task<GetNumChildrenResponse> GetNumChildren(GetNumChildrenRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); return Task.FromResult( new GetNumChildrenResponse { NumChildren = value.GetNumChildren() }); } public override Task<GetChildrenResponse> GetChildren( GetChildrenRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); var children = value.GetChildren(request.Offset, request.Count); var response = new GetChildrenResponse(); for (uint n = 0; n < children.Count; ++n) { RemoteValue child = children[(int)n]; if (child != null) { response.Children[n + request.Offset] = GrpcFactoryUtils.CreateValue(child, valueStore.AddObject(child)); } } // (internal): Special case for pointers. LLDB names them $"*{value.GetName()}", but // Visual Studio just shows an empty name. if (value.TypeIsPointerType() && response.Children.ContainsKey(0) && response.Children[0].Name == $"*{value.GetName()}") { response.Children[0].Name = string.Empty; } return Task.FromResult(response); } public override Task<CreateValueFromExpressionResponse> CreateValueFromExpression( CreateValueFromExpressionRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); var expressionResult = value.CreateValueFromExpression(request.Name, request.Expression); var response = new CreateValueFromExpressionResponse(); if (expressionResult != null) { response.ExpressionResult = GrpcFactoryUtils.CreateValue( expressionResult, valueStore.AddObject(expressionResult)); } return Task.FromResult(response); } public override Task<CreateValueFromAddressResponse> CreateValueFromAddress( CreateValueFromAddressRequest request, ServerCallContext context) { RemoteValue value = valueStore.GetObject(request.Value.Id); RemoteValue expressionResult = value.CreateValueFromAddress( request.Name, request.Address, typeStore.GetObject(request.Type.Id)); var response = new CreateValueFromAddressResponse(); if (expressionResult != null) { response.ExpressionResult = GrpcFactoryUtils.CreateValue( expressionResult, valueStore.AddObject(expressionResult)); } return Task.FromResult(response); } public override Task<EvaluateExpressionResponse> EvaluateExpression( EvaluateExpressionRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); var expressionResult = value.EvaluateExpression(request.Expression); var response = new EvaluateExpressionResponse(); if (expressionResult != null) { response.ExpressionResult = GrpcFactoryUtils.CreateValue( expressionResult, valueStore.AddObject(expressionResult)); } return Task.FromResult(response); } public override Task<EvaluateExpressionLldbEvalResponse> EvaluateExpressionLldbEval( EvaluateExpressionLldbEvalRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); IDictionary<string, SbValue> contextValues = new Dictionary<string, SbValue>(); if (request.ContextVariables != null) { foreach (var contextVariable in request.ContextVariables) { var val = valueStore.GetObject(contextVariable.Value.Id); if (val != null) { contextValues.Add(contextVariable.Name, val.GetSbValue()); } } } var result = value.EvaluateExpressionLldbEval(request.Expression, contextValues); var response = new EvaluateExpressionLldbEvalResponse(); if (result != null) { response.Value = GrpcFactoryUtils.CreateValue(result, valueStore.AddObject(result)); } return Task.FromResult(response); } public override Task<CloneResponse> Clone(CloneRequest request, ServerCallContext context) { RemoteValue value = valueStore.GetObject(request.Value.Id); RemoteValue cloneResult = value.Clone(); var response = new CloneResponse(); if (cloneResult != null) { response.CloneResult = GrpcFactoryUtils.CreateValue(cloneResult, valueStore.AddObject(cloneResult)); } return Task.FromResult(response); } public override Task<DereferenceResponse> Dereference( DereferenceRequest request, ServerCallContext context) { RemoteValue value = valueStore.GetObject(request.Value.Id); RemoteValue dereferenceResult = value.Dereference(); var response = new DereferenceResponse(); if (dereferenceResult != null) { response.DereferenceResult = GrpcFactoryUtils.CreateValue( dereferenceResult, valueStore.AddObject(dereferenceResult)); } return Task.FromResult(response); } public override Task<GetChildMemberWithNameResponse> GetChildMemberWithName( GetChildMemberWithNameRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); var child = value.GetChildMemberWithName(request.Name); var response = new GetChildMemberWithNameResponse(); if (child != null) { response.Child = GrpcFactoryUtils.CreateValue(child, valueStore.AddObject(child)); } return Task.FromResult(response); } public override Task<AddressOfResponse> AddressOf( AddressOfRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); var address = value.AddressOf(); var response = new AddressOfResponse(); if (address != null) { response.AddressValue = GrpcFactoryUtils.CreateValue( address, valueStore.AddObject(address)); } return Task.FromResult(response); } public override Task<TypeIsPointerTypeResponse> TypeIsPointerType( TypeIsPointerTypeRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); return Task.FromResult( new TypeIsPointerTypeResponse { IsPointer = value.TypeIsPointerType() }); } public override Task<GetValueForExpressionPathResponse> GetValueForExpressionPath( GetValueForExpressionPathRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); var childValue = value.GetValueForExpressionPath(request.ExpressionPath); GetValueForExpressionPathResponse response = new GetValueForExpressionPathResponse(); if (childValue != null) { response.Value = GrpcFactoryUtils.CreateValue( childValue, valueStore.AddObject(childValue)); } return Task.FromResult(response); } public override Task<GetExpressionPathResponse> GetExpressionPath( GetExpressionPathRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); string path; bool returnValue = value.GetExpressionPath(out path); return Task.FromResult( new GetExpressionPathResponse { ReturnValue = returnValue, Path = path}); } public override Task<GetCachedViewResponse> GetCachedView( GetCachedViewRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); value.SetFormat(request.Format.ConvertTo<LldbApi.ValueFormat>()); var response = new GetCachedViewResponse { ValueInfo = CreateValueInfoAndUpdateStores(value) }; var addressOf = value.AddressOf(); if (addressOf != null) { response.AddressValue = GrpcFactoryUtils.CreateValue( addressOf, valueStore.AddObject(addressOf)); response.AddressInfo = CreateValueInfoAndUpdateStores(addressOf); } return Task.FromResult(response); } public override Task<GetByteSizeResponse> GetByteSize(GetByteSizeRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); return Task.FromResult( new GetByteSizeResponse { ByteSize = value.GetByteSize() }); } public override Task<GetValueAsUnsignedResponse> GetValueAsUnsigned( GetValueAsUnsignedRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); return Task.FromResult( new GetValueAsUnsignedResponse { Value = value.GetValueAsUnsigned() }); } public override Task<GetPointeeAsByteStringResponse> GetPointeeAsByteString( GetPointeeAsByteStringRequest request, ServerCallContext context) { var value = valueStore.GetObject(request.Value.Id); string error; byte[] data = value.GetPointeeAsByteString(request.CharSize, request.MaxStringSize, out error); return Task.FromResult(new GetPointeeAsByteStringResponse { Data = ByteString.CopyFrom(data ?? new byte[0]), Error = error ?? "" }); } #endregion private GrpcValueInfo CreateValueInfoAndUpdateStores(RemoteValue remoteValue) { if (remoteValue == null) { return null; } string expressionPath; var hasExpressionPath = remoteValue.GetExpressionPath(out expressionPath); var valueInfo = new GrpcValueInfo { ExpressionPath = expressionPath ?? "", HasExpressionPath = hasExpressionPath, NumChildren = remoteValue.GetNumChildren(), Summary = remoteValue.GetSummary() ?? "", TypeName = remoteValue.GetTypeName() ?? "", Value = remoteValue.GetValue() ?? "", ValueType = EnumUtil.ConvertTo<Debugger.Common.ValueType>( remoteValue.GetValueType()), IsPointerType = remoteValue.TypeIsPointerType(), ByteSize = remoteValue.GetByteSize(), }; var typeInfo = remoteValue.GetTypeInfo(); if (typeInfo != null) { valueInfo.Type = GrpcFactoryUtils.CreateType( typeInfo, typeStore.AddObject(typeInfo)); } return valueInfo; } } }
//------------------------------------------------------------------------------ // <copyright file="etwprovider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <OWNER>matell</OWNER> //------------------------------------------------------------------------------ using System; using System.Runtime.InteropServices; #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; #endif #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { [StructLayout(LayoutKind.Explicit, Size = 16)] #if !PROJECTN [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] #endif public struct EventDescriptor { # region private [FieldOffset(0)] private int m_traceloggingId; [FieldOffset(0)] private ushort m_id; [FieldOffset(2)] private byte m_version; [FieldOffset(3)] private byte m_channel; [FieldOffset(4)] private byte m_level; [FieldOffset(5)] private byte m_opcode; [FieldOffset(6)] private ushort m_task; [FieldOffset(8)] private long m_keywords; #endregion public EventDescriptor( int traceloggingId, byte level, byte opcode, long keywords ) { this.m_id = 0; this.m_version = 0; this.m_channel = 0; this.m_traceloggingId = traceloggingId; this.m_level = level; this.m_opcode = opcode; this.m_task = 0; this.m_keywords = keywords; } public EventDescriptor( int id, byte version, byte channel, byte level, byte opcode, int task, long keywords ) { if (id < 0) { #if PROJECTN throw new ArgumentOutOfRangeException("id", SR.GetResourceString("ArgumentOutOfRange_NeedNonNegNum", "ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException("id", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #endif } if (id > ushort.MaxValue) { #if PROJECTN throw new ArgumentOutOfRangeException("id", SR.Format("ArgumentOutOfRange_NeedValidId", 1, ushort.MaxValue)); #else throw new ArgumentOutOfRangeException("id", Environment.GetResourceString("ArgumentOutOfRange_NeedValidId", 1, ushort.MaxValue)); #endif } m_traceloggingId = 0; m_id = (ushort)id; m_version = version; m_channel = channel; m_level = level; m_opcode = opcode; m_keywords = keywords; if (task < 0) { #if PROJECTN throw new ArgumentOutOfRangeException("task", SR.GetResourceString("ArgumentOutOfRange_NeedNonNegNum", "ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException("task", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #endif } if (task > ushort.MaxValue) { #if PROJECTN throw new ArgumentOutOfRangeException("task", SR.Format(SR.GetResourceString("ArgumentOutOfRange_NeedValidId", "ArgumentOutOfRange_NeedValidId"), 1, ushort.MaxValue)); #else throw new ArgumentOutOfRangeException("task", Environment.GetResourceString("ArgumentOutOfRange_NeedValidId", 1, ushort.MaxValue)); #endif } m_task = (ushort)task; } public int EventId { get { return m_id; } } public byte Version { get { return m_version; } } public byte Channel { get { return m_channel; } } public byte Level { get { return m_level; } } public byte Opcode { get { return m_opcode; } } public int Task { get { return m_task; } } public long Keywords { get { return m_keywords; } } public override bool Equals(object obj) { if (!(obj is EventDescriptor)) return false; return Equals((EventDescriptor)obj); } public override int GetHashCode() { return m_id ^ m_version ^ m_channel ^ m_level ^ m_opcode ^ m_task ^ (int)m_keywords; } public bool Equals(EventDescriptor other) { if ((m_id != other.m_id) || (m_version != other.m_version) || (m_channel != other.m_channel) || (m_level != other.m_level) || (m_opcode != other.m_opcode) || (m_task != other.m_task) || (m_keywords != other.m_keywords)) { return false; } return true; } public static bool operator ==(EventDescriptor event1, EventDescriptor event2) { return event1.Equals(event2); } public static bool operator !=(EventDescriptor event1, EventDescriptor event2) { return !event1.Equals(event2); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Parsing.Ast; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.PythonTools.Refactoring { class ImportRemover { private readonly ITextView _view; private readonly PythonAst _ast; private readonly bool _allScopes; private readonly IServiceProvider _serviceProvider; public ImportRemover(IServiceProvider serviceProvider, ITextView textView, bool allScopes) { _view = textView; _serviceProvider = serviceProvider; var snapshot = _view.TextBuffer.CurrentSnapshot; _ast = _view.GetAnalyzer(_serviceProvider).ParseSnapshot(snapshot); _allScopes = allScopes; } internal void RemoveImports() { ScopeStatement targetStmt = null; if (!_allScopes) { var enclosingNodeWalker = new EnclosingNodeWalker(_ast, _view.Caret.Position.BufferPosition, _view.Caret.Position.BufferPosition); _ast.Walk(enclosingNodeWalker); targetStmt = enclosingNodeWalker.Target.Parents[enclosingNodeWalker.Target.Parents.Length - 1]; } var walker = new ImportWalker(targetStmt); _ast.Walk(walker); using (var edit = _view.TextBuffer.CreateEdit()) { foreach (var removeInfo in walker.GetToRemove()) { // see if we're removing some or all of the //var node = removeInfo.Node; var removing = removeInfo.ToRemove; var removed = removeInfo.Statement; UpdatedStatement updatedStatement = removed.InitialStatement; int removeCount = 0; for (int i = 0, curRemoveIndex = 0; i < removed.NameCount; i++) { if (removed.IsRemoved(i, removing)) { removeCount++; updatedStatement = updatedStatement.RemoveName(_ast, curRemoveIndex); } else { curRemoveIndex++; } } var span = removed.Node.GetSpan(_ast); if (removeCount == removed.NameCount) { removeInfo.SiblingCount.Value--; DeleteStatement(edit, span, removeInfo.SiblingCount.Value == 0); } else { var newCode = updatedStatement.ToCodeString(_ast); int proceedingLength = (removed.Node.GetLeadingWhiteSpace(_ast) ?? "").Length; int start = span.Start.Index - proceedingLength; int length = span.Length + proceedingLength; edit.Delete(start, length); edit.Insert(span.Start.Index, newCode); } } edit.Apply(); } } private static void DeleteStatement(VisualStudio.Text.ITextEdit edit, SourceSpan span, bool insertPass) { // remove the entire node, leave any trailing whitespace/comments, but include the // newline and any indentation. int start = span.Start.Index; int length = span.Length; int cur = start - 1; if (!insertPass) { // backup to remove any indentation while (start - 1 > 0) { var curChar = edit.Snapshot.GetText(start - 1, 1); if (curChar[0] == ' ' || curChar[0] == '\t' || curChar[0] == '\f') { length++; start--; } else { break; } } } // extend past any trailing whitespace characters while (start + length < edit.Snapshot.Length) { var curChar = edit.Snapshot.GetText(start + length, 1); if (curChar[0] == ' ' || curChar[0] == '\t' || curChar[0] == '\f') { length++; } else { break; } } // remove the trailing newline as well. if (!insertPass) { if (start + length < edit.Snapshot.Length) { var newlineText = edit.Snapshot.GetText(start + length, 1); if (newlineText == "\r") { if (start + length + 1 < edit.Snapshot.Length) { newlineText = edit.Snapshot.GetText(start + length + 1, 1); if (newlineText == "\n") { length += 2; } else { length++; } } else { length++; } } else if (newlineText == "\n") { length++; } } } edit.Delete(start, length); if (insertPass) { edit.Insert(start, "pass"); } } /// <summary> /// Base class for a statement that we're removing names from. This abstracts away the differences /// between removing names from a "from ... import" statement and an "import " statement so the code /// in RemoveImports can be shared. /// </summary> abstract class RemovedStatement { /// <summary> /// Returns the number of names this statement refers to. /// </summary> public abstract int NameCount { get; } /// <summary> /// Returns true if we're removing the name at the specified index. /// </summary> public abstract bool IsRemoved(int index, HashSet<string> removedNames); /// <summary> /// Gets the initial statement which we can update by removing names from. /// </summary> public abstract UpdatedStatement InitialStatement { get; } /// <summary> /// Gets the node which we're updating - used for getting the span and whitespace info. /// </summary> public abstract Statement Node { get; } } /// <summary> /// Represents a statement that can be edited by repeatedly removing names. /// </summary> abstract class UpdatedStatement { /// <summary> /// Turns the statement back into code. /// </summary> /// <param name="ast"></param> public abstract string ToCodeString(PythonAst ast); /// <summary> /// Removes the name at the given index from the statement returning a new updated statemetn. /// </summary> public abstract UpdatedStatement RemoveName(PythonAst ast, int index); } /// <summary> /// An "import" statement which is having names removed. /// </summary> class RemovedImportStatement : RemovedStatement { private readonly ImportStatement _import; public RemovedImportStatement(ImportStatement removed) { _import = removed; } public override bool IsRemoved(int index, HashSet<string> removedNames) { string name; if (_import.AsNames != null && _import.AsNames[index] != null) { name = _import.AsNames[index].Name; } else { // only the first name becomes available name = _import.Names[index].Names[0].Name; } return removedNames.Contains(name); } public override int NameCount { get { return _import.Names.Count; } } public override UpdatedStatement InitialStatement { get { return new UpdatedImportStatement(_import); } } public override Statement Node { get { return _import; } } class UpdatedImportStatement : UpdatedStatement { private readonly ImportStatement _import; public UpdatedImportStatement(ImportStatement import) { _import = import; } public override string ToCodeString(PythonAst ast) { return _import.ToCodeString(ast); } public override UpdatedStatement RemoveName(PythonAst ast, int index) { return new UpdatedImportStatement(_import.RemoveImport(ast, index)); } } } /// <summary> /// A "from ... import" statement which is having names removed. /// </summary> class RemovedFromImportStatement : RemovedStatement { private readonly FromImportStatement _fromImport; public RemovedFromImportStatement(FromImportStatement fromImport) { _fromImport = fromImport; } public override int NameCount { get { return _fromImport.Names.Count; } } public override bool IsRemoved(int index, HashSet<string> removedNames) { string name; if (_fromImport.AsNames != null && _fromImport.AsNames[index] != null) { name = _fromImport.AsNames[index].Name; } else { // only the first name becomes available name = _fromImport.Names[index].Name; } return removedNames.Contains(name); } public override UpdatedStatement InitialStatement { get { return new UpdatedFromImportStatement(_fromImport); } } public override Statement Node { get { return _fromImport; } } class UpdatedFromImportStatement : UpdatedStatement { private readonly FromImportStatement _fromImport; public UpdatedFromImportStatement(FromImportStatement fromImport) { _fromImport = fromImport; } public override string ToCodeString(PythonAst ast) { return _fromImport.ToCodeString(ast); } public override UpdatedStatement RemoveName(PythonAst ast, int index) { return new UpdatedFromImportStatement(_fromImport.RemoveImport(ast, index)); } } } class ImportRemovalInfo { public readonly HashSet<string> ToRemove = new HashSet<string>(); public readonly RemovedStatement Statement; public readonly StrongBox<int> SiblingCount; public ImportRemovalInfo(ImportStatementInfo statementInfo) { var node = statementInfo.Statement; SiblingCount = statementInfo.Siblings; if (node is FromImportStatement) { Statement = new RemovedFromImportStatement((FromImportStatement)node); } else { Statement = new RemovedImportStatement((ImportStatement)node); } } } /// <summary> /// Tracks a statement and the number of siblings that we share with our parent. /// /// When we remove a complete statement we decrement the number of siblings we have. If /// we remove all of our siblings then we need to insert a pass statement. /// </summary> class ImportStatementInfo { public readonly Statement Statement; public readonly StrongBox<int> Siblings; public ImportStatementInfo(Statement statement, StrongBox<int> siblings) { Statement = statement; Siblings = siblings; } } class ImportWalker : PythonWalker { private readonly List<ScopeStatement> _scopes = new List<ScopeStatement>(); private readonly Dictionary<string, List<ImportStatementInfo>> _importedNames = new Dictionary<string, List<ImportStatementInfo>>(); private readonly HashSet<string> _readNames = new HashSet<string>(); private readonly ScopeStatement _targetStmt; private readonly Dictionary<ScopeStatement, StrongBox<int>> _statementCount = new Dictionary<ScopeStatement, StrongBox<int>>(); public ImportWalker(ScopeStatement targetStmt) { _targetStmt = targetStmt; } public bool InTargetScope { get { return _targetStmt == null || _scopes.Contains(_targetStmt); } } public ICollection<ImportRemovalInfo> GetToRemove() { Dictionary<Statement, ImportRemovalInfo> removeInfo = new Dictionary<Statement, ImportRemovalInfo>(); foreach (var nameAndList in _importedNames) { if (!_readNames.Contains(nameAndList.Key)) { foreach (var node in nameAndList.Value) { ImportRemovalInfo curInfo; if (!removeInfo.TryGetValue(node.Statement, out curInfo)) { removeInfo[node.Statement] = curInfo = new ImportRemovalInfo(node); } curInfo.ToRemove.Add(nameAndList.Key); } } } return removeInfo.Values; } public override bool Walk(ImportStatement node) { if (InTargetScope && !(_scopes[_scopes.Count - 1] is ClassDefinition)) { for (int i = 0; i < node.Names.Count; i++) { if (node.AsNames != null && node.AsNames[i] != null) { var name = node.AsNames[i].Name; TrackImport(node, name); } else { // only the first name becomes available TrackImport(node, node.Names[i].Names[0].Name); } } } return base.Walk(node); } private void TrackImport(Statement node, string name) { var parent = _scopes[_scopes.Count - 1]; StrongBox<int> statementCount; if (!_statementCount.TryGetValue(parent, out statementCount)) { PythonAst outerParent = parent as PythonAst; if (outerParent != null) { // we don't care about the number of children at the top level statementCount = new StrongBox<int>(-1); } else { FunctionDefinition funcDef = parent as FunctionDefinition; if (funcDef != null) { statementCount = GetNumberOfChildStatements(funcDef.Body); } else { var classDef = (ClassDefinition)parent; statementCount = GetNumberOfChildStatements(classDef.Body); } } _statementCount[parent] = statementCount; } List<ImportStatementInfo> imports; if (!_importedNames.TryGetValue(name, out imports)) { _importedNames[name] = imports = new List<ImportStatementInfo>(); } imports.Add(new ImportStatementInfo(node, statementCount)); } private static StrongBox<int> GetNumberOfChildStatements(Statement body) { if (body is SuiteStatement) { return new StrongBox<int>(((SuiteStatement)body).Statements.Count); } else { return new StrongBox<int>(1); } } public override bool Walk(FromImportStatement node) { if (InTargetScope && !node.IsFromFuture && !(_scopes[_scopes.Count - 1] is ClassDefinition)) { for (int i = 0; i < node.Names.Count; i++) { if (node.Names[i].Name == "*") { // ignore from .. import * continue; } if (node.AsNames != null && node.AsNames[i] != null) { TrackImport(node, node.AsNames[i].Name); } else { TrackImport(node, node.Names[i].Name); } } } return base.Walk(node); } public override bool Walk(NameExpression node) { if (InTargetScope) { _readNames.Add(node.Name); } return base.Walk(node); } public override bool Walk(FunctionDefinition node) { _scopes.Add(node); return base.Walk(node); } public override bool Walk(ClassDefinition node) { _scopes.Add(node); return base.Walk(node); } public override bool Walk(PythonAst node) { _scopes.Add(node); return base.Walk(node); } public override void PostWalk(FunctionDefinition node) { _scopes.RemoveAt(_scopes.Count - 1); base.PostWalk(node); } public override void PostWalk(ClassDefinition node) { _scopes.RemoveAt(_scopes.Count - 1); base.PostWalk(node); } public override void PostWalk(PythonAst node) { _scopes.RemoveAt(_scopes.Count - 1); base.PostWalk(node); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // SignedPkcs7.cs // namespace System.Security.Cryptography.Pkcs { using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.Xml; using System.Security.Permissions; using System.Text; using System.Threading; [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class SignedCms { [SecurityCritical] private SafeCryptMsgHandle m_safeCryptMsgHandle; private int m_version; private SubjectIdentifierType m_signerIdentifierType; private ContentInfo m_contentInfo; private bool m_detached; // // Constructors. // public SignedCms () : this(SubjectIdentifierType.IssuerAndSerialNumber, new ContentInfo(Oid.FromOidValue(CAPI.szOID_RSA_data, OidGroup.ExtensionOrAttribute), new byte[0]), false) { } public SignedCms (SubjectIdentifierType signerIdentifierType) : this(signerIdentifierType, new ContentInfo(Oid.FromOidValue(CAPI.szOID_RSA_data, OidGroup.ExtensionOrAttribute), new byte[0]), false) { } public SignedCms (ContentInfo contentInfo) : this(SubjectIdentifierType.IssuerAndSerialNumber, contentInfo, false) {} public SignedCms (SubjectIdentifierType signerIdentifierType, ContentInfo contentInfo) : this(signerIdentifierType, contentInfo, false) {} public SignedCms (ContentInfo contentInfo, bool detached) : this(SubjectIdentifierType.IssuerAndSerialNumber, contentInfo, detached) {} [SecuritySafeCritical] public SignedCms (SubjectIdentifierType signerIdentifierType, ContentInfo contentInfo, bool detached) { if (contentInfo == null) throw new ArgumentNullException("contentInfo"); if (contentInfo.Content == null) throw new ArgumentNullException("contentInfo.Content"); // Reset all states. if (signerIdentifierType != SubjectIdentifierType.SubjectKeyIdentifier && signerIdentifierType != SubjectIdentifierType.IssuerAndSerialNumber && signerIdentifierType != SubjectIdentifierType.NoSignature) { signerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber; } m_safeCryptMsgHandle = SafeCryptMsgHandle.InvalidHandle; m_signerIdentifierType = signerIdentifierType; m_version = 0; m_contentInfo = contentInfo; m_detached = detached; } // // Public APIs. // public int Version { [SecuritySafeCritical] get { // SignedData version can change based on user's operation, so // return the value passed in to the constructor if no message handle is // available. Otherwise, query the version from the handle if (m_safeCryptMsgHandle == null || m_safeCryptMsgHandle.IsInvalid) return m_version; return (int) PkcsUtils.GetVersion(m_safeCryptMsgHandle); } } public ContentInfo ContentInfo { get { return m_contentInfo; } } public bool Detached { get { return m_detached; } } public X509Certificate2Collection Certificates { [SecuritySafeCritical] get { if (m_safeCryptMsgHandle == null || m_safeCryptMsgHandle.IsInvalid) { return new X509Certificate2Collection(); } return PkcsUtils.GetCertificates(m_safeCryptMsgHandle); } } public SignerInfoCollection SignerInfos { [SecuritySafeCritical] get { if (m_safeCryptMsgHandle == null || m_safeCryptMsgHandle.IsInvalid) { return new SignerInfoCollection(); } return new SignerInfoCollection(this); } } [SecuritySafeCritical] public byte[] Encode () { if (m_safeCryptMsgHandle == null || m_safeCryptMsgHandle.IsInvalid) throw new InvalidOperationException(SecurityResources.GetResourceString("Cryptography_Cms_MessageNotSigned")); return PkcsUtils.GetMessage(m_safeCryptMsgHandle); } [SecuritySafeCritical] public void Decode (byte[] encodedMessage) { if (encodedMessage == null) throw new ArgumentNullException("encodedMessage"); if (m_safeCryptMsgHandle != null && !m_safeCryptMsgHandle.IsInvalid) { m_safeCryptMsgHandle.Dispose(); } m_safeCryptMsgHandle = OpenToDecode(encodedMessage, this.ContentInfo, this.Detached); if (!this.Detached) { Oid contentType = PkcsUtils.GetContentType(m_safeCryptMsgHandle); byte[] content = PkcsUtils.GetContent(m_safeCryptMsgHandle); m_contentInfo = new ContentInfo(contentType, content); } } public void ComputeSignature () { ComputeSignature(new CmsSigner(m_signerIdentifierType), true); } public void ComputeSignature (CmsSigner signer) { ComputeSignature(signer, true); } [SecuritySafeCritical] private static int SafeGetLastWin32Error() { return Marshal.GetLastWin32Error(); } [SecuritySafeCritical] public void ComputeSignature (CmsSigner signer, bool silent) { if (signer == null) throw new ArgumentNullException("signer"); if (ContentInfo.Content.Length == 0) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_Empty_Content")); if (SubjectIdentifierType.NoSignature == signer.SignerIdentifierType) { if (m_safeCryptMsgHandle != null && !m_safeCryptMsgHandle.IsInvalid) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_No_Signature_First_Signer")); // First signer. Sign(signer, silent); return; } if (signer.Certificate == null) { if (silent) throw new InvalidOperationException(SecurityResources.GetResourceString("Cryptography_Cms_RecipientCertificateNotFound")); else signer.Certificate = PkcsUtils.SelectSignerCertificate(); } if (!signer.Certificate.HasPrivateKey) throw new CryptographicException(CAPI.NTE_NO_KEY); // CspParameters parameters = new CspParameters(); if (X509Utils.GetPrivateKeyInfo(X509Utils.GetCertContext(signer.Certificate), ref parameters) == false) throw new CryptographicException(SafeGetLastWin32Error()); KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Sign); kp.AccessEntries.Add(entry); kp.Demand(); if (m_safeCryptMsgHandle == null || m_safeCryptMsgHandle.IsInvalid) { // First signer. Sign(signer, silent); } else { // Co-signing. CoSign(signer, silent); } } [SecuritySafeCritical] public void RemoveSignature (int index) { if (m_safeCryptMsgHandle == null || m_safeCryptMsgHandle.IsInvalid) throw new InvalidOperationException(SecurityResources.GetResourceString("Cryptography_Cms_MessageNotSigned")); unsafe { uint dwSigners = 0; uint cbCount = (uint) Marshal.SizeOf(typeof(uint)); if (!CAPI.CAPISafe.CryptMsgGetParam(m_safeCryptMsgHandle, CAPI.CMSG_SIGNER_COUNT_PARAM, 0, new IntPtr(&dwSigners), new IntPtr(&cbCount))) throw new CryptographicException(Marshal.GetLastWin32Error()); if (index < 0 || index >= (int) dwSigners) throw new ArgumentOutOfRangeException("index", SecurityResources.GetResourceString("ArgumentOutOfRange_Index")); if (!CAPI.CryptMsgControl(m_safeCryptMsgHandle, 0, CAPI.CMSG_CTRL_DEL_SIGNER, new IntPtr(&index))) throw new CryptographicException(Marshal.GetLastWin32Error()); } } [SecuritySafeCritical] public void RemoveSignature (SignerInfo signerInfo) { if (signerInfo == null) throw new ArgumentNullException("signerInfo"); RemoveSignature(PkcsUtils.GetSignerIndex(m_safeCryptMsgHandle, signerInfo, 0)); } public void CheckSignature (bool verifySignatureOnly) { CheckSignature(new X509Certificate2Collection(), verifySignatureOnly); } [SecuritySafeCritical] public void CheckSignature (X509Certificate2Collection extraStore, bool verifySignatureOnly) { if (m_safeCryptMsgHandle == null || m_safeCryptMsgHandle.IsInvalid) throw new InvalidOperationException(SecurityResources.GetResourceString("Cryptography_Cms_MessageNotSigned")); if (extraStore == null) throw new ArgumentNullException("extraStore"); CheckSignatures(this.SignerInfos, extraStore, verifySignatureOnly); } [SecuritySafeCritical] public void CheckHash () { if (m_safeCryptMsgHandle == null || m_safeCryptMsgHandle.IsInvalid) throw new InvalidOperationException( SecurityResources.GetResourceString("Cryptography_Cms_MessageNotSigned")); CheckHashes(this.SignerInfos); } // // Internal methods. // [SecurityCritical] internal SafeCryptMsgHandle GetCryptMsgHandle() { return m_safeCryptMsgHandle; } [SecuritySafeCritical] internal void ReopenToDecode () { byte[] encodedMessage = PkcsUtils.GetMessage(m_safeCryptMsgHandle); if (m_safeCryptMsgHandle != null && !m_safeCryptMsgHandle.IsInvalid) { m_safeCryptMsgHandle.Dispose(); } m_safeCryptMsgHandle = OpenToDecode(encodedMessage, this.ContentInfo, this.Detached); } [SecuritySafeCritical] private unsafe void Sign (CmsSigner signer, bool silent) { SafeCryptMsgHandle safeCryptMsgHandle = null; CAPI.CMSG_SIGNED_ENCODE_INFO signedEncodeInfo = new CAPI.CMSG_SIGNED_ENCODE_INFO(Marshal.SizeOf(typeof(CAPI.CMSG_SIGNED_ENCODE_INFO))); CAPI.CMSG_SIGNER_ENCODE_INFO signerEncodeInfo = PkcsUtils.CreateSignerEncodeInfo(signer, silent); byte[] encodedMessage = null; try { SafeLocalAllocHandle pSignerEncodeInfo = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)))); try { Marshal.StructureToPtr(signerEncodeInfo, pSignerEncodeInfo.DangerousGetHandle(), false); X509Certificate2Collection bagOfCerts = PkcsUtils.CreateBagOfCertificates(signer); SafeLocalAllocHandle pEncodedBagOfCerts = PkcsUtils.CreateEncodedCertBlob(bagOfCerts); signedEncodeInfo.cSigners = 1; signedEncodeInfo.rgSigners = pSignerEncodeInfo.DangerousGetHandle(); signedEncodeInfo.cCertEncoded = (uint) bagOfCerts.Count; if (bagOfCerts.Count > 0) signedEncodeInfo.rgCertEncoded = pEncodedBagOfCerts.DangerousGetHandle(); // Because of the way CAPI treats inner content OID, we should pass NULL // for data type, otherwise detached will not work. if (String.Compare(this.ContentInfo.ContentType.Value, CAPI.szOID_RSA_data, StringComparison.OrdinalIgnoreCase) == 0) { safeCryptMsgHandle = CAPI.CryptMsgOpenToEncode(CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, Detached ? CAPI.CMSG_DETACHED_FLAG : 0, CAPI.CMSG_SIGNED, new IntPtr(&signedEncodeInfo), IntPtr.Zero, IntPtr.Zero); } else { safeCryptMsgHandle = CAPI.CryptMsgOpenToEncode(CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, Detached ? CAPI.CMSG_DETACHED_FLAG : 0, CAPI.CMSG_SIGNED, new IntPtr(&signedEncodeInfo), this.ContentInfo.ContentType.Value, IntPtr.Zero); } if (safeCryptMsgHandle == null || safeCryptMsgHandle.IsInvalid) throw new CryptographicException(Marshal.GetLastWin32Error()); if (this.ContentInfo.Content.Length > 0) { if (!CAPI.CAPISafe.CryptMsgUpdate(safeCryptMsgHandle, this.ContentInfo.pContent, (uint) this.ContentInfo.Content.Length, true)) throw new CryptographicException(Marshal.GetLastWin32Error()); } // Retrieve encoded message. encodedMessage = PkcsUtils.GetContent(safeCryptMsgHandle); safeCryptMsgHandle.Dispose(); pEncodedBagOfCerts.Dispose(); } finally { Marshal.DestroyStructure(pSignerEncodeInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)); pSignerEncodeInfo.Dispose(); } } finally { // Don't forget to free all the resource still held inside signerEncodeInfo. signerEncodeInfo.Dispose(); } // Re-open to decode. safeCryptMsgHandle = OpenToDecode(encodedMessage, this.ContentInfo, this.Detached); if (m_safeCryptMsgHandle != null && !m_safeCryptMsgHandle.IsInvalid) { m_safeCryptMsgHandle.Dispose(); } m_safeCryptMsgHandle = safeCryptMsgHandle; GC.KeepAlive(signer); } [SecuritySafeCritical] private void CoSign (CmsSigner signer, bool silent) { CAPI.CMSG_SIGNER_ENCODE_INFO signerEncodeInfo = PkcsUtils.CreateSignerEncodeInfo(signer, silent); try { SafeLocalAllocHandle pSignerEncodeInfo = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)))); try { // Marshal to unmanaged memory. Marshal.StructureToPtr(signerEncodeInfo, pSignerEncodeInfo.DangerousGetHandle(), false); // Add the signature. if (!CAPI.CryptMsgControl(m_safeCryptMsgHandle, 0, CAPI.CMSG_CTRL_ADD_SIGNER, pSignerEncodeInfo.DangerousGetHandle())) throw new CryptographicException(Marshal.GetLastWin32Error()); } finally { Marshal.DestroyStructure(pSignerEncodeInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)); pSignerEncodeInfo.Dispose(); } } finally { // and don't forget to dispose of resources allocated for the structure. signerEncodeInfo.Dispose(); } // Finally, add certs to bag of certs. PkcsUtils.AddCertsToMessage(m_safeCryptMsgHandle, Certificates, PkcsUtils.CreateBagOfCertificates(signer)); } // // Private static methods. // [SecuritySafeCritical] private static SafeCryptMsgHandle OpenToDecode (byte[] encodedMessage, ContentInfo contentInfo, bool detached) { // Open the message for decode. SafeCryptMsgHandle safeCryptMsgHandle = CAPI.CAPISafe.CryptMsgOpenToDecode( CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, detached ? CAPI.CMSG_DETACHED_FLAG : 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); if (safeCryptMsgHandle == null || safeCryptMsgHandle.IsInvalid) throw new CryptographicException(Marshal.GetLastWin32Error()); // ---- the message. if (!CAPI.CAPISafe.CryptMsgUpdate(safeCryptMsgHandle, encodedMessage, (uint) encodedMessage.Length, true)) throw new CryptographicException(Marshal.GetLastWin32Error()); // Make sure this is PKCS7 SignedData type. if (CAPI.CMSG_SIGNED != PkcsUtils.GetMessageType(safeCryptMsgHandle)) throw new CryptographicException(CAPI.CRYPT_E_INVALID_MSG_TYPE); // If detached, then update message with content if available. if (detached) { byte[] content = contentInfo.Content; if (content != null && content.Length > 0) { if (!CAPI.CAPISafe.CryptMsgUpdate(safeCryptMsgHandle, content, (uint) content.Length, true)) throw new CryptographicException(Marshal.GetLastWin32Error()); } } return safeCryptMsgHandle; } private static void CheckSignatures (SignerInfoCollection signers, X509Certificate2Collection extraStore, bool verifySignatureOnly) { if (signers == null || signers.Count < 1) throw new CryptographicException(CAPI.CRYPT_E_NO_SIGNER); foreach (SignerInfo signer in signers) { signer.CheckSignature(extraStore, verifySignatureOnly); if (signer.CounterSignerInfos.Count > 0) CheckSignatures(signer.CounterSignerInfos, extraStore, verifySignatureOnly); } } private static void CheckHashes (SignerInfoCollection signers) { if (signers == null || signers.Count < 1) throw new CryptographicException(CAPI.CRYPT_E_NO_SIGNER); foreach (SignerInfo signer in signers) { if (signer.SignerIdentifier.Type == SubjectIdentifierType.NoSignature) signer.CheckHash(); } } } }
// Copyright (c) 2015 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Reflection; using System.Windows.Forms; using Palaso.Reporting; using Palaso.UI.WindowsForms.Keyboarding; using Palaso.UI.WindowsForms.Spelling; using Palaso.WritingSystems; using Palaso.Text; namespace Palaso.UI.WindowsForms { public partial class StdTextInputBox: TextBox, IControlThatKnowsWritingSystem, ITextInputBox { private IWritingSystemDefinition _writingSystem; private string _previousText; private bool _multiParagraph; private string _nameForLogging; private bool _isSpellCheckingEnabled; /// <summary> /// Don't use this directly, use the Singleton Property TextBoxSpellChecker /// </summary> private static TextBoxSpellChecker _textBoxSpellChecker; public event EventHandler UserLostFocus; public event EventHandler UserGotFocus; public StdTextInputBox() { InitializeComponent(); if (DesignMode) { return; } DoubleBuffered = true; GotFocus += OnGotFocus; LostFocus += OnLostFocus; KeyPress += HandleKeyPress; TextChanged += OnTextChanged; KeyDown += OnKeyDown; if (_nameForLogging == null) { _nameForLogging = "??"; } Name = _nameForLogging; } public Control TheControl { get { return this; } } public void Init(IWritingSystemDefinition writingSystem, String name) { WritingSystem = writingSystem; _nameForLogging = name; if (_nameForLogging == null) { _nameForLogging = "??"; } Name = name; } protected override void OnKeyDown(KeyEventArgs e) { if (Parent is TextInputBox) (Parent as TextInputBox).OnChildKeyDown(e); else base.OnKeyDown(e); } private void OnKeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.PageDown) { e.Handled = false; } } private void OnTextChanged(object sender, EventArgs e) { LanguageForm.AdjustSpansForTextChange(_previousText, Text, Spans); _previousText = Text; } private void OnLostFocus(object sender, EventArgs e) { if (UserLostFocus != null) { UserLostFocus.Invoke(sender, e); } } private void OnGotFocus(object sender, EventArgs e) { if (UserGotFocus != null) { UserGotFocus.Invoke(sender, e); } } protected override void OnTextChanged(EventArgs e) { if (IsDisposed) // are we a zombie still getting events? { throw new ObjectDisposedException(GetType().ToString()); } base.OnTextChanged(e); Height = GetPreferredHeight(Width); #if __MonoCS__ // For some fonts that don't render properly in MONO Refresh(); #endif } // we do this in OnLayout instead of OnResize see // "Setting the Size/Location of child controls in the Resize event // http://blogs.msdn.com/jfoscoding/archive/2005/03/04/385625.aspx protected override void OnLayout(LayoutEventArgs levent) { Height = GetPreferredHeight(Width); base.OnLayout(levent); } // we still need the resize sometimes or ghost fields disappear protected override void OnSizeChanged(EventArgs e) { Height = GetPreferredHeight(Width); base.OnSizeChanged(e); } protected override void OnResize(EventArgs e) { Height = GetPreferredHeight(Width); base.OnResize(e); } public override Size GetPreferredSize(Size proposedSize) { Size size = base.GetPreferredSize(proposedSize); size.Height = GetPreferredHeight(size.Width); return size; } private int _oldWidth = -1; private string _oldText; private Font _oldFont; private int _oldHeight = -1; private int GetPreferredHeight(int width) { if (width == _oldWidth && Text == _oldText && Font == _oldFont && _oldHeight > 0) return _oldHeight; using (Graphics g = CreateGraphics()) { TextFormatFlags flags = TextFormatFlags.TextBoxControl | TextFormatFlags.Default | TextFormatFlags.NoClipping; if (Multiline && WordWrap) { flags |= TextFormatFlags.WordBreak; } if (_writingSystem != null && WritingSystem.RightToLeftScript) { flags |= TextFormatFlags.RightToLeft; } Size sz = TextRenderer.MeasureText(g, Text == String.Empty ? " " : Text + Environment.NewLine, // replace empty string with space, because mono returns zero height for empty string (windows returns one line height) // need extra new line to handle case where ends in new line (since last newline is ignored) Font, new Size(width, int.MaxValue), flags); #if __MonoCS__ // For Mono, need to make an additional adjustment if more than one line is displayed Size sz2 = TextRenderer.MeasureText(g, " ", Font, new Size(width, int.MaxValue), flags); int numberOfLines = sz.Height/ sz2.Height; if (sz.Height % sz2.Height != 0) { numberOfLines++; } if (numberOfLines > 1) { sz.Height += numberOfLines * 4; } #endif _oldHeight = sz.Height + 2; // add enough space for spell checking squiggle underneath _oldWidth = width; _oldText = Text; _oldFont = Font; return _oldHeight; } } public StdTextInputBox(IWritingSystemDefinition ws, string nameForLogging): this() { _nameForLogging = nameForLogging; if (_nameForLogging == null) { _nameForLogging = "??"; } Name = _nameForLogging; WritingSystem = ws; } [Browsable(false)] public override string Text { set { _previousText = value; base.Text = value; } get { return base.Text; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IWritingSystemDefinition WritingSystem { get { return _writingSystem; } set { if (value == null) { throw new ArgumentNullException(); } _writingSystem = value; Font = WritingSystemDefinition.CreateFont(value); if (value.RightToLeftScript) { RightToLeft = RightToLeft.Yes; } else { RightToLeft = RightToLeft.No; } } } public bool MultiParagraph { get { return _multiParagraph; } set { _multiParagraph = value; } } public bool IsSpellCheckingEnabled { get { return _isSpellCheckingEnabled; } set { _isSpellCheckingEnabled = value; if (_isSpellCheckingEnabled && _writingSystem != null && _writingSystem.SpellCheckingId != "none") { OnSpellCheckingEnabled(); } else { OnSpellCheckingDisabled(); } } } private void OnSpellCheckingDisabled() { TextBoxSpellChecker.SetLanguageForSpellChecking(this, null); } private void OnSpellCheckingEnabled() { if (_writingSystem != null) TextBoxSpellChecker.SetLanguageForSpellChecking(this, _writingSystem.SpellCheckingId); } private static TextBoxSpellChecker TextBoxSpellChecker { get { if (_textBoxSpellChecker == null) { _textBoxSpellChecker = new TextBoxSpellChecker(); } return _textBoxSpellChecker; } } protected void HandleKeyPress(object sender, KeyPressEventArgs e) { if (!MultiParagraph && (e.KeyChar == '\r' || e.KeyChar == '\n')) // carriage return e.Handled = true; } protected override void OnEnter(EventArgs e) { base.OnEnter(e); AssignKeyboardFromWritingSystem(); } public void AssignKeyboardFromWritingSystem() { if (_writingSystem != null) _writingSystem.LocalKeyboard.Activate(); } protected override void OnLeave(EventArgs e) { base.OnLeave(e); ClearKeyboard(); } public void ClearKeyboard() { if (_writingSystem != null) Keyboard.Controller.ActivateDefaultKeyboard(); } /// <summary> /// for automated tests /// </summary> public void PretendLostFocus() { OnLostFocus(new EventArgs()); } /// <summary> /// for automated tests /// </summary> public void PretendSetFocus() { Focus(); } public List<LanguageForm.FormatSpan> Spans { get; set; } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G05_SubContinent_Child (editable child object).<br/> /// This is a generated base class of <see cref="G05_SubContinent_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="G04_SubContinent"/> collection. /// </remarks> [Serializable] public partial class G05_SubContinent_Child : BusinessBase<G05_SubContinent_Child> { #region State Fields [NotUndoable] private byte[] _rowVersion = new byte[] {}; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="SubContinent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Sub Continent Child Name"); /// <summary> /// Gets or sets the Sub Continent Child Name. /// </summary> /// <value>The Sub Continent Child Name.</value> public string SubContinent_Child_Name { get { return GetProperty(SubContinent_Child_NameProperty); } set { SetProperty(SubContinent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G05_SubContinent_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="G05_SubContinent_Child"/> object.</returns> internal static G05_SubContinent_Child NewG05_SubContinent_Child() { return DataPortal.CreateChild<G05_SubContinent_Child>(); } /// <summary> /// Factory method. Loads a <see cref="G05_SubContinent_Child"/> object, based on given parameters. /// </summary> /// <param name="parentSubContinent_ID1">The ParentSubContinent_ID1 parameter of the G05_SubContinent_Child to fetch.</param> /// <returns>A reference to the fetched <see cref="G05_SubContinent_Child"/> object.</returns> internal static G05_SubContinent_Child GetG05_SubContinent_Child(int parentSubContinent_ID1) { return DataPortal.FetchChild<G05_SubContinent_Child>(parentSubContinent_ID1); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G05_SubContinent_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G05_SubContinent_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G05_SubContinent_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G05_SubContinent_Child"/> object from the database, based on given criteria. /// </summary> /// <param name="parentSubContinent_ID1">The Parent Sub Continent ID1.</param> protected void Child_Fetch(int parentSubContinent_ID1) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetG05_SubContinent_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID1", parentSubContinent_ID1).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, parentSubContinent_ID1); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="G05_SubContinent_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name")); _rowVersion = dr.GetValue("RowVersion") as byte[]; var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="G05_SubContinent_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G04_SubContinent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddG05_SubContinent_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); _rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value; } } } /// <summary> /// Updates in the database all changes made to the <see cref="G05_SubContinent_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(G04_SubContinent parent) { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateG05_SubContinent_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@RowVersion", _rowVersion).DbType = DbType.Binary; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); _rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value; } } } /// <summary> /// Self deletes the <see cref="G05_SubContinent_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(G04_SubContinent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteG05_SubContinent_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Collections.Generic; using ImGuiNET; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Num = System.Numerics; namespace Nez.ImGuiTools { public partial class ImGuiManager : GlobalManager, IFinalRenderDelegate, IDisposable { public bool ShowDemoWindow = false; public bool ShowStyleEditor = false; public bool ShowSceneGraphWindow = true; public bool ShowCoreWindow = true; public bool ShowSeperateGameWindow = true; public bool ShowMenuBar = true; public bool FocusGameWindowOnMiddleClick = false; public bool FocusGameWindowOnRightClick = false; public bool DisableKeyboardInputWhenGameWindowUnfocused = true; public bool DisableMouseWheelWhenGameWindowUnfocused = true; List<Type> _sceneSubclasses = new List<Type>(); System.Reflection.MethodInfo[] _themes; CoreWindow _coreWindow = new CoreWindow(); SceneGraphWindow _sceneGraphWindow = new SceneGraphWindow(); SpriteAtlasEditorWindow _spriteAtlasEditorWindow; List<EntityInspector> _entityInspectors = new List<EntityInspector>(); List<Action> _drawCommands = new List<Action>(); ImGuiRenderer _renderer; Num.Vector2 _gameWindowFirstPosition; string _gameWindowTitle; ImGuiWindowFlags _gameWindowFlags = 0; RenderTarget2D _lastRenderTarget; IntPtr _renderTargetId = IntPtr.Zero; Num.Vector2? _gameViewForcedSize; WindowPosition? _gameViewForcedPos; float _mainMenuBarHeight; public ImGuiManager(ImGuiOptions options = null) { if (options == null) options = new ImGuiOptions(); _gameWindowFirstPosition = options._gameWindowFirstPosition; _gameWindowTitle = options._gameWindowTitle; _gameWindowFlags = options._gameWindowFlags; LoadSettings(); _renderer = new ImGuiRenderer(Core.Instance); _renderer.RebuildFontAtlas(options); Core.Emitter.AddObserver(CoreEvents.SceneChanged, OnSceneChanged); NezImGuiThemes.DarkTheme1(); // find all Scenes _sceneSubclasses = ReflectionUtils.GetAllSubclasses(typeof(Scene), true); // tone down indent ImGui.GetStyle().IndentSpacing = 12; ImGui.GetIO().ConfigWindowsMoveFromTitleBarOnly = true; // find all themes _themes = typeof(NezImGuiThemes).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); } /// <summary> /// this is where we issue any and all ImGui commands to be drawn /// </summary> void LayoutGui() { if (ShowMenuBar) DrawMainMenuBar(); if (ShowSeperateGameWindow) DrawGameWindow(); DrawEntityInspectors(); for (var i = _drawCommands.Count - 1; i >= 0; i--) _drawCommands[i](); _sceneGraphWindow.Show(ref ShowSceneGraphWindow); _coreWindow.Show(ref ShowCoreWindow); if (_spriteAtlasEditorWindow != null) { if (!_spriteAtlasEditorWindow.Show()) _spriteAtlasEditorWindow = null; } if (ShowDemoWindow) ImGui.ShowDemoWindow(ref ShowDemoWindow); if (ShowStyleEditor) { ImGui.Begin("Style Editor", ref ShowStyleEditor); ImGui.ShowStyleEditor(); ImGui.End(); } } /// <summary> /// draws the main menu bar /// </summary> void DrawMainMenuBar() { if (ImGui.BeginMainMenuBar()) { _mainMenuBarHeight = ImGui.GetWindowHeight(); if (ImGui.BeginMenu("File")) { if (ImGui.MenuItem("Open Sprite Atlas Editor")) _spriteAtlasEditorWindow = _spriteAtlasEditorWindow ?? new SpriteAtlasEditorWindow(); if (ImGui.MenuItem("Quit ImGui")) SetEnabled(false); ImGui.EndMenu(); } if (_sceneSubclasses.Count > 0 && ImGui.BeginMenu("Scenes")) { foreach (var sceneType in _sceneSubclasses) { if (ImGui.MenuItem(sceneType.Name)) { var scene = (Scene) Activator.CreateInstance(sceneType); Core.StartSceneTransition(new FadeTransition(() => scene)); } } ImGui.EndMenu(); } if (_themes.Length > 0 && ImGui.BeginMenu("Themes")) { foreach (var theme in _themes) { if (ImGui.MenuItem(theme.Name)) theme.Invoke(null, new object[] { }); } ImGui.EndMenu(); } if (ImGui.BeginMenu("Game View")) { var rtSize = Core.Scene.SceneRenderTargetSize; if (ImGui.BeginMenu("Resize")) { if (ImGui.MenuItem("0.25x")) _gameViewForcedSize = new Num.Vector2(rtSize.X / 4f, rtSize.Y / 4f); if (ImGui.MenuItem("0.5x")) _gameViewForcedSize = new Num.Vector2(rtSize.X / 2f, rtSize.Y / 2f); if (ImGui.MenuItem("0.75x")) _gameViewForcedSize = new Num.Vector2(rtSize.X / 1.33f, rtSize.Y / 1.33f); if (ImGui.MenuItem("1x")) _gameViewForcedSize = new Num.Vector2(rtSize.X, rtSize.Y); if (ImGui.MenuItem("1.5x")) _gameViewForcedSize = new Num.Vector2(rtSize.X * 1.5f, rtSize.Y * 1.5f); if (ImGui.MenuItem("2x")) _gameViewForcedSize = new Num.Vector2(rtSize.X * 2, rtSize.Y * 2); if (ImGui.MenuItem("3x")) _gameViewForcedSize = new Num.Vector2(rtSize.X * 3, rtSize.Y * 3); ImGui.EndMenu(); } if (ImGui.BeginMenu("Reposition")) { foreach (var pos in Enum.GetNames(typeof(WindowPosition))) { if (ImGui.MenuItem(pos)) _gameViewForcedPos = (WindowPosition) Enum.Parse(typeof(WindowPosition), pos); } ImGui.EndMenu(); } ImGui.EndMenu(); } if (ImGui.BeginMenu("Window")) { ImGui.MenuItem("ImGui Demo Window", null, ref ShowDemoWindow); ImGui.MenuItem("Style Editor", null, ref ShowStyleEditor); if (ImGui.MenuItem("Open imgui_demo.cpp on GitHub")) { var url = "https://github.com/ocornut/imgui/blob/master/imgui_demo.cpp"; var startInfo = new System.Diagnostics.ProcessStartInfo(url) { UseShellExecute = true }; System.Diagnostics.Process.Start(startInfo); } ImGui.Separator(); ImGui.MenuItem("Core Window", null, ref ShowCoreWindow); ImGui.MenuItem("Scene Graph Window", null, ref ShowSceneGraphWindow); ImGui.MenuItem("Separate Game Window", null, ref ShowSeperateGameWindow); ImGui.EndMenu(); } ImGui.EndMainMenuBar(); } } /// <summary> /// draws all the EntityInspectors /// </summary> void DrawEntityInspectors() { for (var i = _entityInspectors.Count - 1; i >= 0; i--) _entityInspectors[i].Draw(); } #region Public API /// <summary> /// registers an Action that will be called and any ImGui drawing can be done in it /// </summary> /// <param name="drawCommand"></param> public void RegisterDrawCommand(Action drawCommand) => _drawCommands.Add(drawCommand); /// <summary> /// removes the Action from the draw commands /// </summary> /// <param name="drawCommand"></param> public void UnregisterDrawCommand(Action drawCommand) => _drawCommands.Remove(drawCommand); /// <summary> /// Creates a pointer to a texture, which can be passed through ImGui calls such as <see cref="ImGui.Image" />. /// That pointer is then used by ImGui to let us know what texture to draw /// </summary> /// <param name="textureId"></param> public void UnbindTexture(IntPtr textureId) => _renderer.UnbindTexture(textureId); /// <summary> /// Removes a previously created texture pointer, releasing its reference and allowing it to be deallocated /// </summary> /// <param name="texture"></param> /// <returns></returns> public IntPtr BindTexture(Texture2D texture) => _renderer.BindTexture(texture); /// <summary> /// creates an EntityInspector window /// </summary> /// <param name="entity"></param> public void StartInspectingEntity(Entity entity) { // if we are already inspecting the Entity focus the window foreach (var inspector in _entityInspectors) { if (inspector.Entity == entity) { inspector.SetWindowFocus(); return; } } var entityInspector = new EntityInspector(entity); entityInspector.SetWindowFocus(); _entityInspectors.Add(entityInspector); } /// <summary> /// removes the EntityInspector for this Entity /// </summary> /// <param name="entity"></param> public void StopInspectingEntity(Entity entity) { for (var i = 0; i < _entityInspectors.Count; i++) { var inspector = _entityInspectors[i]; if (inspector.Entity == entity) { _entityInspectors.RemoveAt(i); return; } } } /// <summary> /// removes the EntityInspector /// </summary> /// <param name="entityInspector"></param> public void StopInspectingEntity(EntityInspector entityInspector) { _entityInspectors.RemoveAt(_entityInspectors.IndexOf(entityInspector)); } #endregion } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// Represents a gRPC channel. Channels are an abstraction of long-lived connections to remote servers. /// More client objects can reuse the same channel. Creating a channel is an expensive operation compared to invoking /// a remote call so in general you should reuse a single channel for as many calls as possible. /// </summary> public class Channel { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>(); readonly object myLock = new object(); readonly AtomicCounter activeCallCounter = new AtomicCounter(); readonly string target; readonly GrpcEnvironment environment; readonly ChannelSafeHandle handle; readonly List<ChannelOption> options; bool shutdownRequested; /// <summary> /// Creates a channel that connects to a specific host. /// Port will default to 80 for an unsecure channel and to 443 for a secure channel. /// </summary> /// <param name="target">Target of the channel.</param> /// <param name="credentials">Credentials to secure the channel.</param> /// <param name="options">Channel options.</param> public Channel(string target, ChannelCredentials credentials, IEnumerable<ChannelOption> options = null) { this.target = Preconditions.CheckNotNull(target, "target"); this.environment = GrpcEnvironment.AddRef(); this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>(); EnsureUserAgentChannelOption(this.options); using (var nativeCredentials = credentials.ToNativeCredentials()) using (var nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options)) { if (nativeCredentials != null) { this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs); } else { this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs); } } } /// <summary> /// Creates a channel that connects to a specific host and port. /// </summary> /// <param name="host">The name or IP address of the host.</param> /// <param name="port">The port.</param> /// <param name="credentials">Credentials to secure the channel.</param> /// <param name="options">Channel options.</param> public Channel(string host, int port, ChannelCredentials credentials, IEnumerable<ChannelOption> options = null) : this(string.Format("{0}:{1}", host, port), credentials, options) { } /// <summary> /// Gets current connectivity state of this channel. /// </summary> public ChannelState State { get { return handle.CheckConnectivityState(false); } } /// <summary> /// Returned tasks completes once channel state has become different from /// given lastObservedState. /// If deadline is reached or and error occurs, returned task is cancelled. /// </summary> public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null) { Preconditions.CheckArgument(lastObservedState != ChannelState.FatalFailure, "FatalFailure is a terminal state. No further state changes can occur."); var tcs = new TaskCompletionSource<object>(); var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture; var handler = new BatchCompletionDelegate((success, ctx) => { if (success) { tcs.SetResult(null); } else { tcs.SetCanceled(); } }); handle.WatchConnectivityState(lastObservedState, deadlineTimespec, environment.CompletionQueue, environment.CompletionRegistry, handler); return tcs.Task; } /// <summary>Resolved address of the remote endpoint in URI format.</summary> public string ResolvedTarget { get { return handle.GetTarget(); } } /// <summary>The original target used to create the channel.</summary> public string Target { get { return this.target; } } /// <summary> /// Allows explicitly requesting channel to connect without starting an RPC. /// Returned task completes once state Ready was seen. If the deadline is reached, /// or channel enters the FatalFailure state, the task is cancelled. /// There is no need to call this explicitly unless your use case requires that. /// Starting an RPC on a new channel will request connection implicitly. /// </summary> /// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param> public async Task ConnectAsync(DateTime? deadline = null) { var currentState = handle.CheckConnectivityState(true); while (currentState != ChannelState.Ready) { if (currentState == ChannelState.FatalFailure) { throw new OperationCanceledException("Channel has reached FatalFailure state."); } await WaitForStateChangedAsync(currentState, deadline); currentState = handle.CheckConnectivityState(false); } } /// <summary> /// Waits until there are no more active calls for this channel and then cleans up /// resources used by this channel. /// </summary> public async Task ShutdownAsync() { lock (myLock) { Preconditions.CheckState(!shutdownRequested); shutdownRequested = true; } var activeCallCount = activeCallCounter.Count; if (activeCallCount > 0) { Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount); } handle.Dispose(); await Task.Run(() => GrpcEnvironment.Release()); } internal ChannelSafeHandle Handle { get { return this.handle; } } internal GrpcEnvironment Environment { get { return this.environment; } } internal void AddCallReference(object call) { activeCallCounter.Increment(); bool success = false; handle.DangerousAddRef(ref success); Preconditions.CheckState(success); } internal void RemoveCallReference(object call) { handle.DangerousRelease(); activeCallCounter.Decrement(); } private static void EnsureUserAgentChannelOption(List<ChannelOption> options) { if (!options.Any((option) => option.Name == ChannelOptions.PrimaryUserAgentString)) { options.Add(new ChannelOption(ChannelOptions.PrimaryUserAgentString, GetUserAgentString())); } } private static string GetUserAgentString() { // TODO(jtattermusch): it would be useful to also provide .NET/mono version. return string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion); } } }
// // GraphService.cs // // Author: // Henning Rauch <Henning@RauchEntwicklung.biz> // // Copyright (c) 2012-2015 Henning Rauch // // 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. #region Usings using Framework.Serialization; using Microsoft.CSharp; using NoSQL.GraphDB.Algorithms.Path; using NoSQL.GraphDB.Helper; using NoSQL.GraphDB.Index; using NoSQL.GraphDB.Index.Fulltext; using NoSQL.GraphDB.Index.Spatial; using NoSQL.GraphDB.Model; using NoSQL.GraphDB.Service.REST.Result; using NoSQL.GraphDB.Service.REST.Specification; using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net; using System.Reflection; using System.ServiceModel; using System.Text; using NoSQL.GraphDB.Log; #endregion namespace NoSQL.GraphDB.Service.REST { /// <summary> /// Fallen-8 REST service. /// </summary> [ServiceBehavior (ConcurrencyMode = ConcurrencyMode.Multiple, IncludeExceptionDetailInFaults = true)] public sealed class GraphService : IGraphService, IDisposable { #region Data /// <summary> /// The internal Fallen-8 instance /// </summary> private readonly Fallen8 _fallen8; #region Code generation stuff private readonly CSharpCodeProvider _codeProvider; private readonly CompilerParameters _compilerParameters; private const String PathDelegateClassName = "NoSQL.GraphDB.Algorithms.Path.PathDelegateProvider"; private readonly String _pathDelegateClassPrefix = CodeGeneration.Prefix; private readonly String _pathDelegateClassSuffix = CodeGeneration.Suffix; private const String VertexFilterMethodName = "VertexFilter"; private const String EdgeFilterMethodName = "EdgeFilter"; private const String EdgePropertyFilterMethodName = "EdgePropertyFilter"; private const String VertexCostMethodName = "VertexCost"; private const String EdgeCostMethodName = "EdgeCost"; #endregion #endregion #region Constructor /// <summary> /// Initializes a new instance of the GraphService class. /// </summary> /// <param name='fallen8'> Fallen-8. </param> public GraphService (Fallen8 fallen8) { _fallen8 = fallen8; _compilerParameters = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true, TreatWarningsAsErrors = false, IncludeDebugInformation = false, CompilerOptions = "/optimize /target:library", }; var curAss = Assembly.GetAssembly (fallen8.GetType ()); _compilerParameters.ReferencedAssemblies.Add ("System.dll"); _compilerParameters.ReferencedAssemblies.Add ("mscorlib.dll"); _compilerParameters.ReferencedAssemblies.Add ("System.dll"); _compilerParameters.ReferencedAssemblies.Add ("System.Data.dll"); _compilerParameters.ReferencedAssemblies.Add (curAss.Location); _codeProvider = new CSharpCodeProvider (new Dictionary<string, string> { { "CompilerVersion", "v4.5" } }); } #endregion #region IDisposable Members public void Dispose() { _codeProvider.Dispose(); } #endregion #region IGraphService implementation public int AddVertex(VertexSpecification definition) { #region initial checks if (definition == null) { throw new ArgumentNullException("definition"); } #endregion return _fallen8.CreateVertex(definition.CreationDate, ServiceHelper.GenerateProperties(definition.Properties)).Id; } public int AddEdge(EdgeSpecification definition) { #region initial checks if (definition == null) { throw new ArgumentNullException("definition"); } #endregion return _fallen8.CreateEdge(definition.SourceVertex, definition.EdgePropertyId, definition.TargetVertex, definition.CreationDate, ServiceHelper.GenerateProperties(definition.Properties)).Id; } /// <summary> /// Gets the graph element properties. /// </summary> /// <returns> The graph element properties. </returns> /// <param name='graphElementIdentifier'> Vertex identifier. </param> public PropertiesREST GetAllGraphelementProperties(string graphElementIdentifier) { AGraphElement vertex; if (_fallen8.TryGetGraphElement(out vertex, Convert.ToInt32(graphElementIdentifier))) { return new PropertiesREST { Id = vertex.Id, CreationDate = DateHelper.GetDateTimeFromUnixTimeStamp(vertex.CreationDate), ModificationDate = DateHelper.GetDateTimeFromUnixTimeStamp(vertex.CreationDate + vertex.ModificationDate), Properties = vertex.GetAllProperties().ToDictionary(key => key.PropertyId, value => value.Value.ToString()) }; } return null; } public int GetSourceVertexForEdge(string edgeIdentifier) { EdgeModel edge; if (_fallen8.TryGetEdge(out edge, Convert.ToInt32(edgeIdentifier))) { return edge.SourceVertex.Id; } throw new WebException(String.Format("Could not find edge with id {0}.", edgeIdentifier)); } public int GetTargetVertexForEdge(string edgeIdentifier) { EdgeModel edge; if (_fallen8.TryGetEdge(out edge, Convert.ToInt32(edgeIdentifier))) { return edge.TargetVertex.Id; } throw new WebException(String.Format("Could not find edge with id {0}.", edgeIdentifier)); } public List<ushort> GetAllAvailableOutEdgesOnVertex(string vertexIdentifier) { VertexModel vertex; return _fallen8.TryGetVertex(out vertex, Convert.ToInt32(vertexIdentifier)) ? vertex.GetOutgoingEdgeIds() : null; } public List<ushort> GetAllAvailableIncEdgesOnVertex(string vertexIdentifier) { VertexModel vertex; return _fallen8.TryGetVertex(out vertex, Convert.ToInt32(vertexIdentifier)) ? vertex.GetIncomingEdgeIds() : null; } public List<int> GetOutgoingEdges(string vertexIdentifier, string edgePropertyIdentifier) { VertexModel vertex; if (_fallen8.TryGetVertex(out vertex, Convert.ToInt32(vertexIdentifier))) { ReadOnlyCollection<EdgeModel> edges; if (vertex.TryGetOutEdge(out edges, Convert.ToUInt16(edgePropertyIdentifier))) { return edges.Select(_ => _.Id).ToList(); } } return null; } public List<int> GetIncomingEdges(string vertexIdentifier, string edgePropertyIdentifier) { VertexModel vertex; if (_fallen8.TryGetVertex(out vertex, Convert.ToInt32(vertexIdentifier))) { ReadOnlyCollection<EdgeModel> edges; if (vertex.TryGetInEdge(out edges, Convert.ToUInt16(edgePropertyIdentifier))) { return edges.Select(_ => _.Id).ToList(); } } return null; } public IEnumerable<int> GraphScan(String propertyIdString, ScanSpecification definition) { #region initial checks if (definition == null) { throw new ArgumentNullException("definition"); } #endregion var propertyId = Convert.ToUInt16(propertyIdString); IComparable value = definition.Literal.FullQualifiedTypeName == null ? definition.Literal.Value : (IComparable)Convert.ChangeType(definition.Literal.Value, Type.GetType(definition.Literal.FullQualifiedTypeName, true, true)); List<AGraphElement> graphElements; return _fallen8.GraphScan(out graphElements, propertyId, value, definition.Operator) ? CreateResult(graphElements, definition.ResultType) : Enumerable.Empty<Int32>(); } public IEnumerable<int> IndexScan(IndexScanSpecification definition) { #region initial checks if (definition == null) { throw new ArgumentNullException("definition"); } #endregion IComparable value = definition.Literal.FullQualifiedTypeName == null ? definition.Literal.Value : (IComparable)Convert.ChangeType(definition.Literal.Value, Type.GetType(definition.Literal.FullQualifiedTypeName, true, true)); ReadOnlyCollection<AGraphElement> graphElements; return _fallen8.IndexScan(out graphElements, definition.IndexId, value, definition.Operator) ? CreateResult(graphElements, definition.ResultType) : Enumerable.Empty<Int32>(); } public IEnumerable<int> RangeIndexScan(RangeIndexScanSpecification definition) { #region initial checks if (definition == null) { throw new ArgumentNullException("definition"); } #endregion var left = (IComparable)Convert.ChangeType(definition.LeftLimit, Type.GetType(definition.FullQualifiedTypeName, true, true)); var right = (IComparable)Convert.ChangeType(definition.RightLimit, Type.GetType(definition.FullQualifiedTypeName, true, true)); ReadOnlyCollection<AGraphElement> graphElements; return _fallen8.RangeIndexScan(out graphElements, definition.IndexId, left, right, definition.IncludeLeft, definition.IncludeRight) ? CreateResult(graphElements, definition.ResultType) : Enumerable.Empty<Int32>(); } public FulltextSearchResultREST FulltextIndexScan(FulltextIndexScanSpecification definition) { #region initial checks if (definition == null) { throw new ArgumentNullException("definition"); } #endregion FulltextSearchResult result; return _fallen8.FulltextIndexScan(out result, definition.IndexId, definition.RequestString) ? new FulltextSearchResultREST(result) : null; } public IEnumerable<int> SpatialIndexScanSearchDistance(SearchDistanceSpecification definition) { #region initial checks if (definition == null) { throw new ArgumentNullException("definition"); } #endregion AGraphElement graphElement; if (_fallen8.TryGetGraphElement(out graphElement, definition.GraphElementId)) { IIndex idx; if (_fallen8.IndexFactory.TryGetIndex(out idx, definition.IndexId)) { var spatialIndex = idx as ISpatialIndex; if (spatialIndex != null) { ReadOnlyCollection<AGraphElement> result; return spatialIndex.SearchDistance(out result, definition.Distance, graphElement) ? result.Select(_ => _.Id) : null; } Logger.LogError(String.Format("The index with id {0} is no spatial index.", definition.IndexId)); return null; } Logger.LogError(String.Format("Could not find index {0}.", definition.IndexId)); return null; } Logger.LogError(String.Format("Could not find graph element {0}.", definition.GraphElementId)); return null; } public bool TryAddProperty(string graphElementIdString, string propertyIdString, PropertySpecification definition) { var graphElementId = Convert.ToInt32(graphElementIdString); var propertyId = Convert.ToUInt16(propertyIdString); var property = Convert.ChangeType( definition.Property, Type.GetType(definition.FullQualifiedTypeName, true, true)); return _fallen8.TryAddProperty(graphElementId, propertyId, property); } public bool TryRemoveProperty(string graphElementIdString, string propertyIdString) { var graphElementId = Convert.ToInt32(graphElementIdString); var propertyId = Convert.ToUInt16(propertyIdString); return _fallen8.TryRemoveProperty(graphElementId, propertyId); } public bool TryRemoveGraphElement(string graphElementIdString) { var graphElementId = Convert.ToInt32(graphElementIdString); return _fallen8.TryRemoveGraphElement(graphElementId); } public uint GetInDegree(string vertexIdentifier) { VertexModel vertex; if (_fallen8.TryGetVertex(out vertex, Convert.ToInt32(vertexIdentifier))) { return vertex.GetInDegree(); } return 0; } public uint GetOutDegree(string vertexIdentifier) { VertexModel vertex; if (_fallen8.TryGetVertex(out vertex, Convert.ToInt32(vertexIdentifier))) { return vertex.GetOutDegree(); } return 0; } public uint GetInEdgeDegree(string vertexIdentifier, string edgePropertyIdentifier) { VertexModel vertex; if (_fallen8.TryGetVertex(out vertex, Convert.ToInt32(vertexIdentifier))) { ReadOnlyCollection<EdgeModel> edges; if (vertex.TryGetInEdge(out edges, Convert.ToUInt16(edgePropertyIdentifier))) { return Convert.ToUInt32(edges.Count); } } return 0; } public uint GetOutEdgeDegree(string vertexIdentifier, string edgePropertyIdentifier) { VertexModel vertex; if (_fallen8.TryGetVertex(out vertex, Convert.ToInt32(vertexIdentifier))) { ReadOnlyCollection<EdgeModel> edges; if (vertex.TryGetOutEdge(out edges, Convert.ToUInt16(edgePropertyIdentifier))) { return Convert.ToUInt32(edges.Count); } } return 0; } public List<PathREST> GetPaths(string from, string to, PathSpecification definition) { if (definition != null) { var fromId = Convert.ToInt32(from); var toId = Convert.ToInt32(to); var results = _codeProvider.CompileAssemblyFromSource(_compilerParameters, new[] { CreateSource(definition) }); if (results.Errors.HasErrors) { throw new Exception(CreateErrorMessage(results.Errors)); } var type = results.CompiledAssembly.GetType(PathDelegateClassName); var edgeCostDelegate = CreateEdgeCostDelegate(definition.Cost, type); var vertexCostDelegate = CreateVertexCostDelegate(definition.Cost, type); var edgePropertyFilterDelegate = CreateEdgePropertyFilterDelegate(definition.Filter, type); var vertexFilterDelegate = CreateVertexFilterDelegate(definition.Filter, type); var edgeFilterDelegate = CreateEdgeFilterDelegate(definition.Filter, type); List<Path> paths; if (_fallen8.CalculateShortestPath( out paths, definition.PathAlgorithmName, fromId, toId, definition.MaxDepth, definition.MaxPathWeight, definition.MaxResults, edgePropertyFilterDelegate, vertexFilterDelegate, edgeFilterDelegate, edgeCostDelegate, vertexCostDelegate)) { if (paths != null) { return new List<PathREST>(paths.Select(aPath => new PathREST(aPath))); } } } return null; } public List<PathREST> GetPathsByVertex(string from, string to, PathSpecification definition) { return GetPaths(from, to, definition); } public bool CreateIndex(PluginSpecification definition) { IIndex result; return _fallen8.IndexFactory.TryCreateIndex(out result, definition.UniqueId, definition.PluginType, ServiceHelper.CreatePluginOptions(definition.PluginOptions)); } public bool AddToIndex(IndexAddToSpecification definition) { IIndex idx; if (_fallen8.IndexFactory.TryGetIndex(out idx, definition.IndexId)) { AGraphElement graphElement; if (_fallen8.TryGetGraphElement(out graphElement, definition.GraphElementId)) { idx.AddOrUpdate(ServiceHelper.CreateObject(definition.Key), graphElement); return true; } Logger.LogError(String.Format("Could not find graph element {0}.", definition.GraphElementId)); return false; } Logger.LogError(String.Format("Could not find index {0}.", definition.IndexId)); return false; } public bool RemoveKeyFromIndex(IndexRemoveKeyFromIndexSpecification definition) { IIndex idx; if (_fallen8.IndexFactory.TryGetIndex(out idx, definition.IndexId)) { return idx.TryRemoveKey(ServiceHelper.CreateObject(definition.Key)); } Logger.LogError(String.Format("Could not find index {0}.", definition.IndexId)); return false; } public bool RemoveGraphElementFromIndex(IndexRemoveGraphelementFromIndexSpecification definition) { IIndex idx; if (_fallen8.IndexFactory.TryGetIndex(out idx, definition.IndexId)) { AGraphElement graphElement; if (_fallen8.TryGetGraphElement(out graphElement, definition.GraphElementId)) { idx.RemoveValue(graphElement); return true; } Logger.LogError(String.Format("Could not find graph element {0}.", definition.GraphElementId)); return false; } Logger.LogError(String.Format("Could not find index {0}.", definition.IndexId)); return false; } public bool DeleteIndex(IndexDeleteSpecificaton definition) { return _fallen8.IndexFactory.TryDeleteIndex(definition.IndexId); } #endregion #region private helper /// <summary> /// Create the source for the code generation /// </summary> /// <param name="definition">The path specification</param> /// <returns>The source code</returns> private string CreateSource(PathSpecification definition) { if (definition == null) return string.Empty; var sb = new StringBuilder(); sb.AppendLine(_pathDelegateClassPrefix); if (definition.Cost != null) { if (definition.Cost.Edge != null) { sb.AppendLine(definition.Cost.Edge); } if (definition.Cost.Vertex != null) { sb.AppendLine(definition.Cost.Vertex); } } if (definition.Filter != null) { if (definition.Filter.Edge != null) { sb.AppendLine(definition.Filter.Edge); } if (definition.Filter.EdgeProperty != null) { sb.AppendLine(definition.Filter.EdgeProperty); } if (definition.Filter.Vertex != null) { sb.AppendLine(definition.Filter.Vertex); } } sb.AppendLine(_pathDelegateClassSuffix); return sb.ToString(); } /// <summary> /// Creates an error message. /// </summary> /// <param name="compilerErrorCollection">The compiler error collection</param> /// <returns>The error string</returns> private static string CreateErrorMessage(CompilerErrorCollection compilerErrorCollection) { if (compilerErrorCollection == null) throw new ArgumentNullException("compilerErrorCollection"); var sb = new StringBuilder(); sb.AppendLine("Error building request"); foreach (var aError in compilerErrorCollection) { sb.AppendLine(aError.ToString()); } return sb.ToString(); } /// <summary> /// Creates an edge filter delegate /// </summary> /// <param name="pathFilterSpecification">Filter specification.</param> /// <param name="pathDelegateType">The path delegate type </param> /// <returns>The delegate</returns> private static PathDelegates.EdgeFilter CreateEdgeFilterDelegate(PathFilterSpecification pathFilterSpecification, Type pathDelegateType) { if (pathFilterSpecification != null && !String.IsNullOrEmpty(pathFilterSpecification.Edge)) { var method = pathDelegateType.GetMethod(EdgeFilterMethodName); return (PathDelegates.EdgeFilter)Delegate.CreateDelegate(typeof(PathDelegates.EdgeFilter), method); } return null; } /// <summary> /// Creates a vertex filter delegate /// </summary> /// <param name="pathFilterSpecification">Filter specification.</param> /// <param name="pathDelegateType">The path delegate type </param> /// <returns>The delegate</returns> private static PathDelegates.VertexFilter CreateVertexFilterDelegate(PathFilterSpecification pathFilterSpecification, Type pathDelegateType) { if (pathFilterSpecification != null && !String.IsNullOrEmpty(pathFilterSpecification.Vertex)) { var method = pathDelegateType.GetMethod(VertexFilterMethodName); return (PathDelegates.VertexFilter)Delegate.CreateDelegate(typeof(PathDelegates.VertexFilter), method); } return null; } /// <summary> /// Creates an edge property filter delegate /// </summary> /// <param name="pathFilterSpecification">Filter specification.</param> /// <param name="pathDelegateType">The path delegate type </param> /// <returns>The delegate</returns> private static PathDelegates.EdgePropertyFilter CreateEdgePropertyFilterDelegate(PathFilterSpecification pathFilterSpecification, Type pathDelegateType) { if (pathFilterSpecification != null && !String.IsNullOrEmpty(pathFilterSpecification.EdgeProperty)) { var method = pathDelegateType.GetMethod(EdgePropertyFilterMethodName); return (PathDelegates.EdgePropertyFilter)Delegate.CreateDelegate(typeof(PathDelegates.EdgePropertyFilter), method); } return null; } /// <summary> /// Creates a vertex cost delegate /// </summary> /// <param name="pathCostSpecification">Cost specificateion</param> /// <param name="pathDelegateType">The path delegate type </param> /// <returns>The delegate</returns> private static PathDelegates.VertexCost CreateVertexCostDelegate(PathCostSpecification pathCostSpecification, Type pathDelegateType) { if (pathCostSpecification != null && !String.IsNullOrEmpty(pathCostSpecification.Edge)) { var method = pathDelegateType.GetMethod(VertexCostMethodName); return (PathDelegates.VertexCost)Delegate.CreateDelegate(typeof(PathDelegates.VertexCost), method); } return null; } /// <summary> /// Creates an edge cost delegate /// </summary> /// <param name="pathCostSpecification">Cost specificateion</param> /// <param name="pathDelegateType">The path delegate type</param> /// <returns>The delegate</returns> private static PathDelegates.EdgeCost CreateEdgeCostDelegate(PathCostSpecification pathCostSpecification, Type pathDelegateType) { if (pathCostSpecification != null && !String.IsNullOrEmpty(pathCostSpecification.Edge)) { var method = pathDelegateType.GetMethod(EdgeCostMethodName); return (PathDelegates.EdgeCost)Delegate.CreateDelegate(typeof(PathDelegates.EdgeCost), method); } return null; } /// <summary> /// Creats the result /// </summary> /// <param name="graphElements"> The graph elements </param> /// <param name="resultTypeSpecification"> The result specification </param> /// <returns> </returns> private static IEnumerable<int> CreateResult(IEnumerable<AGraphElement> graphElements, ResultTypeSpecification resultTypeSpecification) { switch (resultTypeSpecification) { case ResultTypeSpecification.Vertices: return graphElements.OfType<VertexModel>().Select(_ => _.Id); case ResultTypeSpecification.Edges: return graphElements.OfType<EdgeModel>().Select(_ => _.Id); case ResultTypeSpecification.Both: return graphElements.Select(_ => _.Id); default: throw new ArgumentOutOfRangeException("resultTypeSpecification"); } } #endregion #region not implemented public void Save(SerializationWriter writer) { } public void Load(SerializationReader reader, Fallen8 fallen8) { } public void Shutdown() { } #endregion } }
// 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.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Extensions.ObjectExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Primitives; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Framework.Utils; using osu.Game.Graphics; using osu.Game.Input.Bindings; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Objects; using osu.Game.Screens.Edit.Components.Timelines.Summary.Parts; using osuTK; using osuTK.Graphics; namespace osu.Game.Screens.Edit.Compose.Components.Timeline { internal class TimelineBlueprintContainer : EditorBlueprintContainer { [Resolved(CanBeNull = true)] private Timeline timeline { get; set; } [Resolved] private OsuColour colours { get; set; } private DragEvent lastDragEvent; private Bindable<HitObject> placement; private SelectionBlueprint<HitObject> placementBlueprint; private SelectableAreaBackground backgroundBox; // we only care about checking vertical validity. // this allows selecting and dragging selections before time=0. public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) { float localY = ToLocalSpace(screenSpacePos).Y; return DrawRectangle.Top <= localY && DrawRectangle.Bottom >= localY; } public TimelineBlueprintContainer(HitObjectComposer composer) : base(composer) { RelativeSizeAxes = Axes.Both; Anchor = Anchor.Centre; Origin = Anchor.Centre; Height = 0.6f; } [BackgroundDependencyLoader] private void load() { AddInternal(backgroundBox = new SelectableAreaBackground { Colour = Color4.Black, Depth = float.MaxValue, Blending = BlendingParameters.Additive, }); } protected override void LoadComplete() { base.LoadComplete(); DragBox.Alpha = 0; placement = Beatmap.PlacementObject.GetBoundCopy(); placement.ValueChanged += placementChanged; } private void placementChanged(ValueChangedEvent<HitObject> obj) { if (obj.NewValue == null) { if (placementBlueprint != null) { SelectionBlueprints.Remove(placementBlueprint); placementBlueprint = null; } } else { placementBlueprint = CreateBlueprintFor(obj.NewValue).AsNonNull(); placementBlueprint.Colour = Color4.MediumPurple; SelectionBlueprints.Add(placementBlueprint); } } protected override Container<SelectionBlueprint<HitObject>> CreateSelectionBlueprintContainer() => new TimelineSelectionBlueprintContainer { RelativeSizeAxes = Axes.Both }; protected override bool OnHover(HoverEvent e) { backgroundBox.FadeColour(colours.BlueLighter, 120, Easing.OutQuint); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { backgroundBox.FadeColour(Color4.Black, 600, Easing.OutQuint); base.OnHoverLost(e); } protected override void OnDrag(DragEvent e) { handleScrollViaDrag(e); base.OnDrag(e); } protected override void OnDragEnd(DragEndEvent e) { base.OnDragEnd(e); lastDragEvent = null; } protected override void Update() { // trigger every frame so drags continue to update selection while playback is scrolling the timeline. if (lastDragEvent != null) OnDrag(lastDragEvent); if (Composer != null && timeline != null) { Composer.Playfield.PastLifetimeExtension = timeline.VisibleRange / 2; Composer.Playfield.FutureLifetimeExtension = timeline.VisibleRange / 2; } base.Update(); updateStacking(); } private void updateStacking() { // because only blueprints of objects which are alive (via pooling) are displayed in the timeline, it's feasible to do this every-update. const int stack_offset = 5; // after the stack gets this tall, we can presume there is space underneath to draw subsequent blueprints. const int stack_reset_count = 3; Stack<HitObject> currentConcurrentObjects = new Stack<HitObject>(); foreach (var b in SelectionBlueprints.Reverse()) { // remove objects from the stack as long as their end time is in the past. while (currentConcurrentObjects.TryPeek(out HitObject hitObject)) { if (Precision.AlmostBigger(hitObject.GetEndTime(), b.Item.StartTime, 1)) break; currentConcurrentObjects.Pop(); } // if the stack gets too high, we should have space below it to display the next batch of objects. // importantly, we only do this if time has incremented, else a stack of hitobjects all at the same time value would start to overlap themselves. if (currentConcurrentObjects.TryPeek(out HitObject h) && !Precision.AlmostEquals(h.StartTime, b.Item.StartTime, 1)) { if (currentConcurrentObjects.Count >= stack_reset_count) currentConcurrentObjects.Clear(); } b.Y = -(stack_offset * currentConcurrentObjects.Count); currentConcurrentObjects.Push(b.Item); } } protected override SelectionHandler<HitObject> CreateSelectionHandler() => new TimelineSelectionHandler(); protected override SelectionBlueprint<HitObject> CreateBlueprintFor(HitObject item) { return new TimelineHitObjectBlueprint(item) { OnDragHandled = handleScrollViaDrag }; } protected override DragBox CreateDragBox(Action<RectangleF> performSelect) => new TimelineDragBox(performSelect); private void handleScrollViaDrag(DragEvent e) { lastDragEvent = e; if (lastDragEvent == null) return; if (timeline != null) { var timelineQuad = timeline.ScreenSpaceDrawQuad; var mouseX = e.ScreenSpaceMousePosition.X; // scroll if in a drag and dragging outside visible extents if (mouseX > timelineQuad.TopRight.X) timeline.ScrollBy((float)((mouseX - timelineQuad.TopRight.X) / 10 * Clock.ElapsedFrameTime)); else if (mouseX < timelineQuad.TopLeft.X) timeline.ScrollBy((float)((mouseX - timelineQuad.TopLeft.X) / 10 * Clock.ElapsedFrameTime)); } } private class SelectableAreaBackground : CompositeDrawable { [BackgroundDependencyLoader] private void load() { RelativeSizeAxes = Axes.Both; Alpha = 0.1f; AddRangeInternal(new[] { // fade out over intro time, outside the valid time bounds. new Box { RelativeSizeAxes = Axes.Y, Width = 200, Origin = Anchor.TopRight, Colour = ColourInfo.GradientHorizontal(Color4.White.Opacity(0), Color4.White), }, new Box { Colour = Color4.White, RelativeSizeAxes = Axes.Both, } }); } } internal class TimelineSelectionHandler : EditorSelectionHandler, IKeyBindingHandler<GlobalAction> { // for now we always allow movement. snapping is provided by the Timeline's "distance" snap implementation public override bool HandleMovement(MoveSelectionEvent<HitObject> moveEvent) => true; public bool OnPressed(GlobalAction action) { switch (action) { case GlobalAction.EditorNudgeLeft: nudgeSelection(-1); return true; case GlobalAction.EditorNudgeRight: nudgeSelection(1); return true; } return false; } public void OnReleased(GlobalAction action) { } /// <summary> /// Nudge the current selection by the specified multiple of beat divisor lengths, /// based on the timing at the first object in the selection. /// </summary> /// <param name="amount">The direction and count of beat divisor lengths to adjust.</param> private void nudgeSelection(int amount) { var selected = EditorBeatmap.SelectedHitObjects; if (selected.Count == 0) return; var timingPoint = EditorBeatmap.ControlPointInfo.TimingPointAt(selected.First().StartTime); double adjustment = timingPoint.BeatLength / EditorBeatmap.BeatDivisor * amount; EditorBeatmap.PerformOnSelection(h => { h.StartTime += adjustment; EditorBeatmap.Update(h); }); } } private class TimelineDragBox : DragBox { // the following values hold the start and end X positions of the drag box in the timeline's local space, // but with zoom unapplied in order to be able to compensate for positional changes // while the timeline is being zoomed in/out. private float? selectionStart; private float selectionEnd; [Resolved] private Timeline timeline { get; set; } public TimelineDragBox(Action<RectangleF> performSelect) : base(performSelect) { } protected override Drawable CreateBox() => new Box { RelativeSizeAxes = Axes.Y, Alpha = 0.3f }; public override bool HandleDrag(MouseButtonEvent e) { selectionStart ??= e.MouseDownPosition.X / timeline.CurrentZoom; // only calculate end when a transition is not in progress to avoid bouncing. if (Precision.AlmostEquals(timeline.CurrentZoom, timeline.Zoom)) selectionEnd = e.MousePosition.X / timeline.CurrentZoom; updateDragBoxPosition(); return true; } private void updateDragBoxPosition() { if (selectionStart == null) return; float rescaledStart = selectionStart.Value * timeline.CurrentZoom; float rescaledEnd = selectionEnd * timeline.CurrentZoom; Box.X = Math.Min(rescaledStart, rescaledEnd); Box.Width = Math.Abs(rescaledStart - rescaledEnd); var boxScreenRect = Box.ScreenSpaceDrawQuad.AABBFloat; // we don't care about where the hitobjects are vertically. in cases like stacking display, they may be outside the box without this adjustment. boxScreenRect.Y -= boxScreenRect.Height; boxScreenRect.Height *= 2; PerformSelection?.Invoke(boxScreenRect); } public override void Hide() { base.Hide(); selectionStart = null; } } protected class TimelineSelectionBlueprintContainer : Container<SelectionBlueprint<HitObject>> { protected override Container<SelectionBlueprint<HitObject>> Content { get; } public TimelineSelectionBlueprintContainer() { AddInternal(new TimelinePart<SelectionBlueprint<HitObject>>(Content = new HitObjectOrderedSelectionContainer { RelativeSizeAxes = Axes.Both }) { RelativeSizeAxes = Axes.Both }); } } } }
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1) #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Text; using System.IO; #if !JSONNET_XMLDISABLE using System.Xml; #endif using System.Globalization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json { /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data. /// </summary> public class JsonTextReader : JsonReader, IJsonLineInfo { private enum ReadType { Read, ReadAsBytes, ReadAsDecimal, ReadAsDateTimeOffset } private readonly TextReader _reader; private readonly StringBuffer _buffer; private char? _lastChar; private int _currentLinePosition; private int _currentLineNumber; private bool _end; private ReadType _readType; private CultureInfo _culture; /// <summary> /// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.CurrentCulture"/>. /// </summary> public CultureInfo Culture { get { return _culture ?? CultureInfo.CurrentCulture; } set { _culture = value; } } /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> /// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param> public JsonTextReader(TextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); _reader = reader; _buffer = new StringBuffer(4096); _currentLineNumber = 1; } private void ParseString(char quote) { ReadStringIntoBuffer(quote); if (_readType == ReadType.ReadAsBytes) { byte[] data; if (_buffer.Position == 0) { data = new byte[0]; } else { data = Convert.FromBase64CharArray(_buffer.GetInternalBuffer(), 0, _buffer.Position); _buffer.Position = 0; } SetToken(JsonToken.Bytes, data); } else { string text = _buffer.ToString(); _buffer.Position = 0; if (text.StartsWith("/Date(", StringComparison.Ordinal) && text.EndsWith(")/", StringComparison.Ordinal)) { ParseDate(text); } else { SetToken(JsonToken.String, text); QuoteChar = quote; } } } private void ReadStringIntoBuffer(char quote) { while (true) { char currentChar = MoveNext(); switch (currentChar) { case '\0': if (_end) throw CreateJsonReaderException("Unterminated string. Expected delimiter: {0}. Line {1}, position {2}.", quote, _currentLineNumber, _currentLinePosition); _buffer.Append('\0'); break; case '\\': if ((currentChar = MoveNext()) != '\0' || !_end) { switch (currentChar) { case 'b': _buffer.Append('\b'); break; case 't': _buffer.Append('\t'); break; case 'n': _buffer.Append('\n'); break; case 'f': _buffer.Append('\f'); break; case 'r': _buffer.Append('\r'); break; case '\\': _buffer.Append('\\'); break; case '"': case '\'': case '/': _buffer.Append(currentChar); break; case 'u': char[] hexValues = new char[4]; for (int i = 0; i < hexValues.Length; i++) { if ((currentChar = MoveNext()) != '\0' || !_end) hexValues[i] = currentChar; else throw CreateJsonReaderException("Unexpected end while parsing unicode character. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } char hexChar = Convert.ToChar(int.Parse(new string(hexValues), NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo)); _buffer.Append(hexChar); break; default: throw CreateJsonReaderException("Bad JSON escape sequence: {0}. Line {1}, position {2}.", @"\" + currentChar, _currentLineNumber, _currentLinePosition); } } else { throw CreateJsonReaderException("Unterminated string. Expected delimiter: {0}. Line {1}, position {2}.", quote, _currentLineNumber, _currentLinePosition); } break; case '"': case '\'': if (currentChar == quote) { return; } else { _buffer.Append(currentChar); } break; default: _buffer.Append(currentChar); break; } } } private JsonReaderException CreateJsonReaderException(string format, params object[] args) { string message = format.FormatWith(CultureInfo.InvariantCulture, args); return new JsonReaderException(message, null, _currentLineNumber, _currentLinePosition); } private TimeSpan ReadOffset(string offsetText) { bool negative = (offsetText[0] == '-'); int hours = int.Parse(offsetText.Substring(1, 2), NumberStyles.Integer, CultureInfo.InvariantCulture); int minutes = 0; if (offsetText.Length >= 5) minutes = int.Parse(offsetText.Substring(3, 2), NumberStyles.Integer, CultureInfo.InvariantCulture); TimeSpan offset = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes); if (negative) offset = offset.Negate(); return offset; } private void ParseDate(string text) { string value = text.Substring(6, text.Length - 8); DateTimeKind kind = DateTimeKind.Utc; int index = value.IndexOf('+', 1); if (index == -1) index = value.IndexOf('-', 1); TimeSpan offset = TimeSpan.Zero; if (index != -1) { kind = DateTimeKind.Local; offset = ReadOffset(value.Substring(index)); value = value.Substring(0, index); } long javaScriptTicks = long.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture); DateTime utcDateTime = JsonConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks); if (_readType == ReadType.ReadAsDateTimeOffset) { SetToken(JsonToken.Date, new DateTimeOffset(utcDateTime.Add(offset).Ticks, offset)); } else { DateTime dateTime; switch (kind) { case DateTimeKind.Unspecified: dateTime = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified); break; case DateTimeKind.Local: dateTime = utcDateTime.ToLocalTime(); break; default: dateTime = utcDateTime; break; } SetToken(JsonToken.Date, dateTime); } } private const int LineFeedValue = StringUtils.LineFeed; private const int CarriageReturnValue = StringUtils.CarriageReturn; private char MoveNext() { int value = _reader.Read(); switch (value) { case -1: _end = true; return '\0'; case CarriageReturnValue: if (_reader.Peek() == LineFeedValue) _reader.Read(); _currentLineNumber++; _currentLinePosition = 0; break; case LineFeedValue: _currentLineNumber++; _currentLinePosition = 0; break; default: _currentLinePosition++; break; } return (char)value; } private bool HasNext() { return (_reader.Peek() != -1); } private int PeekNext() { return _reader.Peek(); } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns> /// true if the next token was read successfully; false if there are no more tokens to read. /// </returns> public override bool Read() { _readType = ReadType.Read; return ReadInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>. /// </summary> /// <returns> /// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. /// </returns> public override byte[] ReadAsBytes() { _readType = ReadType.ReadAsBytes; do { if (!ReadInternal()) throw CreateJsonReaderException("Unexpected end when reading bytes: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } while (TokenType == JsonToken.Comment); if (TokenType == JsonToken.Null) return null; if (TokenType == JsonToken.Bytes) return (byte[]) Value; if (TokenType == JsonToken.StartArray) { List<byte> data = new List<byte>(); while (ReadInternal()) { switch (TokenType) { case JsonToken.Integer: data.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); break; case JsonToken.EndArray: byte[] d = data.ToArray(); SetToken(JsonToken.Bytes, d); return d; case JsonToken.Comment: // skip break; default: throw CreateJsonReaderException("Unexpected token when reading bytes: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition); } } throw CreateJsonReaderException("Unexpected end when reading bytes: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } throw CreateJsonReaderException("Unexpected token when reading bytes: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>.</returns> public override decimal? ReadAsDecimal() { _readType = ReadType.ReadAsDecimal; do { if (!ReadInternal()) throw CreateJsonReaderException("Unexpected end when reading decimal: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } while (TokenType == JsonToken.Comment); if (TokenType == JsonToken.Null) return null; if (TokenType == JsonToken.Float) return (decimal?)Value; decimal d; if (TokenType == JsonToken.String && decimal.TryParse((string)Value, NumberStyles.Number, Culture, out d)) { SetToken(JsonToken.Float, d); return d; } throw CreateJsonReaderException("Unexpected token when reading decimal: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="DateTimeOffset"/>.</returns> public override DateTimeOffset? ReadAsDateTimeOffset() { _readType = ReadType.ReadAsDateTimeOffset; do { if (!ReadInternal()) throw CreateJsonReaderException("Unexpected end when reading date: Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } while (TokenType == JsonToken.Comment); if (TokenType == JsonToken.Null) return null; if (TokenType == JsonToken.Date) return (DateTimeOffset)Value; DateTimeOffset dt; if (TokenType == JsonToken.String && DateTimeOffset.TryParse((string)Value, Culture, DateTimeStyles.None, out dt)) { SetToken(JsonToken.Date, dt); return dt; } throw CreateJsonReaderException("Unexpected token when reading date: {0}. Line {1}, position {2}.", TokenType, _currentLineNumber, _currentLinePosition); } private bool ReadInternal() { while (true) { char currentChar; if (_lastChar != null) { currentChar = _lastChar.Value; _lastChar = null; } else { currentChar = MoveNext(); } if (currentChar == '\0' && _end) return false; switch (CurrentState) { case State.Start: case State.Property: case State.Array: case State.ArrayStart: case State.Constructor: case State.ConstructorStart: return ParseValue(currentChar); case State.Complete: break; case State.Object: case State.ObjectStart: return ParseObject(currentChar); case State.PostValue: // returns true if it hits // end of object or array if (ParsePostValue(currentChar)) return true; break; case State.Closed: break; case State.Error: break; default: throw CreateJsonReaderException("Unexpected state: {0}. Line {1}, position {2}.", CurrentState, _currentLineNumber, _currentLinePosition); } } } private bool ParsePostValue(char currentChar) { do { switch (currentChar) { case '}': SetToken(JsonToken.EndObject); return true; case ']': SetToken(JsonToken.EndArray); return true; case ')': SetToken(JsonToken.EndConstructor); return true; case '/': ParseComment(); return true; case ',': // finished parsing SetStateBasedOnCurrent(); return false; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: // eat break; default: if (char.IsWhiteSpace(currentChar)) { // eat } else { throw CreateJsonReaderException("After parsing a value an unexpected character was encountered: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } break; } } while ((currentChar = MoveNext()) != '\0' || !_end); return false; } private bool ParseObject(char currentChar) { do { switch (currentChar) { case '}': SetToken(JsonToken.EndObject); return true; case '/': ParseComment(); return true; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: // eat break; default: if (char.IsWhiteSpace(currentChar)) { // eat } else { return ParseProperty(currentChar); } break; } } while ((currentChar = MoveNext()) != '\0' || !_end); return false; } private bool ParseProperty(char firstChar) { char currentChar = firstChar; char quoteChar; if (ValidIdentifierChar(currentChar)) { quoteChar = '\0'; currentChar = ParseUnquotedProperty(currentChar); } else if (currentChar == '"' || currentChar == '\'') { quoteChar = currentChar; ReadStringIntoBuffer(quoteChar); currentChar = MoveNext(); } else { throw CreateJsonReaderException("Invalid property identifier character: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } if (currentChar != ':') { currentChar = MoveNext(); // finished property. skip any whitespace and move to colon EatWhitespace(currentChar, false, out currentChar); if (currentChar != ':') throw CreateJsonReaderException("Invalid character after parsing property name. Expected ':' but got: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } SetToken(JsonToken.PropertyName, _buffer.ToString()); QuoteChar = quoteChar; _buffer.Position = 0; return true; } private bool ValidIdentifierChar(char value) { return (char.IsLetterOrDigit(value) || value == '_' || value == '$'); } private char ParseUnquotedProperty(char firstChar) { // parse unquoted property name until whitespace or colon _buffer.Append(firstChar); char currentChar; while ((currentChar = MoveNext()) != '\0' || !_end) { if (char.IsWhiteSpace(currentChar) || currentChar == ':') { return currentChar; } else if (ValidIdentifierChar(currentChar)) { _buffer.Append(currentChar); } else { throw CreateJsonReaderException("Invalid JavaScript property identifier character: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } } throw CreateJsonReaderException("Unexpected end when parsing unquoted property name. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } private bool ParseValue(char currentChar) { do { switch (currentChar) { case '"': case '\'': ParseString(currentChar); return true; case 't': ParseTrue(); return true; case 'f': ParseFalse(); return true; case 'n': if (HasNext()) { char next = (char)PeekNext(); if (next == 'u') ParseNull(); else if (next == 'e') ParseConstructor(); else throw CreateJsonReaderException("Unexpected character encountered while parsing value: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } else { throw CreateJsonReaderException("Unexpected end. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } return true; case 'N': ParseNumberNaN(); return true; case 'I': ParseNumberPositiveInfinity(); return true; case '-': if (PeekNext() == 'I') ParseNumberNegativeInfinity(); else ParseNumber(currentChar); return true; case '/': ParseComment(); return true; case 'u': ParseUndefined(); return true; case '{': SetToken(JsonToken.StartObject); return true; case '[': SetToken(JsonToken.StartArray); return true; case '}': SetToken(JsonToken.EndObject); return true; case ']': SetToken(JsonToken.EndArray); return true; case ',': SetToken(JsonToken.Undefined); return true; case ')': SetToken(JsonToken.EndConstructor); return true; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: // eat break; default: if (char.IsWhiteSpace(currentChar)) { // eat } else if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.') { ParseNumber(currentChar); return true; } else { throw CreateJsonReaderException("Unexpected character encountered while parsing value: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); } break; } } while ((currentChar = MoveNext()) != '\0' || !_end); return false; } private bool EatWhitespace(char initialChar, bool oneOrMore, out char finalChar) { bool whitespace = false; char currentChar = initialChar; while (currentChar == ' ' || char.IsWhiteSpace(currentChar)) { whitespace = true; currentChar = MoveNext(); } finalChar = currentChar; return (!oneOrMore || whitespace); } private void ParseConstructor() { if (MatchValue('n', "new", true)) { char currentChar = MoveNext(); if (EatWhitespace(currentChar, true, out currentChar)) { while (char.IsLetter(currentChar)) { _buffer.Append(currentChar); currentChar = MoveNext(); } EatWhitespace(currentChar, false, out currentChar); if (currentChar != '(') throw CreateJsonReaderException("Unexpected character while parsing constructor: {0}. Line {1}, position {2}.", currentChar, _currentLineNumber, _currentLinePosition); string constructorName = _buffer.ToString(); _buffer.Position = 0; SetToken(JsonToken.StartConstructor, constructorName); } } } private void ParseNumber(char firstChar) { char currentChar = firstChar; // parse until seperator character or end bool end = false; do { if (IsSeperator(currentChar)) { end = true; _lastChar = currentChar; } else { _buffer.Append(currentChar); } } while (!end && ((currentChar = MoveNext()) != '\0' || !_end)); string number = _buffer.ToString(); object numberValue; JsonToken numberType; bool nonBase10 = (firstChar == '0' && !number.StartsWith("0.", StringComparison.OrdinalIgnoreCase)); if (_readType == ReadType.ReadAsDecimal) { if (nonBase10) { // decimal.Parse doesn't support parsing hexadecimal values long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); numberValue = Convert.ToDecimal(integer); } else { numberValue = decimal.Parse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture); } numberType = JsonToken.Float; } else { if (nonBase10) { numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); numberType = JsonToken.Integer; } else if (number.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || number.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1) { numberValue = Convert.ToDouble(number, CultureInfo.InvariantCulture); numberType = JsonToken.Float; } else { try { numberValue = Convert.ToInt64(number, CultureInfo.InvariantCulture); } catch (OverflowException ex) { throw new JsonReaderException("JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, number), ex); } numberType = JsonToken.Integer; } } _buffer.Position = 0; SetToken(numberType, numberValue); } private void ParseComment() { // should have already parsed / character before reaching this method char currentChar = MoveNext(); if (currentChar == '*') { while ((currentChar = MoveNext()) != '\0' || !_end) { if (currentChar == '*') { if ((currentChar = MoveNext()) != '\0' || !_end) { if (currentChar == '/') { break; } else { _buffer.Append('*'); _buffer.Append(currentChar); } } } else { _buffer.Append(currentChar); } } } else { throw CreateJsonReaderException("Error parsing comment. Expected: *. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } SetToken(JsonToken.Comment, _buffer.ToString()); _buffer.Position = 0; } private bool MatchValue(char firstChar, string value) { char currentChar = firstChar; int i = 0; do { if (currentChar != value[i]) { break; } i++; } while (i < value.Length && ((currentChar = MoveNext()) != '\0' || !_end)); return (i == value.Length); } private bool MatchValue(char firstChar, string value, bool noTrailingNonSeperatorCharacters) { // will match value and then move to the next character, checking that it is a seperator character bool match = MatchValue(firstChar, value); if (!noTrailingNonSeperatorCharacters) { return match; } else { int c = PeekNext(); char next = (c != -1) ? (char) c : '\0'; bool matchAndNoTrainingNonSeperatorCharacters = (match && (next == '\0' || IsSeperator(next))); return matchAndNoTrainingNonSeperatorCharacters; } } private bool IsSeperator(char c) { switch (c) { case '}': case ']': case ',': return true; case '/': // check next character to see if start of a comment return (HasNext() && PeekNext() == '*'); case ')': if (CurrentState == State.Constructor || CurrentState == State.ConstructorStart) return true; break; case ' ': case StringUtils.Tab: case StringUtils.LineFeed: case StringUtils.CarriageReturn: return true; default: if (char.IsWhiteSpace(c)) return true; break; } return false; } private void ParseTrue() { // check characters equal 'true' // and that it is followed by either a seperator character // or the text ends if (MatchValue('t', JsonConvert.True, true)) { SetToken(JsonToken.Boolean, true); } else { throw CreateJsonReaderException("Error parsing boolean value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseNull() { if (MatchValue('n', "null"/*JsonConvert.Null*/, true)) { SetToken(JsonToken.Null); } else { throw CreateJsonReaderException("Error parsing null value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseUndefined() { if (MatchValue('u', JsonConvert.Undefined, true)) { SetToken(JsonToken.Undefined); } else { throw CreateJsonReaderException("Error parsing undefined value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseFalse() { if (MatchValue('f', JsonConvert.False, true)) { SetToken(JsonToken.Boolean, false); } else { throw CreateJsonReaderException("Error parsing boolean value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseNumberNegativeInfinity() { if (MatchValue('-', JsonConvert.NegativeInfinity, true)) { SetToken(JsonToken.Float, double.NegativeInfinity); } else { throw CreateJsonReaderException("Error parsing negative infinity value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseNumberPositiveInfinity() { if (MatchValue('I', JsonConvert.PositiveInfinity, true)) { SetToken(JsonToken.Float, double.PositiveInfinity); } else { throw CreateJsonReaderException("Error parsing positive infinity value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } private void ParseNumberNaN() { if (MatchValue('N', JsonConvert.NaN, true)) { SetToken(JsonToken.Float, double.NaN); } else { throw CreateJsonReaderException("Error parsing NaN value. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition); } } /// <summary> /// Changes the state to closed. /// </summary> public override void Close() { base.Close(); if (CloseInput && _reader != null) _reader.Close(); if (_buffer != null) _buffer.Clear(); } /// <summary> /// Gets a value indicating whether the class can return line information. /// </summary> /// <returns> /// <c>true</c> if LineNumber and LinePosition can be provided; otherwise, <c>false</c>. /// </returns> public bool HasLineInfo() { return true; } /// <summary> /// Gets the current line number. /// </summary> /// <value> /// The current line number or 0 if no line information is available (for example, HasLineInfo returns false). /// </value> public int LineNumber { get { if (CurrentState == State.Start) return 0; return _currentLineNumber; } } /// <summary> /// Gets the current line position. /// </summary> /// <value> /// The current line position or 0 if no line information is available (for example, HasLineInfo returns false). /// </value> public int LinePosition { get { return _currentLinePosition; } } } } #endif
//--------------------------------------------------------------------------- // // File: TreeChangeInfo.cs // // Description: // This data-structure is used // 1. As the data that is passed around by the DescendentsWalker // during an AncestorChanged tree-walk. // // Copyright (C) by Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Media; using System.Windows.Controls; using System.Windows.Documents; using MS.Internal; using MS.Utility; namespace System.Windows { /// <summary> /// This is the data that is passed through the DescendentsWalker /// during an AncestorChange tree-walk. /// </summary> internal struct TreeChangeInfo { #region Properties public TreeChangeInfo(DependencyObject root, DependencyObject parent, bool isAddOperation) { _rootOfChange = root; _isAddOperation = isAddOperation; _topmostCollapsedParentNode = null; _rootInheritableValues = null; _inheritablePropertiesStack = null; _valueIndexer = 0; // Create the InheritableProperties cache for the parent // and push it to start the stack ... we don't need to // pop this when we're done because we'll be throing the // stack away at that point. InheritablePropertiesStack.Push(CreateParentInheritableProperties(root, parent, isAddOperation)); } // // This method // 1. Is called from AncestorChange InvalidateTree. // 2. It is used to create the InheritableProperties on the given node. // 3. It also accumulates oldValues for the inheritable properties that are about to be invalidated // internal FrugalObjectList<DependencyProperty> CreateParentInheritableProperties( DependencyObject d, DependencyObject parent, bool isAddOperation) { Debug.Assert(d != null, "Must have non-null current node"); if (parent == null) { return new FrugalObjectList<DependencyProperty>(0); } DependencyObjectType treeObjDOT = d.DependencyObjectType; // See if we have a cached value. EffectiveValueEntry[] parentEffectiveValues = null; uint parentEffectiveValuesCount = 0; uint inheritablePropertiesCount = 0; // If inheritable properties aren't cached on you then use the effective // values cache on the parent to discover those inherited properties that // may need to be invalidated on the children nodes. if (!parent.IsSelfInheritanceParent) { DependencyObject inheritanceParent = parent.InheritanceParent; if (inheritanceParent != null) { parentEffectiveValues = inheritanceParent.EffectiveValues; parentEffectiveValuesCount = inheritanceParent.EffectiveValuesCount; inheritablePropertiesCount = inheritanceParent.InheritableEffectiveValuesCount; } } else { parentEffectiveValues = parent.EffectiveValues; parentEffectiveValuesCount = parent.EffectiveValuesCount; inheritablePropertiesCount = parent.InheritableEffectiveValuesCount; } FrugalObjectList<DependencyProperty> inheritableProperties = new FrugalObjectList<DependencyProperty>((int) inheritablePropertiesCount); if (inheritablePropertiesCount == 0) { return inheritableProperties; } _rootInheritableValues = new InheritablePropertyChangeInfo[(int) inheritablePropertiesCount]; int inheritableIndex = 0; FrameworkObject foParent = new FrameworkObject(parent); for (uint i=0; i<parentEffectiveValuesCount; i++) { // Add all the inheritable properties from the effectiveValues // cache to the TreeStateCache on the parent EffectiveValueEntry entry = parentEffectiveValues[i]; DependencyProperty dp = DependencyProperty.RegisteredPropertyList.List[entry.PropertyIndex]; // There are UncommonFields also stored in the EffectiveValues cache. We need to exclude those. if ((dp != null) && dp.IsPotentiallyInherited) { PropertyMetadata metadata = dp.GetMetadata(parent.DependencyObjectType); if (metadata != null && metadata.IsInherited) { Debug.Assert(!inheritableProperties.Contains(dp), "EffectiveValues cache must not contains duplicate entries for the same DP"); FrameworkPropertyMetadata fMetadata = (FrameworkPropertyMetadata)metadata; // Children do not need to inherit properties across a tree boundary // unless the property is set to override this behavior. if (!TreeWalkHelper.SkipNow(foParent.InheritanceBehavior) || fMetadata.OverridesInheritanceBehavior) { inheritableProperties.Add(dp); EffectiveValueEntry oldEntry; EffectiveValueEntry newEntry; oldEntry = d.GetValueEntry( d.LookupEntry(dp.GlobalIndex), dp, dp.GetMetadata(treeObjDOT), RequestFlags.DeferredReferences); if (isAddOperation) { // set up the new value newEntry = entry; if ((newEntry.BaseValueSourceInternal != BaseValueSourceInternal.Default) || newEntry.HasModifiers) { newEntry = newEntry.GetFlattenedEntry(RequestFlags.FullyResolved); newEntry.BaseValueSourceInternal = BaseValueSourceInternal.Inherited; } } else { newEntry = new EffectiveValueEntry(); } _rootInheritableValues[inheritableIndex++] = new InheritablePropertyChangeInfo(d, dp, oldEntry, newEntry); if (inheritablePropertiesCount == inheritableIndex) { // no more inheritable properties, bail early break; } } } } } return inheritableProperties; } // This is called by TreeWalker.InvalidateTreeDependentProperties before looping through // all of the items in the InheritablesPropertiesStack internal void ResetInheritableValueIndexer() { _valueIndexer = 0; } // This is called by TreeWalker.InvalidateTreeDependentProperty. // _valueIndexer is an optimization because we know (a) that the last DP list pushed on the // InheritablePropertiesStack is a subset of the first DP list pushed on this stack; // (b) the first DP list pushed on the stack has the same # (and order) of entries as the // RootInheritableValues list; and (c) the last DP list pushed on the stack will have its // DPs in the same order as those DPs appear in the first DP list pushed on the stack. This // allows us to simply increment _valueIndexer until we find a match; and on subsequent // calls to GetRootInheritableValue just continue our incrementing from where we left off // the last time. internal InheritablePropertyChangeInfo GetRootInheritableValue(DependencyProperty dp) { InheritablePropertyChangeInfo info; do { info = _rootInheritableValues[_valueIndexer++]; } while (info.Property != dp); return info; } /// <summary> /// This is a stack that is used during an AncestorChange operation. /// I holds the InheritableProperties cache on the parent nodes in /// the tree in the order of traversal. The top of the stack holds /// the cache for the immediate parent node. /// </summary> internal Stack<FrugalObjectList<DependencyProperty>> InheritablePropertiesStack { get { if (_inheritablePropertiesStack == null) { _inheritablePropertiesStack = new Stack<FrugalObjectList<DependencyProperty>>(1); } return _inheritablePropertiesStack; } } /// <summary> /// When we enter a Visibility=Collapsed subtree, we remember that node /// using this property. As we process the children of this collapsed /// node, we see this property as non-null and know we're collapsed. /// As we exit the subtree, this reference is nulled out which means /// we don't know whether we're in a collapsed tree and the optimizations /// based on Visibility=Collapsed are not valid and should not be used. /// </summary> internal object TopmostCollapsedParentNode { get { return _topmostCollapsedParentNode; } set { _topmostCollapsedParentNode = value; } } // Indicates if this is a add child tree operation internal bool IsAddOperation { get { return _isAddOperation; } } // This is the element at the root of the sub-tree that had a parent change. internal DependencyObject Root { get { return _rootOfChange; } } #endregion Properties #region Data private Stack<FrugalObjectList<DependencyProperty>> _inheritablePropertiesStack; private object _topmostCollapsedParentNode; private bool _isAddOperation; private DependencyObject _rootOfChange; private InheritablePropertyChangeInfo[] _rootInheritableValues; private int _valueIndexer; #endregion Data } }
using System; using System.Globalization; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using EnvDTE; using Microsoft.VisualStudio.ExtensionsExplorer.UI; using Microsoft.VisualStudio.PlatformUI; using NuGet.Dialog.PackageManagerUI; using NuGet.Dialog.Providers; using NuGet.VisualStudio; namespace NuGet.Dialog { public partial class PackageManagerWindow : DialogWindow { internal static PackageManagerWindow CurrentInstance; private const string DialogUserAgentClient = "NuGet Add Package Dialog"; private readonly Lazy<string> _dialogUserAgent = new Lazy<string>(() => HttpUtility.CreateUserAgentString(DialogUserAgentClient)); private const string F1Keyword = "vs.ExtensionManager"; private readonly IHttpClientEvents _httpClientEvents; private bool _hasOpenedOnlineProvider; private ComboBox _prereleaseComboBox; private readonly SmartOutputConsoleProvider _smartOutputConsoleProvider; private readonly IProviderSettings _providerSettings; private readonly IProductUpdateService _productUpdateService; private readonly IOptionsPageActivator _optionsPageActivator; private readonly Project _activeProject; public PackageManagerWindow(Project project) : this(project, ServiceLocator.GetInstance<DTE>(), ServiceLocator.GetInstance<IVsPackageManagerFactory>(), ServiceLocator.GetInstance<IPackageRepositoryFactory>(), ServiceLocator.GetInstance<IPackageSourceProvider>(), ServiceLocator.GetInstance<IRecentPackageRepository>(), ServiceLocator.GetInstance<IHttpClientEvents>(), ServiceLocator.GetInstance<IProductUpdateService>(), ServiceLocator.GetInstance<IPackageRestoreManager>(), ServiceLocator.GetInstance<ISolutionManager>(), ServiceLocator.GetInstance<IOptionsPageActivator>()) { } private PackageManagerWindow(Project project, DTE dte, IVsPackageManagerFactory packageManagerFactory, IPackageRepositoryFactory repositoryFactory, IPackageSourceProvider packageSourceProvider, IRecentPackageRepository recentPackagesRepository, IHttpClientEvents httpClientEvents, IProductUpdateService productUpdateService, IPackageRestoreManager packageRestoreManager, ISolutionManager solutionManager, IOptionsPageActivator optionPageActivator) : base(F1Keyword) { InitializeComponent(); _httpClientEvents = httpClientEvents; if (_httpClientEvents != null) { _httpClientEvents.SendingRequest += OnSendingRequest; } _productUpdateService = productUpdateService; _optionsPageActivator = optionPageActivator; _activeProject = project; // replace the ConsoleOutputProvider with SmartOutputConsoleProvider so that we can clear // the console the first time an entry is written to it var providerServices = new ProviderServices(); _smartOutputConsoleProvider = new SmartOutputConsoleProvider(providerServices.OutputConsoleProvider); providerServices.OutputConsoleProvider = _smartOutputConsoleProvider; _providerSettings = providerServices.ProviderSettings; AddUpdateBar(productUpdateService); AddRestoreBar(packageRestoreManager); InsertDisclaimerElement(); AdjustSortComboBoxWidth(); PreparePrereleaseComboBox(); SetupProviders( project, dte, packageManagerFactory, repositoryFactory, packageSourceProvider, providerServices, recentPackagesRepository, httpClientEvents, solutionManager); } private void AddUpdateBar(IProductUpdateService productUpdateService) { var updateBar = new ProductUpdateBar(productUpdateService); updateBar.UpdateStarting += ExecutedClose; LayoutRoot.Children.Add(updateBar); updateBar.SizeChanged += OnHeaderBarSizeChanged; } private void AddRestoreBar(IPackageRestoreManager packageRestoreManager) { var restoreBar = new PackageRestoreBar(packageRestoreManager); LayoutRoot.Children.Add(restoreBar); restoreBar.SizeChanged += OnHeaderBarSizeChanged; } private void OnHeaderBarSizeChanged(object sender, SizeChangedEventArgs e) { // when the update bar appears, we adjust the window position // so that it doesn't push the main content area down if (e.HeightChanged) { double heightDifference = e.NewSize.Height - e.PreviousSize.Height; if (heightDifference > 0) { Top = Math.Max(0, Top - heightDifference); } } } private void SetupProviders(Project activeProject, DTE dte, IVsPackageManagerFactory packageManagerFactory, IPackageRepositoryFactory packageRepositoryFactory, IPackageSourceProvider packageSourceProvider, ProviderServices providerServices, IPackageRepository recentPackagesRepository, IHttpClientEvents httpClientEvents, ISolutionManager solutionManager) { // This package manager is not used for installing from a remote source, and therefore does not need a fallback repository for resolving dependencies IVsPackageManager packageManager = packageManagerFactory.CreatePackageManager(ServiceLocator.GetInstance<IPackageRepository>(), useFallbackForDependencies: false); IPackageRepository localRepository; // we need different sets of providers depending on whether the dialog is open for solution or a project OnlineProvider onlineProvider; InstalledProvider installedProvider; UpdatesProvider updatesProvider; OnlineProvider recentProvider; if (activeProject == null) { Title = String.Format( CultureInfo.CurrentUICulture, NuGet.Dialog.Resources.Dialog_Title, dte.Solution.GetName() + ".sln"); localRepository = packageManager.LocalRepository; onlineProvider = new SolutionOnlineProvider( localRepository, Resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, httpClientEvents, solutionManager); installedProvider = new SolutionInstalledProvider( packageManager, localRepository, Resources, providerServices, httpClientEvents, solutionManager); updatesProvider = new SolutionUpdatesProvider( localRepository, Resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, httpClientEvents, solutionManager); recentProvider = new SolutionRecentProvider( localRepository, Resources, packageRepositoryFactory, packageManagerFactory, recentPackagesRepository, packageSourceProvider, providerServices, httpClientEvents, solutionManager); } else { IProjectManager projectManager = packageManager.GetProjectManager(activeProject); localRepository = projectManager.LocalRepository; Title = String.Format( CultureInfo.CurrentUICulture, NuGet.Dialog.Resources.Dialog_Title, activeProject.GetDisplayName()); onlineProvider = new OnlineProvider( activeProject, localRepository, Resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, httpClientEvents, solutionManager); installedProvider = new InstalledProvider( packageManager, activeProject, localRepository, Resources, providerServices, httpClientEvents, solutionManager); updatesProvider = new UpdatesProvider( activeProject, localRepository, Resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, httpClientEvents, solutionManager); recentProvider = new RecentProvider( activeProject, localRepository, Resources, packageRepositoryFactory, packageManagerFactory, recentPackagesRepository, packageSourceProvider, providerServices, httpClientEvents, solutionManager); } explorer.Providers.Add(installedProvider); explorer.Providers.Add(onlineProvider); explorer.Providers.Add(updatesProvider); explorer.Providers.Add(recentProvider); installedProvider.IncludePrerelease = onlineProvider.IncludePrerelease = updatesProvider.IncludePrerelease = recentProvider.IncludePrerelease = _providerSettings.IncludePrereleasePackages; // retrieve the selected provider from the settings int selectedProvider = Math.Min(3, _providerSettings.SelectedProvider); explorer.SelectedProvider = explorer.Providers[selectedProvider]; } private void CanExecuteCommandOnPackage(object sender, CanExecuteRoutedEventArgs e) { if (OperationCoordinator.IsBusy) { e.CanExecute = false; return; } VSExtensionsExplorerCtl control = e.Source as VSExtensionsExplorerCtl; if (control == null) { e.CanExecute = false; return; } PackageItem selectedItem = control.SelectedExtension as PackageItem; if (selectedItem == null) { e.CanExecute = false; return; } try { e.CanExecute = selectedItem.IsEnabled; } catch (Exception) { e.CanExecute = false; } } private void ExecutedPackageCommand(object sender, ExecutedRoutedEventArgs e) { if (OperationCoordinator.IsBusy) { return; } VSExtensionsExplorerCtl control = e.Source as VSExtensionsExplorerCtl; if (control == null) { return; } PackageItem selectedItem = control.SelectedExtension as PackageItem; if (selectedItem == null) { return; } PackagesProviderBase provider = control.SelectedProvider as PackagesProviderBase; if (provider != null) { try { provider.Execute(selectedItem); } catch (Exception exception) { MessageHelper.ShowErrorMessage(exception, NuGet.Dialog.Resources.Dialog_MessageBoxTitle); ExceptionHelper.WriteToActivityLog(exception); } } } private void ExecutedClose(object sender, EventArgs e) { Close(); } private void ExecutedShowOptionsPage(object sender, ExecutedRoutedEventArgs e) { Close(); _optionsPageActivator.ActivatePage( OptionsPage.PackageSources, () => OnActivated(_activeProject)); } /// <summary> /// Called when coming back from the Options dialog /// </summary> private static void OnActivated(Project project) { var window = new PackageManagerWindow(project); try { window.ShowModal(); } catch (TargetInvocationException exception) { MessageHelper.ShowErrorMessage(exception, NuGet.Dialog.Resources.Dialog_MessageBoxTitle); ExceptionHelper.WriteToActivityLog(exception); } } private void ExecuteOpenLicenseLink(object sender, ExecutedRoutedEventArgs e) { Hyperlink hyperlink = e.OriginalSource as Hyperlink; if (hyperlink != null && hyperlink.NavigateUri != null) { UriHelper.OpenExternalLink(hyperlink.NavigateUri); e.Handled = true; } } private void ExecuteSetFocusOnSearchBox(object sender, ExecutedRoutedEventArgs e) { explorer.SetFocusOnSearchBox(); } private void OnCategorySelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { PackagesTreeNodeBase selectedNode = explorer.SelectedExtensionTreeNode as PackagesTreeNodeBase; if (selectedNode != null) { // notify the selected node that it is opened. selectedNode.OnOpened(); } } private void OnDialogWindowClosing(object sender, System.ComponentModel.CancelEventArgs e) { // don't allow the dialog to be closed if an operation is pending if (OperationCoordinator.IsBusy) { e.Cancel = true; } } private void OnDialogWindowClosed(object sender, EventArgs e) { explorer.Providers.Clear(); // flush output messages to the Output console at once when the dialog is closed. _smartOutputConsoleProvider.Flush(); CurrentInstance = null; } /// <summary> /// HACK HACK: Insert the disclaimer element into the correct place inside the Explorer control. /// We don't want to bring in the whole control template of the extension explorer control. /// </summary> private void InsertDisclaimerElement() { Grid grid = LogicalTreeHelper.FindLogicalNode(explorer, "resGrid") as Grid; if (grid != null) { // m_Providers is the name of the expander provider control (the one on the leftmost column) UIElement providerExpander = FindChildElementByNameOrType(grid, "m_Providers", typeof(ProviderExpander)); if (providerExpander != null) { // remove disclaimer text and provider expander from their current parents grid.Children.Remove(providerExpander); LayoutRoot.Children.Remove(DisclaimerText); // create the inner grid which will host disclaimer text and the provider extender Grid innerGrid = new Grid(); innerGrid.RowDefinitions.Add(new RowDefinition()); innerGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0, GridUnitType.Auto) }); innerGrid.Children.Add(providerExpander); Grid.SetRow(DisclaimerText, 1); innerGrid.Children.Add(DisclaimerText); // add the inner grid to the first column of the original grid grid.Children.Add(innerGrid); } } } private void AdjustSortComboBoxWidth() { ComboBox sortCombo = FindComboBox("cmd_SortOrder"); if (sortCombo != null) { // The default style fixes the Sort combo control's width to 160, which is bad for localization. // We fix it by setting Min width as 160, and let the control resize to content. sortCombo.ClearValue(FrameworkElement.WidthProperty); sortCombo.MinWidth = 160; } } private void PreparePrereleaseComboBox() { // This ComboBox is actually used to display framework versions in various VS dialogs. // We "repurpose" it here to show Prerelease option instead. ComboBox fxCombo = FindComboBox("cmb_Fx"); if (fxCombo != null) { fxCombo.Items.Clear(); fxCombo.Items.Add(NuGet.Dialog.Resources.Filter_StablePackages); fxCombo.Items.Add(NuGet.Dialog.Resources.Filter_IncludePrerelease); fxCombo.SelectedIndex = _providerSettings.IncludePrereleasePackages ? 1 : 0; fxCombo.SelectionChanged += OnFxComboBoxSelectionChanged; _prereleaseComboBox = fxCombo; } } private void OnFxComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e) { var combo = (ComboBox)sender; if (combo.SelectedIndex == -1) { return; } bool includePrerelease = combo.SelectedIndex == 1; // persist the option to VS settings store _providerSettings.IncludePrereleasePackages = includePrerelease; // set the flags on all providers foreach (PackagesProviderBase provider in explorer.Providers) { provider.IncludePrerelease = includePrerelease; } var selectedTreeNode = explorer.SelectedExtensionTreeNode as PackagesTreeNodeBase; if (selectedTreeNode != null) { selectedTreeNode.Refresh(resetQueryBeforeRefresh: true); } } private ComboBox FindComboBox(string name) { Grid grid = LogicalTreeHelper.FindLogicalNode(explorer, "resGrid") as Grid; if (grid != null) { return FindChildElementByNameOrType(grid, name, typeof(SortCombo)) as ComboBox; } return null; } private static UIElement FindChildElementByNameOrType(Grid parent, string childName, Type childType) { UIElement element = parent.FindName(childName) as UIElement; if (element != null) { return element; } else { foreach (UIElement child in parent.Children) { if (childType.IsInstanceOfType(child)) { return child; } } return null; } } private void OnProviderSelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { var selectedProvider = explorer.SelectedProvider as PackagesProviderBase; if (selectedProvider != null) { explorer.NoItemsMessage = selectedProvider.NoItemsMessage; _prereleaseComboBox.Visibility = selectedProvider.ShowPrereleaseComboBox ? Visibility.Visible : Visibility.Collapsed; // save the selected provider to user settings _providerSettings.SelectedProvider = explorer.Providers.IndexOf(selectedProvider); // if this is the first time online provider is opened, call to check for update if (selectedProvider == explorer.Providers[1] && !_hasOpenedOnlineProvider) { _hasOpenedOnlineProvider = true; _productUpdateService.CheckForAvailableUpdateAsync(); } } else { _prereleaseComboBox.Visibility = Visibility.Collapsed; } } private void OnSendingRequest(object sender, WebRequestEventArgs e) { HttpUtility.SetUserAgent(e.Request, _dialogUserAgent.Value); } private void CanExecuteClose(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = !OperationCoordinator.IsBusy; e.Handled = true; } private void OnDialogWindowLoaded(object sender, RoutedEventArgs e) { // HACK: Keep track of the currently open instance of this class. CurrentInstance = this; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace LunchBox.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
#region Copyright // // Copyright (c) 2015 // by Satrabel // #endregion #region Using Statements using System; using System.Linq; using System.Collections.Generic; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Modules.Actions; using DotNetNuke.Services.Localization; using DotNetNuke.Security; using Satrabel.OpenContent.Components.Razor; using System.IO; using DotNetNuke.Services.Exceptions; using System.Web.UI; using System.Web.Hosting; using Newtonsoft.Json.Linq; using DotNetNuke.Web.Client.ClientResourceManagement; using DotNetNuke.Web.Client; using Satrabel.OpenContent.Components; using Satrabel.OpenContent.Components.Json; using System.Web.WebPages; using System.Web; using System.Web.Helpers; using Satrabel.OpenContent.Components.Handlebars; using DotNetNuke.Framework; using DotNetNuke.Common.Utilities; using DotNetNuke.Common; using Satrabel.OpenContent.Components.Rss; using System.Web.UI.WebControls; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Tabs; using Satrabel.OpenContent.Components.Dynamic; using DotNetNuke.Security.Permissions; using DotNetNuke.Instrumentation; using DotNetNuke.Services.Installer.Log; using Satrabel.OpenContent.Components.Manifest; using Satrabel.OpenContent.Components.Datasource; using Satrabel.OpenContent.Components.Alpaca; using Satrabel.OpenContent.Components.Logging; using Newtonsoft.Json; using System.Text; using Satrabel.OpenContent.Components.Lucene.Config; #endregion namespace Satrabel.OpenContent { /// <summary> /// This view will look in the settings if a template and all the necessary extra has already been defined. /// If so, it will render the template /// If not, it will display a /// </summary> public partial class View : DotNetNuke.Web.Razor.RazorModuleBase, IActionable { private string _itemId = null; private readonly RenderInfo _renderinfo = new RenderInfo(); private OpenContentSettings _settings; #region Event Handlers protected override void OnInit(EventArgs e) { base.OnInit(e); // auto attach a ContentLocalized OpenContent module to the reference module of the default language string openContentAutoAttach = PortalController.GetPortalSetting("OpenContent_AutoAttach", ModuleContext.PortalId, "False"); bool autoAttach = bool.Parse(openContentAutoAttach); if (autoAttach) { //var module = (new ModuleController()).GetModule(ModuleContext.moduleId, ModuleContext.tabId, false); ModuleInfo module = ModuleContext.Configuration; var defaultModule = module.DefaultLanguageModule; if (defaultModule != null) { if (ModuleContext.ModuleId != defaultModule.ModuleID) { var mc = (new ModuleController()); mc.DeLocalizeModule(module); mc.ClearCache(defaultModule.TabID); mc.ClearCache(module.TabID); const string MODULE_SETTINGS_CACHE_KEY = "ModuleSettings{0}"; // to be compatible with dnn 7.2 DataCache.RemoveCache(string.Format(MODULE_SETTINGS_CACHE_KEY, defaultModule.TabID)); DataCache.RemoveCache(string.Format(MODULE_SETTINGS_CACHE_KEY, module.TabID)); //DataCache.ClearCache(); module = mc.GetModule(defaultModule.ModuleID, ModuleContext.TabId, true); _settings = module.OpenContentSettings(); } } } if (_settings == null) _settings = ModuleContext.OpenContentSettings(); OpenContent.TemplateInit ti = (TemplateInit)TemplateInitControl; ti.ModuleContext = ModuleContext; ti.Settings = _settings; ti.Renderinfo = _renderinfo; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (Page.Request.QueryString["id"] != null) { _itemId = Page.Request.QueryString["id"]; } if (!Page.IsPostBack) { if (ModuleContext.PortalSettings.UserId > 0) { string OpenContent_EditorsRoleId = PortalController.GetPortalSetting("OpenContent_EditorsRoleId", ModuleContext.PortalId, ""); if (!string.IsNullOrEmpty(OpenContent_EditorsRoleId)) { int roleId = int.Parse(OpenContent_EditorsRoleId); var objModule = ModuleContext.Configuration; //todo: probable DNN bug. objModule.ModulePermissions doesn't return correct permissions for attached multi-lingual modules //don't alter permissions of modules that are non-default language and that are attached var permExist = objModule.ModulePermissions.Where(tp => tp.RoleID == roleId).Any(); if (!permExist) { //todo sacha: add two permissions, read and write; Or better still add all permissions that are available. eg if you installed extra permissions var permissionController = new PermissionController(); // view permission var arrSystemModuleViewPermissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW"); var permission = (PermissionInfo)arrSystemModuleViewPermissions[0]; var objModulePermission = new ModulePermissionInfo { ModuleID = ModuleContext.Configuration.ModuleID, //ModuleDefID = permission.ModuleDefID, //PermissionCode = permission.PermissionCode, PermissionID = permission.PermissionID, PermissionKey = permission.PermissionKey, RoleID = roleId, //UserID = userId, AllowAccess = true }; objModule.ModulePermissions.Add(objModulePermission); // edit permission arrSystemModuleViewPermissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "EDIT"); permission = (PermissionInfo)arrSystemModuleViewPermissions[0]; objModulePermission = new ModulePermissionInfo { ModuleID = ModuleContext.Configuration.ModuleID, //ModuleDefID = permission.ModuleDefID, //PermissionCode = permission.PermissionCode, PermissionID = permission.PermissionID, PermissionKey = permission.PermissionKey, RoleID = roleId, //UserID = userId, AllowAccess = true }; objModule.ModulePermissions.Add(objModulePermission); try { ModulePermissionController.SaveModulePermissions(objModule); } catch (Exception ex) { //Log.Logger.ErrorFormat("Failed to automaticly set the permission. It already exists? tab={0}, moduletitle={1} ", objModule.TabID ,objModule.ModuleTitle); } } } } } } protected override void OnPreRender(EventArgs e) { //base.OnPreRender(e); //pHelp.Visible = false; //initialize _info state _renderinfo.Template = _settings.Template; _renderinfo.DetailItemId = _itemId; if (_settings.TabId > 0 && _settings.ModuleId > 0) // other module { ModuleController mc = new ModuleController(); _renderinfo.SetDataSourceModule(_settings.TabId, _settings.ModuleId, mc.GetModule(_renderinfo.ModuleId, _renderinfo.TabId, false), null, ""); } else // this module { _renderinfo.SetDataSourceModule(_settings.TabId, ModuleContext.ModuleId, ModuleContext.Configuration, null, ""); } //start rendering InitTemplateInfo(); bool otherModuleWithFilterSettings = _settings.IsOtherModule && !string.IsNullOrEmpty(_settings.Query); if (_renderinfo.ShowInitControl && !otherModuleWithFilterSettings) { /* thows error because _renderinfo.Module is null var templatemissing = OpenContentUtils.CheckOpenContentSettings(_renderinfo.Module, _settings); if (templatemissing) { //todo: show message on screen } */ // no data exist and ... -> show initialization if (ModuleContext.EditMode) { // edit mode if (_renderinfo.Template == null || ModuleContext.IsEditable) { RenderInitForm(); if (_renderinfo.ShowDemoData) { RenderDemoData(); } } else if (_renderinfo.Template != null) { RenderDemoData(); } } else if (_renderinfo.Template != null) { RenderDemoData(); } } if (_renderinfo.Template != null && !string.IsNullOrEmpty(_renderinfo.OutputString)) { //Rendering was succesful. var lit = new LiteralControl(Server.HtmlDecode(_renderinfo.OutputString)); Controls.Add(lit); var mst = _renderinfo.Template.Manifest; bool editWitoutPostback = mst != null && mst.EditWitoutPostback; if (ModuleContext.PortalSettings.EnablePopUps && ModuleContext.IsEditable && editWitoutPostback) { AJAX.WrapUpdatePanelControl(lit, true); } IncludeResourses(_renderinfo.Template); //if (DemoData) pDemo.Visible = true; if (_renderinfo.Template != null && _renderinfo.Template.ClientSideData) { DotNetNuke.Framework.ServicesFramework.Instance.RequestAjaxScriptSupport(); DotNetNuke.Framework.ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); } if (_renderinfo.Files != null && _renderinfo.Files.PartialTemplates != null) { foreach (var item in _renderinfo.Files.PartialTemplates.Where(p => p.Value.ClientSide)) { try { var f = new FileUri(_renderinfo.Template.ManifestDir.FolderPath, item.Value.Template); string s = File.ReadAllText(f.PhysicalFilePath); var litPartial = new LiteralControl(s); Controls.Add(litPartial); } catch (Exception ex) { DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError); } } } } if (LogContext.IsLogActive) { ClientResourceManager.RegisterScript(Page, Page.ResolveUrl("~/DesktopModules/OpenContent/js/opencontent.js"), FileOrder.Js.DefaultPriority); StringBuilder logScript = new StringBuilder(); logScript.AppendLine("<script type=\"text/javascript\"> "); logScript.AppendLine("$(document).ready(function () { "); logScript.AppendLine("var logs = " + JsonConvert.SerializeObject(LogContext.Current.ModuleLogs(ModuleContext.ModuleId)) + "; "); logScript.AppendLine("$.fn.openContent.printLogs('Module " + ModuleContext.ModuleId + " - " + ModuleContext.Configuration.ModuleTitle + "', logs);"); logScript.AppendLine("});"); logScript.AppendLine("</script>"); Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "logScript" + ModuleContext.ModuleId, logScript.ToString()); } } private void RenderInitForm() { OpenContent.TemplateInit ti = (TemplateInit)TemplateInitControl; ti.RenderInitForm(); } public DotNetNuke.Entities.Modules.Actions.ModuleActionCollection ModuleActions { get { var actions = new ModuleActionCollection(); var settings = ModuleContext.OpenContentSettings(); TemplateManifest template = settings.Template; bool templateDefined = template != null; bool listMode = template != null && template.IsListTemplate; if (Page.Request.QueryString["id"] != null) { _itemId = Page.Request.QueryString["id"]; } if (templateDefined) { string title = Localization.GetString((listMode && string.IsNullOrEmpty(_itemId) ? ModuleActionType.AddContent : ModuleActionType.EditContent), LocalResourceFile); if (!string.IsNullOrEmpty(settings.Manifest.Title)) { title = Localization.GetString((listMode && string.IsNullOrEmpty(_itemId) ? "Add.Action" : "Edit.Action"), LocalResourceFile) + " " + settings.Manifest.Title; } actions.Add(ModuleContext.GetNextActionID(), title, ModuleActionType.AddContent, "", (listMode && string.IsNullOrEmpty(_itemId) ? "~/DesktopModules/OpenContent/images/addcontent2.png" : "~/DesktopModules/OpenContent/images/editcontent2.png"), (listMode && !string.IsNullOrEmpty(_itemId) ? ModuleContext.EditUrl("id", _itemId.ToString()) : ModuleContext.EditUrl()), false, SecurityAccessLevel.Edit, true, false); } if (templateDefined && template.Manifest.AdditionalData != null) { foreach (var addData in template.Manifest.AdditionalData) { actions.Add(ModuleContext.GetNextActionID(), addData.Value.Title, ModuleActionType.EditContent, "", "~/DesktopModules/OpenContent/images/editcontent2.png", ModuleContext.EditUrl("key", addData.Key, "EditAddData"), false, SecurityAccessLevel.Edit, true, false); } } /* string AddEditControl = PortalController.GetPortalSetting("OpenContent_AddEditControl", ModuleContext.PortalId, ""); if (TemplateDefined && !string.IsNullOrEmpty(AddEditControl)) { Actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("AddEntity.Action", LocalResourceFile), ModuleActionType.EditContent, "", "", ModuleContext.EditUrl("AddEdit"), false, SecurityAccessLevel.Edit, true, false); } */ if (templateDefined && settings.Template.SettingsNeeded()) { actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("EditSettings.Action", LocalResourceFile), ModuleActionType.ContentOptions, "", "~/DesktopModules/OpenContent/images/editsettings2.png", ModuleContext.EditUrl("EditSettings"), false, SecurityAccessLevel.Admin, true, false); } actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("EditInit.Action", LocalResourceFile), ModuleActionType.ContentOptions, "", "~/DesktopModules/OpenContent/images/editinit.png", ModuleContext.EditUrl("EditInit"), false, SecurityAccessLevel.Admin, true, false); if (templateDefined && listMode) { //bool queryAvailable = settings.Template.QueryAvailable(); if (settings.Manifest.Index) { actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("EditQuery.Action", LocalResourceFile), ModuleActionType.ContentOptions, "", "~/DesktopModules/OpenContent/images/editfilter.png", ModuleContext.EditUrl("EditQuery"), false, SecurityAccessLevel.Admin, true, false); } } if (templateDefined && OpenContentUtils.BuildersExist(settings.Template.ManifestDir)) actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("Builder.Action", LocalResourceFile), ModuleActionType.ContentOptions, "", "~/DesktopModules/OpenContent/images/formbuilder.png", ModuleContext.EditUrl("FormBuilder"), false, SecurityAccessLevel.Admin, true, false); if (templateDefined) actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("EditTemplate.Action", LocalResourceFile), ModuleActionType.ContentOptions, "", "~/DesktopModules/OpenContent/images/edittemplate.png", ModuleContext.EditUrl("EditTemplate"), false, SecurityAccessLevel.Host, true, false); if (templateDefined || settings.Manifest != null) actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("EditData.Action", LocalResourceFile), ModuleActionType.EditContent, "", "~/DesktopModules/OpenContent/images/edit.png", //ModuleContext.EditUrl("EditData"), (listMode && !string.IsNullOrEmpty(_itemId) ? ModuleContext.EditUrl("id", _itemId.ToString(), "EditData") : ModuleContext.EditUrl("EditData")), false, SecurityAccessLevel.Host, true, false); actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("ShareTemplate.Action", LocalResourceFile), ModuleActionType.ContentOptions, "", "~/DesktopModules/OpenContent/images/exchange.png", ModuleContext.EditUrl("ShareTemplate"), false, SecurityAccessLevel.Host, true, false); actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("EditGlobalSettings.Action", LocalResourceFile), ModuleActionType.ContentOptions, "", "~/DesktopModules/OpenContent/images/settings.png", ModuleContext.EditUrl("EditGlobalSettings"), false, SecurityAccessLevel.Host, true, false); /* Actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("EditGlobalSettings.Action", LocalResourceFile), ModuleActionType.ContentOptions, "", "~/DesktopModules/OpenContent/images/settings.png", ModuleContext.EditUrl("EditGlobalSettings"), false, SecurityAccessLevel.Host, true, false); */ actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("Help.Action", LocalResourceFile), ModuleActionType.ContentOptions, "", "~/DesktopModules/OpenContent/images/help.png", "https://opencontent.readme.io", false, SecurityAccessLevel.Host, true, true); return actions; } } private string RemoveHost(string editUrl) { //Dnn sometimes adds an incorrect alias. //To fix this just remove the host. Give the browser a relative url if (string.IsNullOrEmpty(editUrl)) return editUrl; editUrl = editUrl.Replace("//", ""); var pos = editUrl.IndexOf("/"); if (pos == -1) return editUrl; return editUrl.Remove(0, pos); } #endregion private void InitTemplateInfo() { if (_settings.Template != null) { if (_renderinfo.Template.IsListTemplate) { LogContext.Log(ModuleContext.ModuleId, "RequestContext", "QueryParam Id", _itemId); // Multi items template if (string.IsNullOrEmpty(_itemId)) { // List template if (_renderinfo.Template.Main != null) { // for list templates a main template need to be defined _renderinfo.Files = _renderinfo.Template.Main; string templateKey = GetDataList(_renderinfo, _settings, _renderinfo.Template.ClientSideData); if (!string.IsNullOrEmpty(templateKey) && _renderinfo.Template.Views != null && _renderinfo.Template.Views.ContainsKey(templateKey)) { _renderinfo.Files = _renderinfo.Template.Views[templateKey]; } if (!_renderinfo.SettingsMissing) { _renderinfo.OutputString = GenerateListOutput(_settings.Template.Uri().UrlFolder, _renderinfo.Files, _renderinfo.DataList, _renderinfo.SettingsJson); } } } else { // detail template if (_renderinfo.Template.Detail != null) { GetDetailData(_renderinfo, _settings); } if (_renderinfo.Template.Detail != null && !_renderinfo.ShowInitControl) { _renderinfo.Files = _renderinfo.Template.Detail; _renderinfo.OutputString = GenerateOutput(_settings.Template.Uri().UrlFolder, _renderinfo.Template.Detail, _renderinfo.DataJson, _renderinfo.SettingsJson); } else // if itemid not corresponding to this module, show list template { // List template if (_renderinfo.Template.Main != null) { // for list templates a main template need to be defined _renderinfo.Files = _renderinfo.Template.Main; string templateKey = GetDataList(_renderinfo, _settings, _renderinfo.Template.ClientSideData); if (!string.IsNullOrEmpty(templateKey) && _renderinfo.Template.Views != null && _renderinfo.Template.Views.ContainsKey(templateKey)) { _renderinfo.Files = _renderinfo.Template.Views[templateKey]; } if (!_renderinfo.ShowInitControl) { _renderinfo.OutputString = GenerateListOutput(_settings.Template.Uri().UrlFolder, _renderinfo.Files, _renderinfo.DataList, _renderinfo.SettingsJson); } } } } } else { // single item template GetSingleData(_renderinfo, _settings); bool settingsNeeded = _renderinfo.Template.SettingsNeeded(); if (!_renderinfo.ShowInitControl && (!settingsNeeded || !string.IsNullOrEmpty(_renderinfo.SettingsJson))) { _renderinfo.OutputString = GenerateOutput(_renderinfo.Template.Uri(), _renderinfo.DataJson, _renderinfo.SettingsJson, _renderinfo.Template.Main); } } } } private void IncludeResourses(TemplateManifest template) { if (template != null) { //JavaScript.RequestRegistration() //string templateBase = template.FilePath.Replace("$.hbs", ".hbs"); var cssfilename = new FileUri(Path.ChangeExtension(template.Uri().FilePath, "css")); if (cssfilename.FileExists) { ClientResourceManager.RegisterStyleSheet(Page, Page.ResolveUrl(cssfilename.UrlFilePath), FileOrder.Css.PortalCss); } var jsfilename = new FileUri(Path.ChangeExtension(template.Uri().FilePath, "js")); if (jsfilename.FileExists) { ClientResourceManager.RegisterScript(Page, Page.ResolveUrl(jsfilename.UrlFilePath), FileOrder.Js.DefaultPriority + 100); } ClientResourceManager.RegisterScript(Page, Page.ResolveUrl("~/DesktopModules/OpenContent/js/opencontent.js"), FileOrder.Js.DefaultPriority); } } private FileUri CheckFiles(string templateVirtualFolder, TemplateFiles files, string templateFolder) { if (files == null) LoggingUtils.ProcessModuleLoadException(this, new Exception("Manifest.json missing or incomplete")); string templateFile = templateFolder + "\\" + files.Template; string template = templateVirtualFolder + "/" + files.Template; if (!File.Exists(templateFile)) LoggingUtils.ProcessModuleLoadException(this, new Exception("Template " + template + " don't exist")); if (files.PartialTemplates != null) { foreach (var partial in files.PartialTemplates) { templateFile = templateFolder + "\\" + partial.Value.Template; string partialTemplate = templateVirtualFolder + "/" + partial.Value.Template; if (!File.Exists(templateFile)) LoggingUtils.ProcessModuleLoadException(this, new Exception("PartialTemplate " + partialTemplate + " don't exist")); } } return new FileUri(template); } private bool Filter(string json, string key, string value) { bool accept = true; var obj = json.ToJObject("query string filter"); JToken member = obj.SelectToken(key, false); if (member is JArray) { accept = member.Any(c => c.ToString() == value); } else if (member is JValue) { accept = member.ToString() == value; } return accept; } private bool Filter(dynamic obj, string key, string value) { bool accept = true; Object member = DynamicUtils.GetMemberValue(obj, key); if (member is IEnumerable<Object>) { accept = ((IEnumerable<Object>)member).Any(c => c.ToString() == value); } else if (member is string) { accept = (string)member == value; } return accept; } /* * Single Mode template * */ public void GetSingleData(RenderInfo info, OpenContentSettings settings) { info.ResetData(); var ds = DataSourceManager.GetDataSource(settings.Manifest.DataSource); var dsContext = new DataSourceContext() { ModuleId = info.ModuleId, TemplateFolder = settings.TemplateDir.FolderPath, Config = settings.Manifest.DataSourceConfig, Single = true }; var dsItem = ds.Get(dsContext, null); if (dsItem != null) { info.SetData(dsItem, dsItem.Data, settings.Data); } } public string GetDataList(RenderInfo info, OpenContentSettings settings, bool clientSide) { string templateKey = ""; info.ResetData(); var ds = DataSourceManager.GetDataSource(settings.Manifest.DataSource); var dsContext = new DataSourceContext() { ModuleId = info.ModuleId, TemplateFolder = settings.TemplateDir.FolderPath, Config = settings.Manifest.DataSourceConfig }; IEnumerable<IDataItem> dataList = new List<IDataItem>(); if (clientSide || !info.Files.DataInTemplate) { if (ds.Any(dsContext)) { info.SetData(dataList, settings.Data); info.DataExist = true; } if (info.Template.Views != null) { var indexConfig = OpenContentUtils.GetIndexConfig(info.Template.Key.TemplateDir); templateKey = GetTemplateKey(indexConfig); } } else { bool useLucene = info.Template.Manifest.Index; if (useLucene) { var indexConfig = OpenContentUtils.GetIndexConfig(info.Template.Key.TemplateDir); if (info.Template.Views != null) { templateKey = GetTemplateKey(indexConfig); } bool addWorkFlow = ModuleContext.PortalSettings.UserMode != PortalSettings.Mode.Edit; QueryBuilder queryBuilder = new QueryBuilder(indexConfig); if (!string.IsNullOrEmpty(settings.Query)) { var query = JObject.Parse(settings.Query); queryBuilder.Build(query, addWorkFlow, Request.QueryString); } else { queryBuilder.BuildFilter(addWorkFlow, Request.QueryString); } dataList = ds.GetAll(dsContext, queryBuilder.Select).Items; if (LogContext.IsLogActive) { var logKey = "Query"; LogContext.Log(ModuleContext.ModuleId, logKey, "select", queryBuilder.Select); LogContext.Log(ModuleContext.ModuleId, logKey, "result", dataList); } //Log.Logger.DebugFormat("Query returned [{0}] results.", total); if (!dataList.Any()) { //Log.Logger.DebugFormat("Query did not return any results. API request: [{0}], Lucene Filter: [{1}], Lucene Query:[{2}]", settings.Query, queryDef.Filter == null ? "" : queryDef.Filter.ToString(), queryDef.Query == null ? "" : queryDef.Query.ToString()); if (ds.Any(dsContext)) { info.SetData(dataList, settings.Data); info.DataExist = true; } } } else { //dataList = ctrl.GetContents(info.ModuleId).ToList(); dataList = ds.GetAll(dsContext, null).Items; if (LogContext.IsLogActive) { var logKey = "Get all data of module"; LogContext.Log(ModuleContext.ModuleId, logKey, "result", dataList); } } if (dataList.Any()) { info.SetData(dataList, settings.Data); } } return templateKey; } private string GetTemplateKey(FieldConfig IndexConfig) { string templateKey = ""; var queryString = Request.QueryString; if (queryString != null) { foreach (string key in queryString) { if (IndexConfig != null && IndexConfig.Fields != null && IndexConfig.Fields.Any(f => f.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase))) { var indexConfig = IndexConfig.Fields.Single(f => f.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); string val = queryString[key]; if (string.IsNullOrEmpty(templateKey)) templateKey = key; else templateKey += "-" + key; } } } return templateKey; } public void GetDetailData(RenderInfo info, OpenContentSettings settings) { info.ResetData(); var ds = DataSourceManager.GetDataSource(settings.Manifest.DataSource); var dsContext = new DataSourceContext() { ModuleId = info.ModuleId, TemplateFolder = settings.TemplateDir.FolderPath, Config = settings.Manifest.DataSourceConfig }; var dsItem = ds.Get(dsContext, info.DetailItemId); if (LogContext.IsLogActive) { var logKey = "Get detail data"; LogContext.Log(ModuleContext.ModuleId, logKey, "result", dsItem); } if (dsItem != null) { info.SetData(dsItem, dsItem.Data, settings.Data); } } public bool GetDemoData(RenderInfo info, OpenContentSettings settings) { info.ResetData(); //bool settingsNeeded = false; FileUri dataFilename = null; if (info.Template != null) { dataFilename = new FileUri(info.Template.Uri().UrlFolder, "data.json"); ; } if (dataFilename != null && dataFilename.FileExists) { string fileContent = File.ReadAllText(dataFilename.PhysicalFilePath); string settingContent = ""; if (!string.IsNullOrWhiteSpace(fileContent)) { if (settings.Template != null && info.Template.Uri().FilePath == settings.Template.Uri().FilePath) { settingContent = settings.Data; } if (string.IsNullOrEmpty(settingContent)) { var settingsFilename = info.Template.Uri().PhysicalFullDirectory + "\\" + info.Template.Key.ShortKey + "-data.json"; if (File.Exists(settingsFilename)) { settingContent = File.ReadAllText(settingsFilename); } else { //string schemaFilename = info.Template.Uri().PhysicalFullDirectory + "\\" + info.Template.Key.ShortKey + "-schema.json"; //settingsNeeded = File.Exists(schemaFilename); } } } if (!string.IsNullOrWhiteSpace(fileContent)) info.SetData(null, fileContent, settingContent); } return !info.ShowInitControl; //!string.IsNullOrWhiteSpace(info.DataJson) && (!string.IsNullOrWhiteSpace(info.SettingsJson) || !settingsNeeded); } #region Render private string GenerateOutput(string templateVirtualFolder, TemplateFiles files, JToken dataJson, string settingsJson) { // detail template try { if (!(string.IsNullOrEmpty(files.Template))) { string physicalTemplateFolder = Server.MapPath(templateVirtualFolder); FileUri template = CheckFiles(templateVirtualFolder, files, physicalTemplateFolder); if (dataJson != null) { int mainTabId = _settings.DetailTabId > 0 ? _settings.DetailTabId : _settings.TabId; ModelFactory mf = new ModelFactory(_renderinfo.Data, settingsJson, physicalTemplateFolder, _renderinfo.Template.Manifest, _renderinfo.Template, files, ModuleContext.Configuration, ModuleContext.PortalSettings, mainTabId, _settings.ModuleId); dynamic model = mf.GetModelAsDynamic(); if (!string.IsNullOrEmpty(_renderinfo.Template.Manifest.DetailMetaTitle)) { HandlebarsEngine hbEngine = new HandlebarsEngine(); Page.Title = hbEngine.Execute(_renderinfo.Template.Manifest.DetailMetaTitle, model); } if (!string.IsNullOrEmpty(_renderinfo.Template.Manifest.DetailMetaDescription)) { HandlebarsEngine hbEngine = new HandlebarsEngine(); PageUtils.SetPageDescription(Page, hbEngine.Execute(_renderinfo.Template.Manifest.DetailMetaDescription, model)); } if (!string.IsNullOrEmpty(_renderinfo.Template.Manifest.DetailMeta)) { HandlebarsEngine hbEngine = new HandlebarsEngine(); PageUtils.SetPageMeta(Page, hbEngine.Execute(_renderinfo.Template.Manifest.DetailMeta, model)); } return ExecuteTemplate(templateVirtualFolder, files, template, model); } else { return ""; } } else { return ""; } } catch (Exception ex) { LoggingUtils.ProcessModuleLoadException(this, ex); } return ""; } private string GenerateOutput(FileUri template, JToken dataJson, string settingsJson, TemplateFiles files) { try { if (template != null) { string templateVirtualFolder = template.UrlFolder; string physicalTemplateFolder = Server.MapPath(templateVirtualFolder); if (dataJson != null) { ModelFactory mf; int mainTabId = _settings.DetailTabId > 0 ? _settings.DetailTabId : _settings.TabId; if (_renderinfo.Data == null) { // demo data mf = new ModelFactory(_renderinfo.DataJson, settingsJson, physicalTemplateFolder, _renderinfo.Template.Manifest, _renderinfo.Template, files, ModuleContext.Configuration, ModuleContext.PortalSettings, mainTabId, _settings.ModuleId); } else { mf = new ModelFactory(_renderinfo.Data, settingsJson, physicalTemplateFolder, _renderinfo.Template.Manifest, _renderinfo.Template, files, ModuleContext.Configuration, ModuleContext.PortalSettings, mainTabId, _settings.ModuleId); } dynamic model = mf.GetModelAsDynamic(); if (LogContext.IsLogActive) { var logKey = "Render single item template"; LogContext.Log(ModuleContext.ModuleId, logKey, "template", template.FilePath); LogContext.Log(ModuleContext.ModuleId, logKey, "model", model); } if (template.Extension != ".hbs") { return ExecuteRazor(template, model); } else { HandlebarsEngine hbEngine = new HandlebarsEngine(); return hbEngine.Execute(Page, template, model); } } else { return ""; } } else { return ""; } } catch (TemplateException ex) { RenderTemplateException(ex); } catch (InvalidJsonFileException ex) { RenderJsonException(ex); } catch (Exception ex) { LoggingUtils.ProcessModuleLoadException(this, ex); } return ""; } private string GenerateListOutput(string templateVirtualFolder, TemplateFiles files, IEnumerable<IDataItem> dataList, string settingsJson) { try { if (!(string.IsNullOrEmpty(files.Template))) { string physicalTemplateFolder = Server.MapPath(templateVirtualFolder); FileUri templateUri = CheckFiles(templateVirtualFolder, files, physicalTemplateFolder); if (dataList != null) { int MainTabId = _settings.DetailTabId > 0 ? _settings.DetailTabId : _settings.TabId; ModelFactory mf = new ModelFactory(dataList, settingsJson, physicalTemplateFolder, _renderinfo.Template.Manifest, _renderinfo.Template, files, ModuleContext.Configuration, ModuleContext.PortalSettings, MainTabId, _settings.ModuleId); dynamic model = mf.GetModelAsDynamic(); return ExecuteTemplate(templateVirtualFolder, files, templateUri, model); } } } catch (TemplateException ex) { RenderTemplateException(ex); } catch (InvalidJsonFileException ex) { RenderJsonException(ex); } catch (Exception ex) { LoggingUtils.ProcessModuleLoadException(this, ex); } return ""; } private void RenderTemplateException(TemplateException ex) { DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "<p><b>Template error</b></p>" + ex.MessageAsHtml, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError); //DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "<p><b>Template source</b></p>" + Server.HtmlEncode(ex.TemplateSource).Replace("\n", "<br/>"), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.BlueInfo); //DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "<p><b>Template model</b></p> <pre>" + JsonConvert.SerializeObject(ex.TemplateModel, Formatting.Indented)/*.Replace("\n", "<br/>")*/+"</pre>", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.BlueInfo); //lErrorMessage.Text = ex.HtmlMessage; //lErrorModel.Text = "<pre>" + JsonConvert.SerializeObject(ex.TemplateModel, Formatting.Indented)/*.Replace("\n", "<br/>")*/+"</pre>"; if (LogContext.IsLogActive) { var logKey = "Error in tempate"; LogContext.Log(ModuleContext.ModuleId, logKey, "Error", ex.MessageAsList); LogContext.Log(ModuleContext.ModuleId, logKey, "Model", ex.TemplateModel); LogContext.Log(ModuleContext.ModuleId, logKey, "Source", ex.TemplateSource); //LogContext.Log(logKey, "StackTrace", ex.StackTrace); //DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "<p>More info is availale on de browser console (F12)</p>", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.BlueInfo); } LoggingUtils.ProcessLogFileException(this, ex); } private void RenderJsonException(InvalidJsonFileException ex) { DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "<p><b>Json error</b></p>" + ex.MessageAsHtml, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError); if (LogContext.IsLogActive) { var logKey = "Error in json"; LogContext.Log(ModuleContext.ModuleId, logKey, "Error", ex.MessageAsList); LogContext.Log(ModuleContext.ModuleId, logKey, "Filename", ex.Filename); //LogContext.Log(logKey, "StackTrace", ex.StackTrace); //DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "<p>More info is availale on de browser console (F12)</p>", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.BlueInfo); } LoggingUtils.ProcessLogFileException(this, ex); } private string ExecuteRazor(FileUri template, dynamic model) { string webConfig = template.PhysicalFullDirectory; // Path.GetDirectoryName(template.PhysicalFilePath); webConfig = webConfig.Remove(webConfig.LastIndexOf("\\")) + "\\web.config"; if (!File.Exists(webConfig)) { string filename = HostingEnvironment.MapPath("~/DesktopModules/OpenContent/Templates/web.config"); File.Copy(filename, webConfig); } try { var writer = new StringWriter(); try { var razorEngine = new RazorEngine("~/" + template.FilePath, ModuleContext, LocalResourceFile); RazorRender(razorEngine.Webpage, writer, model); } catch (Exception ex) { string stack = string.Join("\n", ex.StackTrace.Split('\n').Where(s => s.Contains("\\Portals\\") && s.Contains("in")).Select(s => s.Substring(s.IndexOf("in"))).ToArray()); throw new TemplateException("Failed to render Razor template " + template.FilePath + "\n" + stack, ex, model, template.FilePath); } return writer.ToString(); } catch (TemplateException ex) { RenderTemplateException(ex); return ""; } catch (InvalidJsonFileException ex) { RenderJsonException(ex); return ""; } catch (Exception ex) { LoggingUtils.ProcessModuleLoadException(this, ex); return ""; } } private string ExecuteTemplate(string templateVirtualFolder, TemplateFiles files, FileUri template, dynamic model) { if (LogContext.IsLogActive) { var logKey = "Render template"; LogContext.Log(ModuleContext.ModuleId, logKey, "template", template.FilePath); LogContext.Log(ModuleContext.ModuleId, logKey, "model", model); } if (template.Extension != ".hbs") { return ExecuteRazor(template, model); } else { HandlebarsEngine hbEngine = new HandlebarsEngine(); return hbEngine.Execute(Page, this, files, templateVirtualFolder, model); } } private void RenderDemoData() { TemplateManifest template = _renderinfo.Template; if (template != null && template.IsListTemplate) { // Multi items template if (string.IsNullOrEmpty(_renderinfo.DetailItemId)) { // List template if (template.Main != null) { // for list templates a main template need to be defined _renderinfo.Files = _renderinfo.Template.Main; /* GetDataList(_renderinfo, _settings, template.ClientSideData); if (!_renderinfo.SettingsMissing) { _renderinfo.OutputString = GenerateListOutput(_renderinfo.Template.Uri().UrlFolder, template.Main, _renderinfo.DataList, _renderinfo.SettingsJson); } */ } } } else { bool demoExist = GetDemoData(_renderinfo, _settings); bool settingsNeeded = _renderinfo.Template.SettingsNeeded(); if (demoExist && (!settingsNeeded || !string.IsNullOrEmpty(_renderinfo.SettingsJson))) { _renderinfo.OutputString = GenerateOutput(_renderinfo.Template.Uri(), _renderinfo.DataJson, _renderinfo.SettingsJson, _renderinfo.Template.Main); } //too many rendering issues //bool dsDataExist = _datasource.GetOtherModuleDemoData(_info, _info, _settings); //if (dsDataExist) // _info.OutputString = GenerateOutput(_info.Template.Uri(), _info.DataJson, _info.SettingsJson, null); } } private void RazorRender(WebPageBase webpage, TextWriter writer, dynamic model) { var httpContext = new HttpContextWrapper(System.Web.HttpContext.Current); if ((webpage) is OpenContentWebPage) { var mv = (OpenContentWebPage)webpage; mv.Model = model; } if (webpage != null) webpage.ExecutePageHierarchy(new WebPageContext(httpContext, webpage, null), writer, webpage); } #endregion } }
using System; using Server.Targeting; using Server.Network; using Server.Misc; using Server.Items; using System.Collections; using Server.Mobiles; namespace Server.Spells.Druid { public class EnchantedGroveSpell : DruidicSpell { private static SpellInfo m_Info = new SpellInfo( "Enchanted Grove", "En Ante Ohm Sepa", // SpellCircle.Eighth, 266, 9040, false, Reagent.MandrakeRoot, Reagent.PetrifiedWood, Reagent.SpringWater ); public override TimeSpan CastDelayBase { get { return TimeSpan.FromSeconds( 1 ); } } public override SpellCircle Circle { get { return SpellCircle.Eighth; } } public override double RequiredSkill{ get{ return 75.0; } } public override int RequiredMana{ get{ return 60; } } public EnchantedGroveSpell( Mobile caster, Item scroll ) : base( caster, scroll, m_Info ) { } public override void OnCast() { Caster.Target = new InternalTarget( this ); } public void Target( IPoint3D p ) { if ( !Caster.CanSee( p ) ) { Caster.SendLocalizedMessage( 500237 ); // Target can not be seen. } else if ( /*SpellHelper.CheckTown( p, Caster ) &&*/ CheckSequence() ) { if(this.Scroll!=null) Scroll.Consume(); SpellHelper.Turn( Caster, p ); SpellHelper.GetSurfaceTop( ref p ); Effects.PlaySound( p, Caster.Map, 0x2 ); Point3D loc = new Point3D( p.X, p.Y, p.Z ); int grovex; int grovey; int grovez; InternalItem groveStone = new InternalItem( Caster.Location, Caster.Map, Caster ); grovex=loc.X; grovey=loc.Y; grovez=loc.Z; groveStone.ItemID=0x08E3; groveStone.Name="sacred stone"; Point3D stonexyz = new Point3D(grovex,grovey,grovez); groveStone.MoveToWorld( stonexyz, Caster.Map ); InternalItem grovea = new InternalItem( Caster.Location, Caster.Map, Caster ); grovex=loc.X-2; grovey=loc.Y-2; grovez=loc.Z; grovea.ItemID=3290; Point3D grovexyz = new Point3D(grovex,grovey,grovez); grovea.MoveToWorld( grovexyz, Caster.Map ); InternalItem grovec = new InternalItem( Caster.Location, Caster.Map, Caster ); grovex=loc.X; grovey=loc.Y-3; grovez=loc.Z; grovec.ItemID=3293; Point3D grovexyzb = new Point3D(grovex,grovey,grovez); grovec.MoveToWorld( grovexyzb, Caster.Map ); InternalItem groved = new InternalItem( Caster.Location, Caster.Map, Caster ); groved.ItemID=3290; grovex=loc.X+2; grovey=loc.Y-2; grovez=loc.Z; Point3D grovexyzc = new Point3D(grovex,grovey,grovez); groved.MoveToWorld( grovexyzc, Caster.Map ); InternalItem grovee = new InternalItem( Caster.Location, Caster.Map, Caster ); grovex=loc.X+3; grovee.ItemID=3290; grovey=loc.Y; grovez=loc.Z; Point3D grovexyzd = new Point3D(grovex,grovey,grovez); grovee.MoveToWorld( grovexyzd, Caster.Map ); InternalItem grovef = new InternalItem( Caster.Location, Caster.Map, Caster ); grovef.ItemID=3293; grovex=loc.X+2; grovey=loc.Y+2; grovez=loc.Z; Point3D grovexyze = new Point3D(grovex,grovey,grovez); grovef.MoveToWorld( grovexyze, Caster.Map ); InternalItem groveg = new InternalItem( Caster.Location, Caster.Map, Caster ); grovex=loc.X; groveg.ItemID=3290; grovey=loc.Y+3; grovez=loc.Z; Point3D grovexyzf = new Point3D(grovex,grovey,grovez); groveg.MoveToWorld( grovexyzf, Caster.Map ); InternalItem groveh = new InternalItem( Caster.Location, Caster.Map, Caster ); grovex=loc.X-2; groveh.ItemID=3293; grovey=loc.Y+2; grovez=loc.Z; Point3D grovexyzg = new Point3D(grovex,grovey,grovez); groveh.MoveToWorld( grovexyzg, Caster.Map ); InternalItem grovei = new InternalItem( Caster.Location, Caster.Map, Caster ); grovex=loc.X-3; grovei.ItemID=3293; grovey=loc.Y; grovez=loc.Z; Point3D grovexyzh = new Point3D(grovex,grovey,grovez); grovei.MoveToWorld( grovexyzh, Caster.Map ); InternalItem leavesa = new InternalItem( Caster.Location, Caster.Map, Caster ); grovex=loc.X-2; grovey=loc.Y-2; grovez=loc.Z; leavesa.ItemID=3291; Point3D leafxyz = new Point3D(grovex,grovey,grovez); leavesa.MoveToWorld( leafxyz, Caster.Map ); InternalItem leavesc = new InternalItem( Caster.Location, Caster.Map, Caster ); grovex=loc.X; grovey=loc.Y-3; grovez=loc.Z; leavesc.ItemID=3294; Point3D leafxyzb = new Point3D(grovex,grovey,grovez); leavesc.MoveToWorld( leafxyzb, Caster.Map ); InternalItem leavesd = new InternalItem( Caster.Location, Caster.Map, Caster ); leavesd.ItemID=3291; grovex=loc.X+2; grovey=loc.Y-2; grovez=loc.Z; Point3D leafxyzc = new Point3D(grovex,grovey,grovez); leavesd.MoveToWorld( leafxyzc, Caster.Map ); InternalItem leavese = new InternalItem( Caster.Location, Caster.Map, Caster ); grovex=loc.X+3; leavese.ItemID=3291; grovey=loc.Y; grovez=loc.Z; Point3D leafxyzd = new Point3D(grovex,grovey,grovez); leavese.MoveToWorld( leafxyzd, Caster.Map ); InternalItem leavesf = new InternalItem( Caster.Location, Caster.Map, Caster ); leavesf.ItemID=3294; grovex=loc.X+2; grovey=loc.Y+2; grovez=loc.Z; Point3D leafxyze = new Point3D(grovex,grovey,grovez); leavesf.MoveToWorld( leafxyze, Caster.Map ); InternalItem leavesg = new InternalItem( Caster.Location, Caster.Map, Caster ); grovex=loc.X; leavesg.ItemID=3291; grovey=loc.Y+3; grovez=loc.Z; Point3D leafxyzf = new Point3D(grovex,grovey,grovez); leavesg.MoveToWorld( leafxyzf, Caster.Map ); InternalItem leavesh = new InternalItem( Caster.Location, Caster.Map, Caster ); grovex=loc.X-2; leavesh.ItemID=3294; grovey=loc.Y+2; grovez=loc.Z; Point3D leafxyzg = new Point3D(grovex,grovey,grovez); leavesh.MoveToWorld( leafxyzg, Caster.Map ); InternalItem leavesi = new InternalItem( Caster.Location, Caster.Map, Caster ); grovex=loc.X-3; leavesi.ItemID=3294; grovey=loc.Y; grovez=loc.Z; Point3D leafxyzh = new Point3D(grovex,grovey,grovez); leavesi.MoveToWorld( leafxyzh, Caster.Map ); } FinishSequence(); } [DispellableField] private class InternalItem : Item { private Timer m_Timer; private Timer m_Bless; private DateTime m_End; private Mobile m_Caster; public override bool BlocksFit{ get{ return true; } } public InternalItem( Point3D loc, Map map, Mobile caster ) : base( 0x3274 ) { Visible = false; Movable = false; MoveToWorld( loc, map ); m_Caster=caster; if ( caster.InLOS( this ) ) Visible = true; else Delete(); if ( Deleted ) return; m_Timer = new InternalTimer( this, TimeSpan.FromSeconds( 30.0 ) ); m_Timer.Start(); m_Bless = new BlessTimer( this, m_Caster ); m_Bless.Start(); m_End = DateTime.Now + TimeSpan.FromSeconds( 30.0 ); } public InternalItem( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 1 ); // version writer.Write( m_End - DateTime.Now ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 1: { TimeSpan duration = reader.ReadTimeSpan(); m_Timer = new InternalTimer( this, duration ); m_Timer.Start(); m_End = DateTime.Now + duration; break; } case 0: { TimeSpan duration = TimeSpan.FromSeconds( 10.0 ); m_Timer = new InternalTimer( this, duration ); m_Timer.Start(); m_End = DateTime.Now + duration; break; } } } public override void OnAfterDelete() { base.OnAfterDelete(); if ( m_Timer != null ) m_Timer.Stop(); } private class InternalTimer : Timer { private Timer m_Bless; private InternalItem m_Item; public InternalTimer( InternalItem item, TimeSpan duration ) : base( duration ) { m_Item = item; } protected override void OnTick() { m_Item.Delete(); } } } private class InternalTarget : Target { private EnchantedGroveSpell m_Owner; public InternalTarget( EnchantedGroveSpell owner ) : base( 12, true, TargetFlags.None ) { m_Owner = owner; } protected override void OnTarget( Mobile from, object o ) { if ( o is IPoint3D ) m_Owner.Target( (IPoint3D)o ); } protected override void OnTargetFinish( Mobile from ) { m_Owner.FinishSequence(); } } private class BlessTimer : Timer { private Item m_EnchantedGrove; private Mobile m_Caster; private DateTime m_Duration; private static Queue m_Queue = new Queue(); public BlessTimer( Item ap, Mobile ca ) : base( TimeSpan.FromSeconds( 0.5 ), TimeSpan.FromSeconds( 1.0 ) ) { Priority = TimerPriority.FiftyMS; m_EnchantedGrove = ap; m_Caster=ca; m_Duration = DateTime.Now + TimeSpan.FromSeconds( 15.0 + ( Utility.RandomDouble() * 15.0 ) ); } protected override void OnTick() { if ( m_EnchantedGrove.Deleted ) return; if ( DateTime.Now > m_Duration ) { Stop(); } else { ArrayList list = new ArrayList(); foreach ( Mobile m in m_EnchantedGrove.GetMobilesInRange( 5 ) ) { if ( m.Player && m.Karma >= 0 && m.Alive ) list.Add( m ); } for ( int i = 0; i < list.Count; ++i ) { Mobile m = (Mobile)list[i]; bool friendly = true; for ( int j = 0; friendly && j < m_Caster.Aggressors.Count; ++j ) friendly = ( ((AggressorInfo)m_Caster.Aggressors[j]).Attacker != m ); for ( int j = 0; friendly && j < m_Caster.Aggressed.Count; ++j ) friendly = ( ((AggressorInfo)m_Caster.Aggressed[j]).Defender != m ); if ( friendly ) { m.FixedEffect( 0x37C4, 1, 12, 1109, 3 ); // At player m.Mana += (1 + (m_Caster.Karma / 1000)); m.Hits += (1 + (m_Caster.Karma / 1000)); } } } } } } }
using Hashtable = ExitGames.Client.Photon.Hashtable; using System; using System.Collections; using System.Collections.Generic; using System.Text; using ExitGames.Client.Photon; using ExitGames.Client.Photon.Lite; using UnityEngine; public class NetworkController : MonoBehaviour, IPhotonPeerListener { #region Info public string applicationName = "SimpleServer"; public int applicationVersion = 1; public static NetworkController Instance; public NetworkPeer Peer { get; set; } private const int SEND_INTERVAL = 100; private int sendTickCount = Environment.TickCount; // address public enum SERVER_ADDRESS { LOCAL, TEST, }; public SERVER_ADDRESS serverAddress; public string ServerEndPoint { get { switch (serverAddress) { case SERVER_ADDRESS.TEST: return "127.0.0.1:5055"; default: return "127.0.0.1:5055"; } } } // connection type public ConnectionProtocol connectionProtocol = ConnectionProtocol.Udp; #endregion // event public static event OnConnected onConnected; public static event OnDisconnected onDisconnected; public static event OnDisconnectByServer onDisconnectByServer; public static event OnDisconnectByServerLogic onDisconnectByServerLogic; public static event OnDisconnectByServerUserLimit onDisconnectByServerUserLimit; public static event OnEncryptionEstablished onEncryptionEstablished; public static event OnEncryptionFailedToEstablish onEncryptionFailedToEstablish; public static event OnException onException; public static event OnExceptionOnConnect onExceptionOnConnect; public static event OnExceptionOnReceive onExceptionOnReceive; [Obsolete("InternalReceiveException mark as deprecated by photon client sdk")] public static event OnInternalReceiveException onInternalReceiveException; public static event OnQueueIncomingReliableWarning onQueueIncomingReliableWarning; public static event OnQueueIncomingUnreliableWarning onQueueIncomingUnreliableWarning; public static event OnQueueOutgoingAcksWarning onQueueOutgoingAcksWarning; public static event OnQueueOutgoingReliableWarning onQueueOutgoingReliableWarning; public static event OnQueueOutgoingUnreliableWarning onQueueOutgoingUnreliableWarning; public static event OnQueueSentWarning onQueueSentWarning; public static event OnSecurityExceptionOnConnect onSecurityExceptionOnConnect; public static event OnSendError onSendError; [Obsolete("TcpRouterResponseEndpointUnknown mark as deprecated by photon client sdk")] public static event OnTcpRouterResponseEndpointUnknown onTcpRouterResponseEndpointUnknown; [Obsolete("TcpRouterResponseNodeIdUnknown mark as deprecated by photon client sdk")] public static event OnTcpRouterResponseNodeIdUnknown onTcpRouterResponseNodeIdUnknown; [Obsolete("TcpRouterResponseNodeNotReady mark as deprecated by photon client sdk")] public static event OnTcpRouterResponseNodeNotReady onTcpRouterResponseNodeNotReady; [Obsolete("TcpRouterResponseOk mark as deprecated by photon client sdk")] public static event OnTcpRouterResponseOk onOnTcpRouterResponseOk; public static event OnTimeoutDisconnect onTimeoutDisconnect; public delegate void _OnOperationResponse(OperationResponse operationResponse, IPhotonPeerListener peer); public static event _OnOperationResponse onOperationResponse; public virtual void Awake() { Instance = this; Peer = new NetworkPeer(this, connectionProtocol); enabled = false; // debug onConnected += () => DebugReturn(DebugLevel.INFO, "Connected"); onDisconnected += () => DebugReturn(DebugLevel.INFO, "Disconnected"); } public void Connect() { DebugReturn(DebugLevel.INFO, "Connecting..."); if (Peer.PeerState == PeerStateValue.Connected) return; if (Peer.Connect(ServerEndPoint, String.Format("{0} - {1}", applicationName, applicationVersion))) { enabled = true; } } public void DebugReturn(DebugLevel level, string message) { Client.Instance.DebugText.text += String.Format("[{0}] {1} \n", level.ToString(), message); switch (level) { case DebugLevel.INFO: Debug.Log(message); break; case DebugLevel.ERROR: Debug.LogError(message); break; case DebugLevel.ALL: Debug.Log(message); break; case DebugLevel.WARNING: Debug.LogWarning(message); break; default: break; } } public void OnEvent(EventData eventData) { DebugReturn(DebugLevel.INFO, String.Format("OnEvent: {0}", eventData.ToStringFull())); } public void OnOperationResponse(OperationResponse operationResponse) { DebugReturn(DebugLevel.INFO, String.Format("OnOperationResponse: {0}", operationResponse.ToStringFull())); if (onOperationResponse != null) onOperationResponse(operationResponse, this); } public void OnStatusChanged(StatusCode statusCode) { switch (statusCode) { case StatusCode.Connect: if (onConnected != null) onConnected(); break; case StatusCode.Disconnect: if (onDisconnected != null) onDisconnected(); break; case StatusCode.DisconnectByServer: if (onDisconnectByServer != null) onDisconnectByServer(); break; case StatusCode.DisconnectByServerLogic: if (onDisconnectByServerLogic != null) onDisconnectByServerLogic(); break; case StatusCode.DisconnectByServerUserLimit: if (onDisconnectByServerUserLimit != null) onDisconnectByServerUserLimit(); break; case StatusCode.EncryptionEstablished: if (onEncryptionEstablished != null) onEncryptionEstablished(); break; case StatusCode.EncryptionFailedToEstablish: if (onEncryptionFailedToEstablish != null) onEncryptionFailedToEstablish(); break; case StatusCode.Exception: if (onException != null) onException(); break; case StatusCode.ExceptionOnConnect: if (onExceptionOnConnect != null) onExceptionOnConnect(); break; case StatusCode.ExceptionOnReceive: if (onExceptionOnReceive != null) onExceptionOnReceive(); break; case StatusCode.QueueIncomingReliableWarning: if (onQueueIncomingReliableWarning != null) onQueueIncomingReliableWarning(); break; case StatusCode.QueueIncomingUnreliableWarning: if (onQueueIncomingUnreliableWarning != null) onQueueIncomingUnreliableWarning(); break; case StatusCode.QueueOutgoingAcksWarning: if (onQueueOutgoingAcksWarning != null) onQueueOutgoingAcksWarning(); break; case StatusCode.QueueOutgoingReliableWarning: if (onQueueOutgoingReliableWarning != null) onQueueOutgoingReliableWarning(); break; case StatusCode.QueueOutgoingUnreliableWarning: if (onQueueOutgoingUnreliableWarning != null) onQueueOutgoingUnreliableWarning(); break; case StatusCode.QueueSentWarning: if (onQueueSentWarning != null) onQueueSentWarning(); break; case StatusCode.SecurityExceptionOnConnect: if (onSecurityExceptionOnConnect != null) onSecurityExceptionOnConnect(); break; case StatusCode.SendError: if (onSendError != null) onSendError(); break; case StatusCode.TimeoutDisconnect: if (onTimeoutDisconnect != null) onTimeoutDisconnect(); break; } } public virtual void Update() { //Send update each SEND_INTERVAL if (Environment.TickCount > sendTickCount) { if (Peer == null) { Application.Quit(); } Peer.Service(); sendTickCount = Environment.TickCount + SEND_INTERVAL; } } public virtual void OnApplicationQuit() { Peer.Disconnect(); } }
namespace SPALM.SPSF.Library { using System; using System.Collections; using System.Collections.Generic; using System.Windows.Forms; public partial class SelectionForm : Form { List<NameValueItem> nvitems = null; private bool multipleItems = false; private bool groupItems = true; private object selection; public SelectionForm(List<NameValueItem> _nvitems, object _selection, bool grouped) { InitializeComponent(); nvitems = _nvitems; groupItems = grouped; selection = _selection; GenerateTree(); } private void GenerateTree() { treeView.Nodes.Clear(); //if in all items the groups are empty then grouping should be disabled CheckGrouped(); if (selection is NameValueItem) { InitiallySelectedNameValueItem = (NameValueItem)selection; } else if (selection is NameValueItem[]) { multipleItems = true; InitiallySelectedNameValueItems = (NameValueItem[])selection; } if (multipleItems) { treeView.CheckBoxes = true; } if (nvitems != null) { if (groupItems) { //first grouping foreach (NameValueItem nvitem in nvitems) { string key = nvitem.Group; if ((key == null) || (key == "")) { key = "[nogroup]"; } TreeNode groupnode = null; if (!treeView.Nodes.ContainsKey(key)) { //create new group groupnode = new TreeNode(); groupnode.Text = key; groupnode.Name = key; //if(key.Equals(SPSFConstants.ThisSolutionNodeText, StringComparison.InvariantCultureIgnoreCase)){ // groupnode.NodeFont = new Font(treeView.Font, FontStyle.Bold); //} treeView.Nodes.Add(groupnode); } else { groupnode = treeView.Nodes[key]; } if (groupnode != null && !string.IsNullOrEmpty(nvitem.Name) && (!nvitem.Name.StartsWith("$Resources:",StringComparison.InvariantCultureIgnoreCase) || key.Equals(SPSFConstants.ThisSolutionNodeText, StringComparison.InvariantCultureIgnoreCase))) { TreeNode tnode = new TreeNode(); tnode.Text = nvitem.Name; tnode.Tag = nvitem; tnode.ToolTipText = nvitem.Description; groupnode.Nodes.Add(tnode); if (InitiallySelectedNameValueItem != null) { if (nvitem.Value == InitiallySelectedNameValueItem.Value) { groupnode.Expand(); } } if (InitiallySelectedNameValueItems != null) { foreach (NameValueItem nvi in InitiallySelectedNameValueItems) { if (nvi.Value == nvitem.Value) { tnode.Checked = true; groupnode.Expand(); } } } } } } else { foreach (NameValueItem nvitem in nvitems) { //gibt es das item schon auf 1. ebene? if (!NodeExists(nvitem) && !string.IsNullOrEmpty(nvitem.Name) ) /*&& (!nvitem.Name.StartsWith("$Resources:",StringComparison.InvariantCultureIgnoreCase) || key.Equals(SPSFConstants.ThisSolutionNodeText, StringComparison.InvariantCultureIgnoreCase)))*/ { TreeNode tnode = new TreeNode(); tnode.Text = nvitem.Name; tnode.Tag = nvitem; tnode.ToolTipText = nvitem.Description; treeView.Nodes.Add(tnode); } } } } treeView.Sort(); ValidateButtons(); } private void SearchTree() { string searchstring = this.textBox1.Text; if(searchstring != "") { treeView.Nodes.Clear(); searchstring = searchstring.ToUpper(); foreach (NameValueItem nvitem in nvitems) { bool additem = false; if (nvitem.Name != null) { if (nvitem.Name.ToUpper().Contains(searchstring)) { additem = true; } } else if (nvitem.Value != null) { if (nvitem.Value.ToUpper().Contains(searchstring)) { additem = true; } } if (additem) { //gibt es das item schon auf 1. ebene? if (!NodeExists(nvitem)) { TreeNode tnode = new TreeNode(); tnode.Text = nvitem.Name; tnode.Tag = nvitem; tnode.ToolTipText = nvitem.Description; treeView.Nodes.Add(tnode); } } } } treeView.Sort(); } private bool NodeExists(NameValueItem nvitem) { foreach (TreeNode node in treeView.Nodes) { if (node.Tag != null) { if ((((NameValueItem)node.Tag).Name == nvitem.Name) && (((NameValueItem)node.Tag).Value == nvitem.Value)) { return true; } } } return false; } private void CheckGrouped() { bool nonEmptyGroupFound = false; foreach (NameValueItem nvitem in nvitems) { if (nvitem.Group.Trim() != "") { nonEmptyGroupFound = true; } } if (!nonEmptyGroupFound) { groupItems = false; } } public NameValueItem InitiallySelectedNameValueItem = null; public NameValueItem[] InitiallySelectedNameValueItems = null; public NameValueItem SelectedNameValueItem = null; public NameValueItem[] SelectedNameValueItems = new NameValueItem[0]; private void treeView_AfterSelect(object sender, TreeViewEventArgs e) { if (treeView.SelectedNode != null) { if (treeView.SelectedNode.Tag != null) { NameValueItem item = (NameValueItem)treeView.SelectedNode.Tag; selectedValue.Text = item.Value; selectedName.Text = item.Name; selectedDescription.Text = item.Description; selectedGroup.Text = item.Group; } else { selectedValue.Text = ""; selectedName.Text = ""; selectedDescription.Text = ""; selectedGroup.Text = ""; } } ValidateButtons(); } private void FindSelectedNodes(TreeNodeCollection nodes, ArrayList items) { foreach (TreeNode node in nodes) { if (node.Checked) { if (node.Tag != null) { if (node.Tag is NameValueItem) { items.Add(node.Tag); } } } FindSelectedNodes(node.Nodes, items); } } private void ValidateButtons() { buton_ok.Enabled = false; if ((treeView.SelectedNode != null) && (treeView.SelectedNode.Tag != null)) { buton_ok.Enabled = true; } else if (treeView.CheckBoxes) { ArrayList items = new ArrayList(); FindSelectedNodes(treeView.Nodes, items); if (items.Count > 0) { buton_ok.Enabled = true; } } } private void button1_Click(object sender, EventArgs e) { CloseForm(); } private void CloseForm() { if (multipleItems) { ArrayList items = new ArrayList(); FindSelectedNodes(treeView.Nodes, items); SelectedNameValueItems = new NameValueItem[items.Count]; for (int i = 0; i < items.Count; i++) { SelectedNameValueItems[i] = (NameValueItem)items[i]; } } else { if (treeView.SelectedNode != null) { if (treeView.SelectedNode.Tag != null) { SelectedNameValueItem = (NameValueItem)treeView.SelectedNode.Tag; selectedValue.Text = SelectedNameValueItem.Value; selectedName.Text = SelectedNameValueItem.Name; selectedDescription.Text = SelectedNameValueItem.Description; selectedGroup.Text = SelectedNameValueItem.Group; } else { selectedValue.Text = ""; selectedName.Text = ""; selectedDescription.Text = ""; selectedGroup.Text = ""; } } } } private void button3_Click(object sender, EventArgs e) { SearchTree(); ValidateButtons(); } private void button1_Click_1(object sender, EventArgs e) { textBox1.Text = ""; GenerateTree(); ValidateButtons(); } private void treeView_AfterCheck(object sender, TreeViewEventArgs e) { if (e.Node != null) { if (e.Node.Nodes.Count > 0) { foreach(TreeNode childNode in e.Node.Nodes) { childNode.Checked = e.Node.Checked; } } } ValidateButtons(); } private void treeView_DoubleClick(object sender, EventArgs e) { if (buton_ok.Enabled) { CloseForm(); } } private void textBox1_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { SearchTree(); ValidateButtons(); } } private void textBox1_TextChanged(object sender, EventArgs e) { } private void panel2_Paint(object sender, PaintEventArgs e) { } } }
// 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.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Framework.Testing; using osu.Framework.Timing; using osu.Game.Beatmaps; using osu.Game.Database; using osu.Game.Online.API; using osu.Game.Online.API.Requests.Responses; using osu.Game.Overlays; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.UI; using osu.Game.Screens; using osu.Game.Storyboards; using osu.Game.Tests.Beatmaps; namespace osu.Game.Tests.Visual { [ExcludeFromDynamicCompile] public abstract class OsuTestScene : TestScene { protected Bindable<WorkingBeatmap> Beatmap { get; private set; } protected Bindable<RulesetInfo> Ruleset; protected Bindable<IReadOnlyList<Mod>> SelectedMods; protected new OsuScreenDependencies Dependencies { get; private set; } protected IResourceStore<byte[]> Resources; protected IAPIProvider API { get { if (UseOnlineAPI) throw new InvalidOperationException($"Using the {nameof(OsuTestScene)} dummy API is not supported when {nameof(UseOnlineAPI)} is true"); return dummyAPI; } } private DummyAPIAccess dummyAPI; /// <summary> /// Whether this test scene requires real-world API access. /// If true, this will bypass the local <see cref="DummyAPIAccess"/> and use the <see cref="OsuGameBase"/> provided one. /// </summary> protected virtual bool UseOnlineAPI => false; /// <summary> /// A database context factory to be used by test runs. Can be isolated and reset by setting <see cref="UseFreshStoragePerRun"/> to <c>true</c>. /// </summary> /// <remarks> /// In interactive runs (ie. VisualTests) this will use the user's database if <see cref="UseFreshStoragePerRun"/> is not set to <c>true</c>. /// </remarks> protected DatabaseContextFactory ContextFactory => contextFactory.Value; private Lazy<DatabaseContextFactory> contextFactory; /// <summary> /// Whether a fresh storage should be initialised per test (method) run. /// </summary> /// <remarks> /// By default (ie. if not set to <c>true</c>): /// - in interactive runs, the user's storage will be used /// - in headless runs, a shared temporary storage will be used per test class. /// </remarks> protected virtual bool UseFreshStoragePerRun => false; /// <summary> /// A storage to be used by test runs. Can be isolated by setting <see cref="UseFreshStoragePerRun"/> to <c>true</c>. /// </summary> /// <remarks> /// In interactive runs (ie. VisualTests) this will use the user's storage if <see cref="UseFreshStoragePerRun"/> is not set to <c>true</c>. /// </remarks> protected Storage LocalStorage => localStorage.Value; private Lazy<Storage> localStorage; private Storage headlessHostStorage; private DrawableRulesetDependencies rulesetDependencies; protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { headlessHostStorage = (parent.Get<GameHost>() as HeadlessGameHost)?.Storage; Resources = parent.Get<OsuGameBase>().Resources; contextFactory = new Lazy<DatabaseContextFactory>(() => { var factory = new DatabaseContextFactory(LocalStorage); using (var usage = factory.Get()) usage.Migrate(); return factory; }); RecycleLocalStorage(false); var baseDependencies = base.CreateChildDependencies(parent); var providedRuleset = CreateRuleset(); if (providedRuleset != null) baseDependencies = rulesetDependencies = new DrawableRulesetDependencies(providedRuleset, baseDependencies); Dependencies = new OsuScreenDependencies(false, baseDependencies); Beatmap = Dependencies.Beatmap; Beatmap.SetDefault(); Ruleset = Dependencies.Ruleset; Ruleset.SetDefault(); SelectedMods = Dependencies.Mods; SelectedMods.SetDefault(); if (!UseOnlineAPI) { dummyAPI = new DummyAPIAccess(); Dependencies.CacheAs<IAPIProvider>(dummyAPI); base.Content.Add(dummyAPI); } return Dependencies; } protected override Container<Drawable> Content => content ?? base.Content; private readonly Container content; protected OsuTestScene() { base.Content.Add(content = new DrawSizePreservingFillContainer()); } public virtual void RecycleLocalStorage(bool isDisposing) { if (localStorage?.IsValueCreated == true) { try { localStorage.Value.DeleteDirectory("."); } catch { // we don't really care if this fails; it will just leave folders lying around from test runs. } } localStorage = new Lazy<Storage>(() => { // When running headless, there is an opportunity to use the host storage rather than creating a second isolated one. // This is because the host is recycled per TestScene execution in headless at an nunit level. // Importantly, we can't use this optimisation when `UseFreshStoragePerRun` is true, as it doesn't reset per test method. if (!UseFreshStoragePerRun && headlessHostStorage != null) return headlessHostStorage; return new TemporaryNativeStorage($"{GetType().Name}-{Guid.NewGuid()}"); }); } [Resolved] protected AudioManager Audio { get; private set; } [Resolved] protected MusicController MusicController { get; private set; } /// <summary> /// Creates the ruleset to be used for this test scene. /// </summary> /// <remarks> /// When testing against ruleset-specific components, this method must be overriden to their corresponding ruleset. /// </remarks> [CanBeNull] protected virtual Ruleset CreateRuleset() => null; protected virtual IBeatmap CreateBeatmap(RulesetInfo ruleset) => new TestBeatmap(ruleset); /// <summary> /// Returns a sample API Beatmap with BeatmapSet populated. /// </summary> /// <param name="ruleset">The ruleset to create the sample model using. osu! ruleset will be used if not specified.</param> protected APIBeatmap CreateAPIBeatmap(RulesetInfo ruleset = null) { var beatmapSet = CreateAPIBeatmapSet(ruleset ?? Ruleset.Value); // Avoid circular reference. var beatmap = beatmapSet.Beatmaps.First(); beatmapSet.Beatmaps = Array.Empty<APIBeatmap>(); // Populate the set as that's generally what we expect from the API. beatmap.BeatmapSet = beatmapSet; return beatmap; } /// <summary> /// Returns a sample API BeatmapSet with beatmaps populated. /// </summary> /// <param name="ruleset">The ruleset to create the sample model using. osu! ruleset will be used if not specified.</param> protected APIBeatmapSet CreateAPIBeatmapSet(RulesetInfo ruleset = null) { var beatmap = CreateBeatmap(ruleset ?? Ruleset.Value).BeatmapInfo; Debug.Assert(beatmap.BeatmapSet != null); return new APIBeatmapSet { OnlineID = ((IBeatmapSetInfo)beatmap.BeatmapSet).OnlineID, Status = BeatmapOnlineStatus.Ranked, Covers = new BeatmapSetOnlineCovers { Cover = "https://assets.ppy.sh/beatmaps/163112/covers/cover.jpg", Card = "https://assets.ppy.sh/beatmaps/163112/covers/card.jpg", List = "https://assets.ppy.sh/beatmaps/163112/covers/list.jpg" }, Title = beatmap.Metadata.Title, TitleUnicode = beatmap.Metadata.TitleUnicode, Artist = beatmap.Metadata.Artist, ArtistUnicode = beatmap.Metadata.ArtistUnicode, Author = new APIUser { Username = beatmap.Metadata.Author.Username, Id = beatmap.Metadata.Author.OnlineID }, Source = beatmap.Metadata.Source, Tags = beatmap.Metadata.Tags, Beatmaps = new[] { new APIBeatmap { OnlineID = ((IBeatmapInfo)beatmap).OnlineID, OnlineBeatmapSetID = ((IBeatmapSetInfo)beatmap.BeatmapSet).OnlineID, Status = beatmap.Status, Checksum = beatmap.MD5Hash, AuthorID = beatmap.Metadata.Author.OnlineID, RulesetID = beatmap.RulesetID, StarRating = beatmap.StarRating, DifficultyName = beatmap.DifficultyName, } } }; } protected WorkingBeatmap CreateWorkingBeatmap(RulesetInfo ruleset) => CreateWorkingBeatmap(CreateBeatmap(ruleset)); protected virtual WorkingBeatmap CreateWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null) => new ClockBackedTestWorkingBeatmap(beatmap, storyboard, Clock, Audio); [BackgroundDependencyLoader] private void load(RulesetStore rulesets) { Ruleset.Value = CreateRuleset()?.RulesetInfo ?? rulesets.AvailableRulesets.First(); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); rulesetDependencies?.Dispose(); if (MusicController?.TrackLoaded == true) MusicController.Stop(); if (contextFactory?.IsValueCreated == true) contextFactory.Value.ResetDatabase(); RecycleLocalStorage(true); } protected override ITestSceneTestRunner CreateRunner() => new OsuTestSceneTestRunner(); public class ClockBackedTestWorkingBeatmap : TestWorkingBeatmap { private readonly Track track; private readonly TrackVirtualStore store; /// <summary> /// Create an instance which creates a <see cref="TestBeatmap"/> for the provided ruleset when requested. /// </summary> /// <param name="ruleset">The target ruleset.</param> /// <param name="referenceClock">A clock which should be used instead of a stopwatch for virtual time progression.</param> /// <param name="audio">Audio manager. Required if a reference clock isn't provided.</param> public ClockBackedTestWorkingBeatmap(RulesetInfo ruleset, IFrameBasedClock referenceClock, AudioManager audio) : this(new TestBeatmap(ruleset), null, referenceClock, audio) { } /// <summary> /// Create an instance which provides the <see cref="IBeatmap"/> when requested. /// </summary> /// <param name="beatmap">The beatmap</param> /// <param name="storyboard">The storyboard.</param> /// <param name="referenceClock">An optional clock which should be used instead of a stopwatch for virtual time progression.</param> /// <param name="audio">Audio manager. Required if a reference clock isn't provided.</param> public ClockBackedTestWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard, IFrameBasedClock referenceClock, AudioManager audio) : base(beatmap, storyboard, audio) { double trackLength = 60000; if (beatmap.HitObjects.Count > 0) // add buffer after last hitobject to allow for final replay frames etc. trackLength = Math.Max(trackLength, beatmap.HitObjects.Max(h => h.GetEndTime()) + 2000); if (referenceClock != null) { store = new TrackVirtualStore(referenceClock); audio.AddItem(store); track = store.GetVirtual(trackLength); } else track = audio?.Tracks.GetVirtual(trackLength); } ~ClockBackedTestWorkingBeatmap() { // Remove the track store from the audio manager store?.Dispose(); } protected override Track GetBeatmapTrack() => track; public class TrackVirtualStore : AudioCollectionManager<Track>, ITrackStore { private readonly IFrameBasedClock referenceClock; public TrackVirtualStore(IFrameBasedClock referenceClock) { this.referenceClock = referenceClock; } public Track Get(string name) => throw new NotImplementedException(); public Task<Track> GetAsync(string name) => throw new NotImplementedException(); public Stream GetStream(string name) => throw new NotImplementedException(); public IEnumerable<string> GetAvailableResources() => throw new NotImplementedException(); public Track GetVirtual(double length = double.PositiveInfinity) { var track = new TrackVirtualManual(referenceClock) { Length = length }; AddItem(track); return track; } } /// <summary> /// A virtual track which tracks a reference clock. /// </summary> public class TrackVirtualManual : Track { private readonly IFrameBasedClock referenceClock; private bool running; public TrackVirtualManual(IFrameBasedClock referenceClock) { this.referenceClock = referenceClock; Length = double.PositiveInfinity; } public override bool Seek(double seek) { accumulated = Math.Clamp(seek, 0, Length); lastReferenceTime = null; return accumulated == seek; } public override void Start() { running = true; } public override void Reset() { Seek(0); base.Reset(); } public override void Stop() { if (running) { running = false; lastReferenceTime = null; } } public override bool IsRunning => running; private double? lastReferenceTime; private double accumulated; public override double CurrentTime => Math.Min(accumulated, Length); protected override void UpdateState() { base.UpdateState(); if (running) { double refTime = referenceClock.CurrentTime; double? lastRefTime = lastReferenceTime; if (lastRefTime != null) accumulated += (refTime - lastRefTime.Value) * Rate; lastReferenceTime = refTime; } if (CurrentTime >= Length) { Stop(); // `RaiseCompleted` is not called here to prevent transitioning to the next song. } } } } public class OsuTestSceneTestRunner : OsuGameBase, ITestSceneTestRunner { private TestSceneTestRunner.TestRunner runner; protected override void LoadAsyncComplete() { // this has to be run here rather than LoadComplete because // TestScene.cs is checking the IsLoaded state (on another thread) and expects // the runner to be loaded at that point. Add(runner = new TestSceneTestRunner.TestRunner()); } protected override void InitialiseFonts() { // skip fonts load as it's not required for testing purposes. } public void RunTestBlocking(TestScene test) => runner.RunTestBlocking(test); } } }
// Created by Paul Gonzalez Becerra using System; namespace GDToolkit.Storage { public class Properties { #region --- Field Variables --- // Variables private string[] keys; private object[] items; #endregion // Field Variables #region --- Constructors --- public Properties() { keys= new string[0]; items= new object[0]; } #endregion // Constructors #region --- Properties --- // Gets the size of the properties public int size { get { return keys.Length; } } // Gets and sets the items of the properties public object this[string key] { get { return get(key); } set { set(key, value); } } #endregion // Properties #region --- Methods --- // Clears all the properties public void clear() { keys= new string[0]; items= new object[0]; } // Adds the given key and item into the properties public bool add(string key, object item) { if(contains(key)) return false; // Variables string[] keyTemp= new string[size+1]; object[] temp= new object[size+1]; for(int i= 0; i< size; i++) { keyTemp[i]= keys[i]; temp[i]= items[i]; } keyTemp[size]= key; temp[size]= item; keys= keyTemp; items= temp; return true; } // Adds the given array of keys and items into the properties public bool addRange(string[] pmKeys, object[] pmItems) { if(pmKeys.Length== pmItems.Length) return false; // Variables string[] keyTemp= new string[size+pmKeys.Length]; object[] temp= new object[size+pmKeys.Length]; int k= 0; int missed= 0; for(int i= 0; i< size; i++) { keyTemp[i]= keys[i]; temp[i]= items[i]; } for(int h= size; h< temp.Length; h++) { if(contains(pmKeys[k])) { k++; missed++; continue; } keyTemp[h]= pmKeys[k]; temp[h]= pmItems[k++]; } if(missed>= pmKeys.Length) return false; keys= keyTemp; items= temp; return true; } // Removes the item from the list given the key public bool remove(string key) { return removeAt(getIndexOf(key)); } // Removes the item from the list given the index public bool removeAt(int index) { if(index< 0 || index>= size) return false; // Variables string[] keyTemp= new string[size-1]; object[] temp= new object[size-1]; int k= index; for(int i= 0; i< index; i++) { keyTemp[i]= keys[i]; temp[i]= items[i]; } if(k>= size) k= size-1; for(int h= index; h< temp.Length; h++) { keyTemp[h]= keys[k]; temp[h]= items[k++]; } keys= keyTemp; items= temp; return true; } // Finds if the given key is within the list public bool contains(string key) { for(int i= 0; i< size; i++) { if(keys[i]== key) return true; } return false; } // Gets the index of the given key public int getIndexOf(string key) { for(int i= 0; i< size; i++) { if(keys[i]== key) return i; } return -1; } // Gets the item given the key public object get(string key) { return (items[getIndexOf(key)]); } // Gets the item given the key public T get<T>(string key) { return (T)(get(key)); } public string getKey(int index) { return keys[index]; } // Sets the item with the given key with the given item public void set(string key, object item) { // Variables int index= getIndexOf(key); if(index== -1) return; items[index]= item; } #endregion // Methods } } // End of File
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Collections; using System.Collections.Specialized; using System.IO; using NUnit.TestUtilities; namespace NUnit.Framework.Constraints { [TestFixture] public class EmptyConstraintTest : ConstraintTestBase { [SetUp] public void SetUp() { TheConstraint = new EmptyConstraint(); ExpectedDescription = "<empty>"; StringRepresentation = "<empty>"; } static object[] SuccessData = new object[] { string.Empty, new object[0], new ArrayList(), new System.Collections.Generic.List<int>(), Guid.Empty, new SingleElementCollection<int>(), new NameValueCollection(), #if !NET35 && !NET40 System.Collections.Immutable.ImmutableArray<int>.Empty, #endif }; static object[] FailureData = new object[] { new TestCaseData("Hello", "\"Hello\"" ), new TestCaseData(new object[] { 1, 2, 3 }, "< 1, 2, 3 >" ), new TestCaseData(new Guid("12345678-1234-1234-1234-123456789012"), "12345678-1234-1234-1234-123456789012"), new TestCaseData(new SingleElementCollection<int>(1), "<1>"), new TestCaseData(new NameValueCollection { ["Hello"] = "World" }, "< \"Hello\" >"), #if !NET35 && !NET40 new TestCaseData(System.Collections.Immutable.ImmutableArray.Create(1), "< 1 >"), #endif }; [TestCase(null)] [TestCase(5)] public void InvalidDataThrowsArgumentException(object data) { Assert.Throws<ArgumentException>(() => TheConstraint.ApplyTo(data)); } public void InvalidDataThrowsArgumentException() { Assert.Throws<ArgumentException>(() => TheConstraint.ApplyTo(default(SingleElementCollection<int>))); Assert.Throws<ArgumentException>(() => TheConstraint.ApplyTo(new NotReallyACollection())); } [Test] public void NullStringGivesFailureResult() { string actual = null; var result = TheConstraint.ApplyTo(actual); Assert.That(result.Status, Is.EqualTo(ConstraintStatus.Failure)); } [Test] public void NullNullableGuidGivesFailureResult() { Guid? actual = null; var result = TheConstraint.ApplyTo(actual); Assert.That(result.Status, Is.EqualTo(ConstraintStatus.Failure)); } [Test] public void NullArgumentExceptionMessageContainsTypeName() { int? testInput = null; Assert.That(() => TheConstraint.ApplyTo(testInput), Throws.ArgumentException.With.Message.Contains("System.Int32")); } private class SingleElementCollection<T> { private readonly T _element; public int Count { get; private set; } public SingleElementCollection() { } public SingleElementCollection(T element) { _element = element; Count = 1; } public T Get() { if (Count == 0) { throw new InvalidOperationException("Collection is empty"); } Count = 0; return _element; } public override string ToString() { return Count == 0 ? "<empty>" : _element.ToString(); } } private class NotReallyACollection { #pragma warning disable CA1822 // Mark members as static public double Count => 0; #pragma warning restore CA1822 // Mark members as static } } [TestFixture] public class EmptyStringConstraintTest : StringConstraintTests { [SetUp] public void SetUp() { TheConstraint = new EmptyStringConstraint(); ExpectedDescription = "<empty>"; StringRepresentation = "<emptystring>"; } static object[] SuccessData = new object[] { string.Empty }; static object[] FailureData = new object[] { new TestCaseData( "Hello", "\"Hello\"" ), new TestCaseData( null, "null") }; } [TestFixture] public class EmptyDirectoryConstraintTest { [Test] public void EmptyDirectory() { using (var testDir = new TestDirectory()) { Assert.That(testDir.Directory, Is.Empty); } } [Test] public void NotEmptyDirectory_ContainsFile() { using (var testDir = new TestDirectory()) { File.Create(Path.Combine(testDir.Directory.FullName, "DUMMY.FILE")).Dispose(); Assert.That(testDir.Directory, Is.Not.Empty); } } [Test] public void NotEmptyDirectory_ContainsDirectory() { using (var testDir = new TestDirectory()) { Directory.CreateDirectory(Path.Combine(testDir.Directory.FullName, "DUMMY_DIR")); Assert.That(testDir.Directory, Is.Not.Empty); } } } [TestFixture] public class EmptyGuidConstraintTest { [Test] public void EmptyGuid() { Assert.That(Guid.Empty, Is.Empty); } [Test] public void EmptyNullableGuid() { Guid? empty = Guid.Empty; Assert.That(empty, Is.Empty); } [Test] public void NonEmptyGuid() { Guid nonEmpty = new Guid("10000000-0000-0000-0000-000000000000"); Assert.That(nonEmpty, Is.Not.Empty); } [Test] public void NonEmptyNullableGuid() { Guid? nonEmpty = new Guid("10000000-0000-0000-0000-000000000000"); Assert.That(nonEmpty, Is.Not.Empty); } [Test] public void NullNullableGuid() { Guid? nonEmpty = null; Assert.That(nonEmpty, Is.Not.Empty); } } }
// // Copyright (c) 2004-2016 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. // #if !SILVERLIGHT && !MONO namespace NLog.UnitTests.Targets.Wrappers { using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using System; using System.Collections.Generic; using System.DirectoryServices.AccountManagement; using System.Runtime.InteropServices; using System.Security.Principal; using Xunit; public class ImpersonatingTargetWrapperTests : NLogTestBase, IDisposable { private const string NLogTestUser = "NLogTestUser"; private const string NLogTestUserPassword = "BC@57acasd123"; private const string Localhost = "127.0.0.1"; public ImpersonatingTargetWrapperTests() { CreateUserIfNotPresent(); } [Fact] public void ImpersonatingWrapperTest() { var wrapped = new MyTarget() { ExpectedUser = Environment.MachineName + "\\" + NLogTestUser, }; var wrapper = new ImpersonatingTargetWrapper() { UserName = NLogTestUser, Password = NLogTestUserPassword, Domain = Environment.MachineName, WrappedTarget = wrapped, }; // wrapped.Initialize(null); wrapper.Initialize(null); var exceptions = new List<Exception>(); wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(1, exceptions.Count); wrapper.WriteAsyncLogEvents( LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(4, exceptions.Count); wrapper.Flush(exceptions.Add); Assert.Equal(5, exceptions.Count); foreach (var ex in exceptions) { Assert.Null(ex); } wrapper.Close(); } [Fact] public void RevertToSelfTest() { var wrapped = new MyTarget() { ExpectedUser = Environment.UserDomainName + "\\" + Environment.UserName, }; WindowsIdentity originalIdentity = WindowsIdentity.GetCurrent(); try { var id = this.CreateWindowsIdentity(NLogTestUser, Environment.MachineName, NLogTestUserPassword, SecurityLogOnType.Interactive, LogOnProviderType.Default, SecurityImpersonationLevel.Identification); id.Impersonate(); WindowsIdentity changedIdentity = WindowsIdentity.GetCurrent(); Assert.Contains(NLogTestUser.ToLowerInvariant(), changedIdentity.Name.ToLowerInvariant(), StringComparison.InvariantCulture); var wrapper = new ImpersonatingTargetWrapper() { WrappedTarget = wrapped, RevertToSelf = true, }; // wrapped.Initialize(null); wrapper.Initialize(null); var exceptions = new List<Exception>(); wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(1, exceptions.Count); wrapper.WriteAsyncLogEvents( LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(4, exceptions.Count); wrapper.Flush(exceptions.Add); Assert.Equal(5, exceptions.Count); foreach (var ex in exceptions) { Assert.Null(ex); } wrapper.Close(); } finally { // revert to self NativeMethods.RevertToSelf(); WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); Assert.Equal(originalIdentity.Name.ToLowerInvariant(), currentIdentity.Name.ToLowerInvariant()); } } [Fact] public void ImpersonatingWrapperNegativeTest() { var wrapped = new MyTarget() { ExpectedUser = NLogTestUser, }; LogManager.ThrowExceptions = true; var wrapper = new ImpersonatingTargetWrapper() { UserName = NLogTestUser, Password = Guid.NewGuid().ToString("N"), // wrong password Domain = Environment.MachineName, WrappedTarget = wrapped, }; Assert.Throws<COMException>(() => { wrapper.Initialize(null); }); wrapper.Close(); // will not fail because Initialize() failed } [Fact] public void ImpersonatingWrapperNegativeTest2() { var wrapped = new MyTarget() { ExpectedUser = NLogTestUser, }; LogManager.ThrowExceptions = true; var wrapper = new ImpersonatingTargetWrapper() { UserName = NLogTestUser, Password = NLogTestUserPassword, Domain = Environment.MachineName, ImpersonationLevel = (SecurityImpersonationLevel)1234, WrappedTarget = wrapped, }; Assert.Throws<COMException>(() => { wrapper.Initialize(null); }); wrapper.Close(); // will not fail because Initialize() failed } private WindowsIdentity CreateWindowsIdentity(string username, string domain, string password, SecurityLogOnType logonType, LogOnProviderType logonProviderType, SecurityImpersonationLevel impersonationLevel) { // initialize tokens var existingTokenHandle = IntPtr.Zero; var duplicateTokenHandle = IntPtr.Zero; if (!NativeMethods.LogonUser( username, domain, password, (int)logonType, (int)logonProviderType, out existingTokenHandle)) { throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } if (!NativeMethods.DuplicateToken(existingTokenHandle, (int)impersonationLevel, out duplicateTokenHandle)) { NativeMethods.CloseHandle(existingTokenHandle); throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } // create new identity using new primary token return new WindowsIdentity(duplicateTokenHandle); } private static class NativeMethods { // obtains user token [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken); // closes open handles returned by LogonUser [DllImport("kernel32.dll", CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(IntPtr handle); // creates duplicate token handle [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DuplicateToken(IntPtr existingTokenHandle, int impersonationLevel, out IntPtr duplicateTokenHandle); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool RevertToSelf(); } public class MyTarget : Target { public MyTarget() { this.Events = new List<LogEventInfo>(); } public MyTarget(string name) : this() { this.Name = name; } public List<LogEventInfo> Events { get; set; } public string ExpectedUser { get; set; } protected override void InitializeTarget() { base.InitializeTarget(); this.AssertExpectedUser(); } protected override void CloseTarget() { base.CloseTarget(); this.AssertExpectedUser(); } protected override void Write(LogEventInfo logEvent) { this.AssertExpectedUser(); this.Events.Add(logEvent); } protected override void Write(AsyncLogEventInfo[] logEvents) { this.AssertExpectedUser(); base.Write(logEvents); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.AssertExpectedUser(); base.FlushAsync(asyncContinuation); } private void AssertExpectedUser() { if (this.ExpectedUser != null) { var windowsIdentity = WindowsIdentity.GetCurrent(); Assert.True(windowsIdentity.IsAuthenticated); Assert.Equal(Environment.MachineName + "\\" + ExpectedUser, windowsIdentity.Name); } } } private void CreateUserIfNotPresent() { using (var context = new PrincipalContext(ContextType.Machine, Localhost)) { if (UserPrincipal.FindByIdentity(context, IdentityType.Name, NLogTestUser) != null) return; var user = new UserPrincipal(context); user.SetPassword(NLogTestUserPassword); user.Name = NLogTestUser; user.Save(); var group = GroupPrincipal.FindByIdentity(context, "Users"); group.Members.Add(user); group.Save(); } } public void Dispose() { DeleteUser(); } private void DeleteUser() { using (var context = new PrincipalContext(ContextType.Machine, Localhost)) using (var up = UserPrincipal.FindByIdentity(context, IdentityType.Name, NLogTestUser)) { if (up != null) up.Delete(); } } } } #endif
using Grpc.Core; using FluentAssertions; using MagicOnion.Client; using MagicOnion.Server; using MessagePack; using System; using System.Linq; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using Grpc.Net.Client; using Xunit; using Xunit.Abstractions; namespace MagicOnion.Server.Tests { [MessagePackObject] public class MyRequest { [Key(0)] public virtual int Id { get; set; } [Key(1)] public virtual string Data { get; set; } } [MessagePackObject] public struct MyStructRequest { [Key(0)] public int X; [Key(1)] public int Y; public MyStructRequest(int x, int y) { this.X = x; this.Y = y; } } [MessagePackObject] public struct MyStructResponse { [Key(0)] public int X; [Key(1)] public int Y; public MyStructResponse(int x, int y) { this.X = x; this.Y = y; } } [MessagePackObject] public class MyResponse { [Key(0)] public virtual int Id { get; set; } [Key(1)] public virtual string Data { get; set; } } public interface IArgumentPattern : IService<IArgumentPattern> { UnaryResult<MyResponse> Unary1(int x, int y, string z = "unknown"); UnaryResult<MyResponse> Unary2(MyRequest req); UnaryResult<MyResponse> Unary3(); UnaryResult<Nil> Unary4(); UnaryResult<MyStructResponse> Unary5(MyStructRequest req); Task<ServerStreamingResult<MyResponse>> ServerStreamingResult1(int x, int y, string z = "unknown"); Task<ServerStreamingResult<MyResponse>> ServerStreamingResult2(MyRequest req); Task<ServerStreamingResult<MyResponse>> ServerStreamingResult3(); Task<ServerStreamingResult<Nil>> ServerStreamingResult4(); Task<ServerStreamingResult<MyStructResponse>> ServerStreamingResult5(MyStructRequest req); } public class ArgumentPattern : ServiceBase<IArgumentPattern>, IArgumentPattern { public UnaryResult<MyResponse> Unary1(int x, int y, string z = "unknown") { return UnaryResult(new MyResponse { Id = x + y, Data = z }); } public UnaryResult<MyResponse> Unary2(MyRequest req) { return UnaryResult(new MyResponse { Id = req.Id, Data = req.Data }); } public UnaryResult<MyResponse> Unary3() { return UnaryResult(new MyResponse { Id = -1, Data = "NoArg" }); } public UnaryResult<Nil> Unary4() { return UnaryResult(Nil.Default); } public UnaryResult<MyStructResponse> Unary5(MyStructRequest req) { return UnaryResult(new MyStructResponse { X = req.X, Y = req.Y }); } public async Task<ServerStreamingResult<MyResponse>> ServerStreamingResult1(int x, int y, string z = "unknown") { var stream = GetServerStreamingContext<MyResponse>(); await stream.WriteAsync(new MyResponse { Id = x + y, Data = z }); return stream.Result(); } public async Task<ServerStreamingResult<MyResponse>> ServerStreamingResult2(MyRequest req) { var stream = GetServerStreamingContext<MyResponse>(); await stream.WriteAsync(new MyResponse { Id = req.Id, Data = req.Data }); return stream.Result(); } public async Task<ServerStreamingResult<MyResponse>> ServerStreamingResult3() { var stream = GetServerStreamingContext<MyResponse>(); await stream.WriteAsync(new MyResponse { Id = -1, Data = "empty" }); return stream.Result(); } public async Task<ServerStreamingResult<Nil>> ServerStreamingResult4() { var stream = GetServerStreamingContext<Nil>(); await stream.WriteAsync(Nil.Default); return stream.Result(); } public async Task<ServerStreamingResult<MyStructResponse>> ServerStreamingResult5(MyStructRequest req) { var stream = GetServerStreamingContext<MyStructResponse>(); await stream.WriteAsync(new MyStructResponse { X = req.X, Y = req.Y }); return stream.Result(); } } public class ArgumentPatternTest : IClassFixture<ServerFixture<ArgumentPattern>> { ITestOutputHelper logger; GrpcChannel channel; public ArgumentPatternTest(ITestOutputHelper logger, ServerFixture<ArgumentPattern> server) { this.logger = logger; this.channel = server.DefaultChannel; } [Fact] public async Task Unary1() { { var client = MagicOnionClient.Create<IArgumentPattern>(channel); var result = await client.Unary1(10, 20, "hogehoge"); result.Id.Should().Be(30); result.Data.Should().Be("hogehoge"); } { var client = new ArgumentPatternManualClient(channel); var result = await client.Unary1(10, 20, "__omit_last_argument__"); result.Id.Should().Be(30); result.Data.Should().Be("unknown"); } } [Fact] public async Task Unary2() { var client = MagicOnionClient.Create<IArgumentPattern>(channel); var result = await client.Unary2(new MyRequest { Id = 30, Data = "huga" }); result.Id.Should().Be(30); result.Data.Should().Be("huga"); } [Fact] public async Task Unary3() { var client = MagicOnionClient.Create<IArgumentPattern>(channel); var result = await client.Unary3(); result.Id.Should().Be(-1); result.Data.Should().Be("NoArg"); } [Fact] public async Task Unary4() { var client = MagicOnionClient.Create<IArgumentPattern>(channel); var result = await client.Unary4(); result.Should().Be(Nil.Default); } [Fact] public async Task Unary5() { var client = MagicOnionClient.Create<IArgumentPattern>(channel); var result = await client.Unary5(new MyStructRequest(999, 9999)); result.X.Should().Be(999); result.Y.Should().Be(9999); } async Task<T> First<T>(IAsyncStreamReader<T> reader) { await reader.MoveNext(CancellationToken.None); return reader.Current; } [Fact] public async Task ServerStreaming() { var client = MagicOnionClient.Create<IArgumentPattern>(channel); { var callResult = await client.ServerStreamingResult1(10, 100, "aaa"); var result = await First(callResult.ResponseStream); result.Id.Should().Be(110); result.Data.Should().Be("aaa"); } { var callResult = await client.ServerStreamingResult2(new MyRequest { Id = 999, Data = "zzz" }); var result = await First(callResult.ResponseStream); result.Id.Should().Be(999); result.Data.Should().Be("zzz"); } { var callResult = await client.ServerStreamingResult3(); var result = await First(callResult.ResponseStream); result.Id.Should().Be(-1); result.Data.Should().Be("empty"); } { var callResult = await client.ServerStreamingResult4(); var result = await First(callResult.ResponseStream); result.Should().Be(Nil.Default); } { var callResult = await client.ServerStreamingResult5(new MyStructRequest { X = 9, Y = 100 }); var result = await First(callResult.ResponseStream); result.X.Should().Be(9); result.Y.Should().Be(100); } } [Ignore] // client is not service. class ArgumentPatternManualClient : IArgumentPattern { readonly CallInvoker invoker; public ArgumentPatternManualClient(GrpcChannel channel) { this.invoker = channel.CreateCallInvoker(); } public Task<ServerStreamingResult<MyResponse>> ServerStreamingResult1(int x, int y, string z = "unknown") { throw new NotImplementedException(); } public Task<ServerStreamingResult<MyResponse>> ServerStreamingResult2(MyRequest req) { throw new NotImplementedException(); } public Task<ServerStreamingResult<MyResponse>> ServerStreamingResult3() { throw new NotImplementedException(); } public Task<ServerStreamingResult<Nil>> ServerStreamingResult4() { throw new NotImplementedException(); } public Task<ServerStreamingResult<MyStructResponse>> ServerStreamingResult5(MyStructRequest req) { throw new NotImplementedException(); } public UnaryResult<MyResponse> Unary1(int x, int y, string z = "unknown") { var tuple = new DynamicArgumentTuple<int, int>(x, y); var method = new Method<byte[], byte[]>(MethodType.Unary, "IArgumentPattern", "Unary1", MagicOnionMarshallers.ThroughMarshaller, MagicOnionMarshallers.ThroughMarshaller); var request = MessagePackSerializer.Serialize(tuple); var callResult = invoker.AsyncUnaryCall(method, null, default(CallOptions), request); var response = new ResponseContext<MyResponse>(callResult, MessagePackSerializer.DefaultOptions); return new UnaryResult<MyResponse>(Task.FromResult<IResponseContext<MyResponse>>(response)); } public UnaryResult<MyResponse> Unary2(MyRequest req) { throw new NotImplementedException(); } public UnaryResult<MyResponse> Unary3() { throw new NotImplementedException(); } public UnaryResult<Nil> Unary4() { throw new NotImplementedException(); } public UnaryResult<MyStructResponse> Unary5(MyStructRequest req) { throw new NotImplementedException(); } public IArgumentPattern WithCancellationToken(CancellationToken cancellationToken) { throw new NotImplementedException(); } public IArgumentPattern WithDeadline(DateTime deadline) { throw new NotImplementedException(); } public IArgumentPattern WithHeaders(Metadata headers) { throw new NotImplementedException(); } public IArgumentPattern WithHost(string host) { throw new NotImplementedException(); } public IArgumentPattern WithOptions(CallOptions option) { throw new NotImplementedException(); } } } }
using System; using System.Threading.Tasks; #if __UNIFIED__ using CoreGraphics; using UIKit; #else using MonoTouch.UIKit; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace AdvancedColorPicker { /// <summary> /// The view controller that represents a color picker. /// </summary> public class ColorPickerViewController : UIViewController { private ColorPickerView colorPicker; /// <summary> /// Initializes a new instance of the <see cref="ColorPickerViewController"/> class. /// </summary> public ColorPickerViewController() { Initialize(UIColor.FromHSB(0.5984375f, 0.5f, 0.7482993f)); } /// <summary> /// Initializes a new instance of the <see cref="ColorPickerViewController"/> class /// with the specified initial selected hue, saturation and brightness. /// </summary> /// <param name="hue">The initial selected hue.</param> /// <param name="saturation">The initial selected saturation.</param> /// <param name="brightness">The initial selected brightness.</param> public ColorPickerViewController(nfloat hue, nfloat saturation, nfloat brightness) { Initialize(UIColor.FromHSB(hue, saturation, brightness)); } /// <summary> /// Initializes a new instance of the <see cref="ColorPickerViewController"/> class /// with the specified initial selected color. /// </summary> /// <param name="color">The initial selected color.</param> public ColorPickerViewController(UIColor color) { Initialize(color); } /// <summary> /// Initializes this instance with the specified color. /// </summary> /// <param name="color">The initial selected color.</param> protected void Initialize(UIColor color) { colorPicker = new ColorPickerView(color); } /// <summary> /// Gets or sets the selected color. /// </summary> /// <value>The selected color.</value> public UIColor SelectedColor { get { return colorPicker.SelectedColor; } set { colorPicker.SelectedColor = value; } } /// <summary> /// Occurs when the a color is selected. /// </summary> public event EventHandler<ColorPickedEventArgs> ColorPicked { add { colorPicker.ColorPicked += value; } remove { colorPicker.ColorPicked -= value; } } /// <summary> /// Initializes the <see cref="UIViewController.View"/> property. /// </summary> public override void LoadView() { View = colorPicker; } /// <summary> /// The orientations supported by this <see cref="UIViewController"/>. /// </summary> /// <returns>A <see cref="UIInterfaceOrientationMask"/> of the orientations supported by this <see cref="UIViewController"/>.</returns> public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations() { return UIInterfaceOrientationMask.All; } /// <summary> /// If the <see cref="UIViewController"/> supports rotation to the specified <see cref="UIInterfaceOrientation"/>. /// </summary> /// <param name="toInterfaceOrientation">The final <see cref="UIInterfaceOrientation"/>.</param> /// <returns><c>true</c> if the <see cref="UIViewController"/> supports rotation to the specified <see cref="UIInterfaceOrientation"/>, <c>false</c> otherwise.</returns> public override bool ShouldAutorotateToInterfaceOrientation(UIInterfaceOrientation toInterfaceOrientation) { return true; } /// <summary> /// Turns auto-rotation on or off. /// </summary> /// <returns><c>true</c> if the MonoTouch.UIKit.UIViewController should auto-rotate, <c>false</c> otherwise.</returns> public override bool ShouldAutorotate() { return true; } /// <summary> /// Presents a new color picker. /// </summary> /// <param name="parent">The parent <see cref="UIViewController"/>.</param> /// <param name="title">The picker title.</param> /// <param name="initialColor">The initial selected color.</param> /// <param name="done">The method invoked when the picker closes.</param> public static void Present(UIViewController parent, string title, UIColor initialColor, Action<UIColor> done) { Present(parent, title, initialColor, done, null); } /// <summary> /// Presents a new color picker. /// </summary> /// <param name="parent">The parent <see cref="UIViewController"/>.</param> /// <param name="title">The picker title.</param> /// <param name="initialColor">The initial selected color.</param> /// <param name="done">The method invoked when the picker closes.</param> /// <param name="colorPicked">The method invoked as colors are picked.</param> public static void Present(UIViewController parent, string title, UIColor initialColor, Action<UIColor> done, Action<UIColor> colorPicked) { if (parent == null) { throw new ArgumentNullException("parent"); } var picker = new ColorPickerViewController { Title = title, SelectedColor = initialColor }; picker.ColorPicked += (_, args) => { if (colorPicked != null) { colorPicked(args.SelectedColor); } }; var pickerNav = new UINavigationController(picker); pickerNav.ModalPresentationStyle = UIModalPresentationStyle.FormSheet; pickerNav.NavigationBar.Translucent = false; var doneBtn = new UIBarButtonItem(UIBarButtonSystemItem.Done); picker.NavigationItem.RightBarButtonItem = doneBtn; doneBtn.Clicked += delegate { if (done != null) { done(picker.SelectedColor); } // hide the picker parent.DismissViewController(true, null); }; // show the picker parent.PresentViewController(pickerNav, true, null); } /// <summary> /// Presents a new color picker, and waits for the picker to close. /// </summary> /// <param name="parent">The parent <see cref="UIViewController"/>.</param> /// <param name="title">The picker title.</param> /// <param name="initialColor">The initial selected color.</param> public static Task<UIColor> PresentAsync(UIViewController parent, string title, UIColor initialColor) { return PresentAsync(parent, title, initialColor, null); } /// <summary> /// Presents a new color picker, and waits for the picker to close. /// </summary> /// <param name="parent">The parent <see cref="UIViewController"/>.</param> /// <param name="title">The picker title.</param> /// <param name="initialColor">The initial selected color.</param> /// <param name="colorPicked">The method invoked as colors are picked.</param> public static Task<UIColor> PresentAsync(UIViewController parent, string title, UIColor initialColor, Action<UIColor> colorPicked) { var tcs = new TaskCompletionSource<UIColor>(); Present(parent, title, initialColor, color => { tcs.SetResult(color); }, colorPicked); return tcs.Task; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using WpfMath.Boxes; using WpfMath.Exceptions; namespace WpfMath.Controls { /// <summary> /// Interaction logic for FormulaControl.xaml /// </summary> public partial class FormulaControl : UserControl { private static TexFormulaParser formulaParser = new TexFormulaParser(); private TexFormula? texFormula; public string Formula { get { return (string)GetValue(FormulaProperty); } set { SetValue(FormulaProperty, value); } } public double Scale { get { return (double)GetValue(ScaleProperty); } set { SetValue(ScaleProperty, value); } } public string SystemTextFontName { get => (string)GetValue(SystemTextFontNameProperty); set => SetValue(SystemTextFontNameProperty, value); } public bool HasError { get { return (bool)GetValue(HasErrorProperty); } private set { SetValue(HasErrorProperty, value); } } public ObservableCollection<Exception> Errors { get { return (ObservableCollection<Exception>)GetValue(ErrorsProperty); } private set { SetValue(ErrorsProperty, value); } } public ControlTemplate ErrorTemplate { get { return (ControlTemplate)GetValue(ErrorTemplateProperty); } set { SetValue(ErrorTemplateProperty, value); } } public int SelectionStart { get { return (int)GetValue(SelectionStartProperty); } set { SetValue(SelectionStartProperty, value); } } public int SelectionLength { get { return (int)GetValue(SelectionLengthProperty); } set { SetValue(SelectionLengthProperty, value); } } public Brush? SelectionBrush { get => (Brush)GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } public static readonly DependencyProperty FormulaProperty = DependencyProperty.Register( nameof(Formula), typeof(string), typeof(FormulaControl), new PropertyMetadata("", OnRenderSettingsChanged, CoerceFormula)); public static readonly DependencyProperty ScaleProperty = DependencyProperty.Register( nameof(Scale), typeof(double), typeof(FormulaControl), new PropertyMetadata(20d, OnRenderSettingsChanged, CoerceScaleValue)); public static readonly DependencyProperty SystemTextFontNameProperty = DependencyProperty.Register( nameof(SystemTextFontName), typeof(string), typeof(FormulaControl), new PropertyMetadata("Arial", OnRenderSettingsChanged)); public static readonly DependencyProperty HasErrorProperty = DependencyProperty.Register( nameof(HasError), typeof(bool), typeof(FormulaControl), new PropertyMetadata(false)); public static readonly DependencyProperty ErrorsProperty = DependencyProperty.Register( nameof(Errors), typeof(ObservableCollection<Exception>), typeof(FormulaControl), new PropertyMetadata(new ObservableCollection<Exception>())); public static readonly DependencyProperty ErrorTemplateProperty = DependencyProperty.Register( nameof(ErrorTemplate), typeof(ControlTemplate), typeof(FormulaControl), new PropertyMetadata(new ControlTemplate())); public static readonly DependencyProperty SelectionStartProperty = DependencyProperty.Register( nameof(SelectionStart), typeof(int), typeof(FormulaControl), new PropertyMetadata(0, OnRenderSettingsChanged)); public static readonly DependencyProperty SelectionLengthProperty = DependencyProperty.Register( nameof(SelectionLength), typeof(int), typeof(FormulaControl), new PropertyMetadata(0, OnRenderSettingsChanged)); public static readonly DependencyProperty SelectionBrushProperty = DependencyProperty.Register( nameof(SelectionBrush), typeof(Brush), typeof(FormulaControl), new PropertyMetadata(null, OnRenderSettingsChanged)); static FormulaControl() { // Call OnRenderSettingsChanged on Foreground property change. ForegroundProperty.OverrideMetadata( typeof(FormulaControl), new FrameworkPropertyMetadata( SystemColors.ControlTextBrush, FrameworkPropertyMetadataOptions.Inherits, OnRenderSettingsChanged)); } public FormulaControl() { InitializeComponent(); } private void Render() { // Create formula object from input text. if (texFormula == null) { formulaContainerElement.Visual = null; return; } // Render formula to visual. var visual = new DrawingVisual(); // Pass transparent background, since the control background will be effectively used anyway. var renderer = texFormula.GetRenderer(TexStyle.Display, Scale, SystemTextFontName, Brushes.Transparent, Foreground); var formulaSource = texFormula.Source; if (formulaSource != null) { var selectionBrush = SelectionBrush; if (selectionBrush != null) { var allBoxes = new List<Box>(renderer.Box.Children); var selectionStart = SelectionStart; var selectionEnd = selectionStart + SelectionLength; for (var idx = 0; idx < allBoxes.Count; idx++) { var box = allBoxes[idx]; allBoxes.AddRange(box.Children); var source = box.Source; if (source == null || !source.SourceName.Equals(formulaSource.SourceName, StringComparison.Ordinal) || !source.Source.Equals(formulaSource.Source, StringComparison.Ordinal)) continue; if (selectionStart < source.Start + source.Length && source.Start < selectionEnd && box is CharBox) { box.Background = selectionBrush; } } } } using (var drawingContext = visual.RenderOpen()) { renderer.Render(drawingContext, 0, 0); } formulaContainerElement.Visual = visual; } private static object CoerceFormula(DependencyObject d, object baseValue) { var control = (FormulaControl)d; var formula = (string)baseValue; try { control.HasError = false; control.Errors.Clear(); control.texFormula = formulaParser.Parse(formula); return baseValue; } catch (TexException e) { control.SetError(e); return ""; } } private static object CoerceScaleValue(DependencyObject d, object baseValue) { var val = (double)baseValue; return val < 1d ? 1d : val; } private static void OnRenderSettingsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = (FormulaControl)d; try { control.Render(); } catch (TexException exception) { control.SetError(exception); } } private void SetError(TexException exception) { Errors.Add(exception); HasError = true; texFormula = null; } } }
using NUnit.Framework; using System; using Microsoft.Xna.Framework; using Vector2Extensions; namespace Vector2Extensions.Tests { [TestFixture()] public class Test { [Test()] public void testToString() { Vector2 test = new Vector2(1.1f, 2.2f); string strTest = test.StringFromVector(); Vector2 test1 = strTest.ToVector2(); Assert.AreEqual(1.1f, test1.X); Assert.AreEqual(2.2f, test1.Y); } [Test()] public void VectZero() { Vector2 test = Vector2.Zero; string strTest = test.StringFromVector(); Vector2 test1 = strTest.ToVector2(); Assert.AreEqual(0.0f, test1.X); Assert.AreEqual(0.0f, test1.Y); } [Test()] public void NullString() { string strTest = ""; Vector2 test1 = strTest.ToVector2(); Assert.AreEqual(0.0f, test1.X); Assert.AreEqual(0.0f, test1.Y); } [Test()] public void NumAndNaNString() { Vector2 test = new Vector2(1.5f, float.NaN); string strTest = test.StringFromVector(); Vector2 test1 = strTest.ToVector2(); Assert.AreEqual(1.5f, test1.X); Assert.AreEqual(float.NaN, test1.Y); } [Test()] public void NaNString() { Vector2 test = new Vector2(float.NaN, float.NaN); string strTest = test.StringFromVector(); Vector2 test1 = strTest.ToVector2(); Assert.AreEqual(float.NaN, test1.X); Assert.AreEqual(float.NaN, test1.Y); } [Test()] public void BullshitString() { string strTest = "buttnuts"; Vector2 test1 = Vector2.Zero; try { test1 = strTest.ToVector2(); } catch { } Assert.AreEqual(0.0f, test1.X); Assert.AreEqual(0.0f, test1.Y); } [Test()] public void TruncateTest() { Vector2 vec = new Vector2(100.0f, 100.0f); vec = vec.Truncate(1.0f); Assert.AreEqual(1.0f, Math.Round(vec.Length(), 4)); } [Test()] public void TruncateTest2() { Vector2 vec = new Vector2(100.0f, 100.0f); vec = vec.Truncate(2.0f); Assert.AreEqual(2.0f, Math.Round(vec.Length(), 4)); } [Test()] public void Angle0() { Vector2 vec = new Vector2(1.0f, 0.0f); Assert.AreEqual(0.0f, Math.Round(vec.Angle(), 4)); } [Test()] public void Angle90() { Vector2 vec = new Vector2(0.0f, 1.0f); float desiredAngle = MathHelper.ToRadians(90.0f); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(desiredAngle, (float)Math.Round(vec.Angle(), 4)); } [Test()] public void AngleMinus45() { Vector2 vec = new Vector2(1.0f, -1.0f); float desiredAngle = MathHelper.ToRadians(-45.0f); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(desiredAngle, (float)Math.Round(vec.Angle(), 4)); } [Test()] public void AngleMinus45_1() { Vector2 vec = new Vector2(100.0f, -100.0f); float desiredAngle = MathHelper.ToRadians(-45.0f); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(desiredAngle, (float)Math.Round(vec.Angle(), 4)); } [Test()] public void Angle180() { Vector2 vec = new Vector2(-1.0f, 0.0f); float desiredAngle = MathHelper.ToRadians(180.0f); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(desiredAngle, (float)Math.Round(vec.Angle(), 4)); } [Test()] public void Angle180_1() { Vector2 vec = new Vector2(-100.0f, 0.0f); float desiredAngle = vec.Angle(); desiredAngle = MathHelper.ToDegrees(desiredAngle); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(180.0f, desiredAngle); } [Test()] public void AngleBetween0() { Vector2 vec1 = new Vector2(1.0f, 0.0f); Vector2 vec2 = new Vector2(1.0f, 0.0f); Assert.AreEqual(0.0f, (float)Math.Round(vec1.AngleBetweenVectors(vec2), 4)); } [Test()] public void AngleBetween90() { Vector2 vec1 = new Vector2(1.0f, 0.0f); Vector2 vec2 = new Vector2(0.0f, 1.0f); float desiredAngle = vec1.AngleBetweenVectors(vec2); desiredAngle = MathHelper.ToDegrees(desiredAngle); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(90.0f, desiredAngle); } [Test()] public void AngleBetween90_1() { Vector2 vec1 = new Vector2(1.0f, 0.0f); Vector2 vec2 = new Vector2(0.0f, 1.0f); float desiredAngle = vec2.AngleBetweenVectors(vec1); desiredAngle = MathHelper.ToDegrees(desiredAngle); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(-90.0f, desiredAngle); } [Test()] public void AngleBetween90_2() { Vector2 vec1 = new Vector2(0.0f, -1.0f); Vector2 vec2 = new Vector2(1.0f, 0.0f); float desiredAngle = vec2.AngleBetweenVectors(vec1); desiredAngle = MathHelper.ToDegrees(desiredAngle); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(-90.0f, desiredAngle); } [Test()] public void AngleBetweenMinus90() { Vector2 vec1 = new Vector2(1.0f, 0.0f); Vector2 vec2 = new Vector2(0.0f, -1.0f); float desiredAngle = vec1.AngleBetweenVectors(vec2); desiredAngle = MathHelper.ToDegrees(desiredAngle); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(-90.0f, desiredAngle); } [Test()] public void AngleBetweenMinus90_1() { Vector2 vec1 = new Vector2(1.0f, 0.0f); Vector2 vec2 = new Vector2(0.0f, -1.0f); float desiredAngle = vec2.AngleBetweenVectors(vec1); desiredAngle = MathHelper.ToDegrees(desiredAngle); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(90.0f, desiredAngle); } [Test()] public void AngleBetween180() { Vector2 vec1 = new Vector2(1.0f, 0.0f); Vector2 vec2 = new Vector2(-1.0f, 0.0f); float desiredAngle = vec1.AngleBetweenVectors(vec2); desiredAngle = MathHelper.ToDegrees(desiredAngle); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(180.0f, desiredAngle); } [Test()] public void AngleBetween180_1() { Vector2 vec1 = new Vector2(1.0f, 0.0f); Vector2 vec2 = new Vector2(-1.0f, 0.0f); float desiredAngle = vec2.AngleBetweenVectors(vec1); desiredAngle = MathHelper.ToDegrees(desiredAngle); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(-180.0f, desiredAngle); } [Test()] public void AngleBetweenMinus180() { Vector2 vec1 = new Vector2(-1.0f, 0.0f); Vector2 vec2 = new Vector2(1.0f, 0.0f); float desiredAngle = vec1.AngleBetweenVectors(vec2); desiredAngle = MathHelper.ToDegrees(desiredAngle); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(-180.0f, desiredAngle); } [Test()] public void AngleBetweenMinus180_1() { Vector2 vec1 = new Vector2(-1.0f, 0.0f); Vector2 vec2 = new Vector2(1.0f, 0.0f); float desiredAngle = vec2.AngleBetweenVectors(vec1); desiredAngle = MathHelper.ToDegrees(desiredAngle); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(180.0f, desiredAngle); } [Test()] public void AngleBetween45() { Vector2 vec1 = new Vector2(1.0f, 0.0f); Vector2 vec2 = new Vector2(1.0f, 1.0f); float desiredAngle = vec1.AngleBetweenVectors(vec2); desiredAngle = MathHelper.ToDegrees(desiredAngle); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(45.0f, desiredAngle); } [Test()] public void AngleBetween45_1() { Vector2 vec1 = new Vector2(1.0f, 0.0f); Vector2 vec2 = new Vector2(1.0f, 1.0f); float desiredAngle = vec2.AngleBetweenVectors(vec1); desiredAngle = MathHelper.ToDegrees(desiredAngle); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(-45.0f, desiredAngle); } [Test()] public void AngleBetween45_2() { Vector2 vec1 = new Vector2(1.0f, 0.0f); Vector2 vec2 = new Vector2(100.0f, 100.0f); float desiredAngle = vec2.AngleBetweenVectors(vec1); desiredAngle = MathHelper.ToDegrees(desiredAngle); desiredAngle = (float)Math.Round(desiredAngle, 4); Assert.AreEqual(-45.0f, desiredAngle); } [Test] public void FromAngle() { float fTest = 0.0f; Vector2 test = fTest.ToVector2(); float desiredX = 1.0f; float desiredY = 0.0f; Assert.AreEqual(desiredX, (float)Math.Round(test.X, 4)); Assert.AreEqual(desiredY, (float)Math.Round(test.Y, 4)); } [Test] public void FromAngle_2() { float fTest = MathHelper.ToRadians(90.0f); Vector2 test = fTest.ToVector2(); float desiredX = 0.0f; float desiredY = 1.0f; Assert.AreEqual(desiredX, (float)Math.Round(test.X, 4)); Assert.AreEqual(desiredY, (float)Math.Round(test.Y, 4)); } [Test] public void FromAngle_3() { float fTest = MathHelper.ToRadians(180.0f); Vector2 test = fTest.ToVector2(); float desiredX = -1.0f; float desiredY = 0.0f; Assert.AreEqual(desiredX, (float)Math.Round(test.X, 4)); Assert.AreEqual(desiredY, (float)Math.Round(test.Y, 4)); } } }
using Lucene.Net.Support; using System.Collections; using System.Collections.Generic; /* * dk.brics.automaton * * Copyright (c) 2001-2009 Anders Moeller * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * this SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 Lucene.Net.Util.Automaton { /// <summary> /// Operations for minimizing automata. /// <para/> /// @lucene.experimental /// </summary> public static class MinimizationOperations // LUCENENET specific - made static since all members are static { /// <summary> /// Minimizes (and determinizes if not already deterministic) the given /// automaton. /// </summary> /// <seealso cref="Automaton.SetMinimization(int)"/> public static void Minimize(Automaton a) { if (!a.IsSingleton) { MinimizeHopcroft(a); } // recompute hash code //a.hash_code = 1a.getNumberOfStates() * 3 + a.getNumberOfTransitions() * 2; //if (a.hash_code == 0) a.hash_code = 1; } /// <summary> /// Minimizes the given automaton using Hopcroft's algorithm. /// </summary> public static void MinimizeHopcroft(Automaton a) { a.Determinize(); if (a.initial.numTransitions == 1) { Transition t = a.initial.TransitionsArray[0]; if (t.to == a.initial && t.min == Character.MIN_CODE_POINT && t.max == Character.MAX_CODE_POINT) { return; } } a.Totalize(); // initialize data structures int[] sigma = a.GetStartPoints(); State[] states = a.GetNumberedStates(); int sigmaLen = sigma.Length, statesLen = states.Length; List<State>[,] reverse = new List<State>[statesLen, sigmaLen]; ISet<State>[] partition = new EquatableSet<State>[statesLen]; List<State>[] splitblock = new List<State>[statesLen]; int[] block = new int[statesLen]; StateList[,] active = new StateList[statesLen, sigmaLen]; StateListNode[,] active2 = new StateListNode[statesLen, sigmaLen]; LinkedList<Int32Pair> pending = new LinkedList<Int32Pair>(); OpenBitSet pending2 = new OpenBitSet(sigmaLen * statesLen); OpenBitSet split = new OpenBitSet(statesLen), refine = new OpenBitSet(statesLen), refine2 = new OpenBitSet(statesLen); for (int q = 0; q < statesLen; q++) { splitblock[q] = new List<State>(); partition[q] = new EquatableSet<State>(); for (int x = 0; x < sigmaLen; x++) { active[q, x] = new StateList(); } } // find initial partition and reverse edges for (int q = 0; q < statesLen; q++) { State qq = states[q]; int j = qq.accept ? 0 : 1; partition[j].Add(qq); block[q] = j; for (int x = 0; x < sigmaLen; x++) { //List<State>[] r = reverse[qq.Step(sigma[x]).number]; var r = qq.Step(sigma[x]).number; if (reverse[r, x] == null) { reverse[r, x] = new List<State>(); } reverse[r, x].Add(qq); } } // initialize active sets for (int j = 0; j <= 1; j++) { for (int x = 0; x < sigmaLen; x++) { foreach (State qq in partition[j]) { if (reverse[qq.number, x] != null) { active2[qq.number, x] = active[j, x].Add(qq); } } } } // initialize pending for (int x = 0; x < sigmaLen; x++) { int j = (active[0, x].Count <= active[1, x].Count) ? 0 : 1; pending.AddLast(new Int32Pair(j, x)); pending2.Set(x * statesLen + j); } // process pending until fixed point int k = 2; while (pending.Count > 0) { Int32Pair ip = pending.First.Value; pending.Remove(ip); int p = ip.N1; int x = ip.N2; pending2.Clear(x * statesLen + p); // find states that need to be split off their blocks for (StateListNode m = active[p, x].First; m != null; m = m.Next) { List<State> r = reverse[m.Q.number, x]; if (r != null) { foreach (State s in r) { int i = s.number; if (!split.Get(i)) { split.Set(i); int j = block[i]; splitblock[j].Add(s); if (!refine2.Get(j)) { refine2.Set(j); refine.Set(j); } } } } } // refine blocks for (int j = refine.NextSetBit(0); j >= 0; j = refine.NextSetBit(j + 1)) { List<State> sb = splitblock[j]; if (sb.Count < partition[j].Count) { ISet<State> b1 = partition[j]; ISet<State> b2 = partition[k]; foreach (State s in sb) { b1.Remove(s); b2.Add(s); block[s.number] = k; for (int c = 0; c < sigmaLen; c++) { StateListNode sn = active2[s.number, c]; if (sn != null && sn.Sl == active[j, c]) { sn.Remove(); active2[s.number, c] = active[k, c].Add(s); } } } // update pending for (int c = 0; c < sigmaLen; c++) { int aj = active[j, c].Count, ak = active[k, c].Count, ofs = c * statesLen; if (!pending2.Get(ofs + j) && 0 < aj && aj <= ak) { pending2.Set(ofs + j); pending.AddLast(new Int32Pair(j, c)); } else { pending2.Set(ofs + k); pending.AddLast(new Int32Pair(k, c)); } } k++; } refine2.Clear(j); foreach (State s in sb) { split.Clear(s.number); } sb.Clear(); } refine.Clear(0, refine.Length - 1); } // make a new state for each equivalence class, set initial state State[] newstates = new State[k]; for (int n = 0; n < newstates.Length; n++) { State s = new State(); newstates[n] = s; foreach (State q in partition[n]) { if (q == a.initial) { a.initial = s; } s.accept = q.accept; s.number = q.number; // select representative q.number = n; } } // build transitions and set acceptance for (int n = 0; n < newstates.Length; n++) { State s = newstates[n]; s.accept = states[s.number].accept; foreach (Transition t in states[s.number].GetTransitions()) { s.AddTransition(new Transition(t.min, t.max, newstates[t.to.number])); } } a.ClearNumberedStates(); a.RemoveDeadTransitions(); } /// <summary> /// NOTE: This was IntPair in Lucene /// </summary> internal sealed class Int32Pair { internal int N1 { get; private set; } internal int N2 { get; private set; } internal Int32Pair(int n1, int n2) { this.N1 = n1; this.N2 = n2; } } internal sealed class StateList { internal int Count { get; set; } // LUCENENET NOTE: This was size() in Lucene. internal StateListNode First { get; set; } internal StateListNode Last { get; set; } internal StateListNode Add(State q) { return new StateListNode(q, this); } } internal sealed class StateListNode { internal State Q { get; private set; } internal StateListNode Next { get; set; } internal StateListNode Prev { get; set; } internal StateList Sl { get; private set; } internal StateListNode(State q, StateList sl) { this.Q = q; this.Sl = sl; if (sl.Count++ == 0) { sl.First = sl.Last = this; } else { sl.Last.Next = this; Prev = sl.Last; sl.Last = this; } } internal void Remove() { Sl.Count--; if (Sl.First == this) { Sl.First = Next; } else { Prev.Next = Next; } if (Sl.Last == this) { Sl.Last = Prev; } else { Next.Prev = Prev; } } } } }
// --------------------------------------------------------------------------- // <copyright file="GetConversationItemsRequest.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the GetConversationItemsRequest class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Text; /// <summary> /// Represents a request to a GetConversationItems operation /// </summary> internal sealed class GetConversationItemsRequest : MultiResponseServiceRequest<GetConversationItemsResponse>, IJsonSerializable { /// <summary> /// Initializes a new instance of the <see cref="GetConversationItemsRequest"/> class. /// </summary> /// <param name="service">The service.</param> /// <param name="errorHandlingMode">Error handling mode.</param> internal GetConversationItemsRequest(ExchangeService service, ServiceErrorHandling errorHandlingMode) : base(service, errorHandlingMode) { } /// <summary> /// Gets or sets the conversations. /// </summary> internal List<ConversationRequest> Conversations { get; set; } /// <summary> /// Gets or sets the item properties. /// </summary> internal PropertySet ItemProperties { get; set; } /// <summary> /// Gets or sets the folders to ignore. /// </summary> internal FolderIdCollection FoldersToIgnore { get; set; } /// <summary> /// Gets or sets the maximum number of items to return. /// </summary> internal int? MaxItemsToReturn { get; set; } internal ConversationSortOrder? SortOrder { get; set; } /// <summary> /// Gets or sets the mailbox search location to include in the search. /// </summary> internal MailboxSearchLocation? MailboxScope { get; set; } /// <summary> /// Validate request. /// </summary> internal override void Validate() { base.Validate(); // SearchScope is only valid for Exchange2013 or higher // if (this.MailboxScope.HasValue && this.Service.RequestedServerVersion < ExchangeVersion.Exchange2013) { throw new ServiceVersionException( string.Format( Strings.ParameterIncompatibleWithRequestVersion, "MailboxScope", ExchangeVersion.Exchange2013)); } } /// <summary> /// Writes XML attributes. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteAttributesToXml(EwsServiceXmlWriter writer) { base.WriteAttributesToXml(writer); } /// <summary> /// Writes XML elements. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { this.ItemProperties.WriteToXml(writer, ServiceObjectType.Item); this.FoldersToIgnore.WriteToXml(writer, XmlNamespace.Messages, XmlElementNames.FoldersToIgnore); if (this.MaxItemsToReturn.HasValue) { writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.MaxItemsToReturn, this.MaxItemsToReturn.Value); } if (this.SortOrder.HasValue) { writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.SortOrder, this.SortOrder.Value); } if (this.MailboxScope.HasValue) { writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.MailboxScope, this.MailboxScope.Value); } writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.Conversations); this.Conversations.ForEach((conversation) => conversation.WriteToXml(writer, XmlElementNames.Conversation)); writer.WriteEndElement(); } /// <summary> /// Creates a JSON representation of this object. /// </summary> /// <param name="service">The service.</param> /// <returns> /// A Json value (either a JsonObject, an array of Json values, or a Json primitive) /// </returns> object IJsonSerializable.ToJson(ExchangeService service) { JsonObject jsonRequest = new JsonObject(); this.ItemProperties.WriteGetShapeToJson(jsonRequest, service, ServiceObjectType.Item); if (this.FoldersToIgnore.Count > 0) { jsonRequest.Add(XmlElementNames.FoldersToIgnore, this.FoldersToIgnore.InternalToJson(service)); } if (this.MaxItemsToReturn.HasValue) { jsonRequest.Add(XmlElementNames.MaxItemsToReturn, this.MaxItemsToReturn.Value); } if (this.SortOrder.HasValue) { jsonRequest.Add(XmlElementNames.SortOrder, this.SortOrder.Value); } if (this.MailboxScope.HasValue) { jsonRequest.Add(XmlElementNames.MailboxScope, this.MailboxScope.Value); } List<object> jsonPropertyCollection = new List<object>(); this.Conversations.ForEach((conversation) => jsonPropertyCollection.Add(conversation.InternalToJson(service))); jsonRequest.Add(XmlElementNames.Conversations, jsonPropertyCollection.ToArray()); return jsonRequest; } /// <summary> /// Creates the service response. /// </summary> /// <param name="service">The service.</param> /// <param name="responseIndex">Index of the response.</param> /// <returns>Service response.</returns> internal override GetConversationItemsResponse CreateServiceResponse(ExchangeService service, int responseIndex) { return new GetConversationItemsResponse(this.ItemProperties); } /// <summary> /// Gets the name of the XML element. /// </summary> /// <returns>XML element name.</returns> internal override string GetXmlElementName() { return XmlElementNames.GetConversationItems; } /// <summary> /// Gets the name of the response XML element. /// </summary> /// <returns>XML element name.</returns> internal override string GetResponseXmlElementName() { return XmlElementNames.GetConversationItemsResponse; } /// <summary> /// Gets the name of the response message XML element. /// </summary> /// <returns>XML element name.</returns> internal override string GetResponseMessageXmlElementName() { return XmlElementNames.GetConversationItemsResponseMessage; } /// <summary> /// Gets the request version. /// </summary> /// <returns>Earliest Exchange version in which this request is supported.</returns> internal override ExchangeVersion GetMinimumRequiredServerVersion() { return ExchangeVersion.Exchange2013; } /// <summary> /// Gets the expected response message count. /// </summary> /// <returns>Number of expected response messages.</returns> internal override int GetExpectedResponseMessageCount() { return this.Conversations.Count; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// HttpRedirects operations. /// </summary> public partial class HttpRedirects : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpRedirects { /// <summary> /// Initializes a new instance of the HttpRedirects class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public HttpRedirects(AutoRestHttpInfrastructureTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestHttpInfrastructureTestService /// </summary> public AutoRestHttpInfrastructureTestService Client { get; private set; } /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsHead300Headers>> Head300WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Head300", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/300").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("HEAD"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 300) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsHead300Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsHead300Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<IList<string>,HttpRedirectsGet300Headers>> Get300WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get300", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/300").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 300) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationResponse<IList<string>,HttpRedirectsGet300Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 300) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<IList<string>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsGet300Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsHead301Headers>> Head301WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Head301", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/301").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("HEAD"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 301) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsHead301Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsHead301Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsGet301Headers>> Get301WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get301", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/301").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 301) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsGet301Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsGet301Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put true Boolean value in request returns 301. This request should not be /// automatically redirected, but should return the received 301 to the /// caller for evaluation /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsPut301Headers>> Put301WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Put301", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/301").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 301) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsPut301Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsPut301Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsHead302Headers>> Head302WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Head302", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/302").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("HEAD"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 302) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsHead302Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsHead302Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsGet302Headers>> Get302WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get302", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/302").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 302) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsGet302Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsGet302Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Patch true Boolean value in request returns 302. This request should not /// be automatically redirected, but should return the received 302 to the /// caller for evaluation /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsPatch302Headers>> Patch302WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Patch302", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/302").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 302) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsPatch302Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsPatch302Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Post true Boolean value in request returns 303. This request should be /// automatically redirected usign a get, ultimately returning a 200 status /// code /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsPost303Headers>> Post303WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Post303", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/303").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 303) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsPost303Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsPost303Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Redirect with 307, resulting in a 200 success /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsHead307Headers>> Head307WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Head307", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/307").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("HEAD"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 307) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsHead307Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsHead307Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Redirect get with 307, resulting in a 200 success /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsGet307Headers>> Get307WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get307", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/307").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 307) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsGet307Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsGet307Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsPut307Headers>> Put307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Put307", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/307").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 307) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsPut307Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsPut307Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Patch redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsPatch307Headers>> Patch307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Patch307", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/307").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 307) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsPatch307Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsPatch307Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Post redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsPost307Headers>> Post307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Post307", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/307").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 307) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsPost307Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsPost307Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Delete redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationHeaderResponse<HttpRedirectsDelete307Headers>> Delete307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete307", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/redirect/307").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200 && (int)_statusCode != 307) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new HttpOperationHeaderResponse<HttpRedirectsDelete307Headers>(); _result.Request = _httpRequest; _result.Response = _httpResponse; try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HttpRedirectsDelete307Headers>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { throw new RestException("Unable to deserialize the headers.", ex); } if (_shouldTrace) { 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; using System.Text; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.CustomAttributes; namespace Internal.Reflection.Tracing { public static partial class ReflectionTrace { //============================================================================== // Returns the type name to emit into the ETW record. // // - If it returns null, skip writing the ETW record. Null returns can happen // for the following reasons: // - Missing metadata // - Open type (no need to trace these - open type creations always succeed) // - Third-party-implemented Types. // // The implementation does a reasonable-effort to avoid MME's to avoid an annoying // debugger experience. However, some MME's will still get caught by the try/catch. // // - The format happens to match what the AssemblyQualifiedName property returns // but we cannot invoke that here due to the risk of infinite recursion. // The implementation must be very careful what it calls. //============================================================================== private static String NameString(this Type type) { try { return type.AssemblyQualifiedTypeName(); } catch { return null; } } //============================================================================== // Returns the assembly name to emit into the ETW record. //============================================================================== private static String NameString(this Assembly assembly) { try { RuntimeAssembly runtimeAssembly = assembly as RuntimeAssembly; if (runtimeAssembly == null) return null; return runtimeAssembly.RuntimeAssemblyName.FullName; } catch { return null; } } //============================================================================== // Returns the custom attribute type name to emit into the ETW record. //============================================================================== private static String AttributeTypeNameString(this CustomAttributeData customAttributeData) { try { RuntimeCustomAttributeData runtimeCustomAttributeData = customAttributeData as RuntimeCustomAttributeData; if (runtimeCustomAttributeData == null) return null; return runtimeCustomAttributeData.AttributeType.NameString(); } catch { return null; } } //============================================================================== // Returns the declaring type name (without calling MemberInfo.DeclaringType) to emit into the ETW record. //============================================================================== private static String DeclaringTypeNameString(this MemberInfo memberInfo) { try { ITraceableTypeMember traceableTypeMember = memberInfo as ITraceableTypeMember; if (traceableTypeMember == null) return null; return traceableTypeMember.ContainingType.NameString(); } catch { return null; } } //============================================================================== // Returns the MemberInfo.Name value (without calling MemberInfo.Name) to emit into the ETW record. //============================================================================== private static String NameString(this MemberInfo memberInfo) { try { TypeInfo typeInfo = memberInfo as TypeInfo; if (typeInfo != null) return typeInfo.AsType().NameString(); ITraceableTypeMember traceableTypeMember = memberInfo as ITraceableTypeMember; if (traceableTypeMember == null) return null; return traceableTypeMember.MemberName; } catch { return null; } } //============================================================================== // Append type argument strings. //============================================================================== private static String GenericTypeArgumentStrings(this Type[] typeArguments) { if (typeArguments == null) return null; String s = ""; foreach (Type typeArgument in typeArguments) { String typeArgumentString = typeArgument.NameString(); if (typeArgumentString == null) return null; s += "@" + typeArgumentString; } return s; } private static String NonQualifiedTypeName(this Type type) { if (!type.IsRuntimeImplemented()) return null; RuntimeTypeInfo runtimeType = type.CastToRuntimeTypeInfo(); if (runtimeType.HasElementType) { String elementTypeName = runtimeType.InternalRuntimeElementType.NonQualifiedTypeName(); if (elementTypeName == null) return null; String suffix; if (runtimeType.IsArray) { int rank = runtimeType.GetArrayRank(); if (rank == 1) suffix = "[" + (runtimeType.InternalIsMultiDimArray ? "*" : "") + "]"; else suffix = "[" + new String(',', rank - 1) + "]"; } else if (runtimeType.IsByRef) suffix = "&"; else if (runtimeType.IsPointer) suffix = "*"; else return null; return elementTypeName + suffix; } else if (runtimeType.IsGenericParameter) { return null; } else if (runtimeType.IsConstructedGenericType) { StringBuilder sb = new StringBuilder(); String genericTypeDefinitionTypeName = runtimeType.GetGenericTypeDefinition().NonQualifiedTypeName(); if (genericTypeDefinitionTypeName == null) return null; sb.Append(genericTypeDefinitionTypeName); sb.Append("["); String sep = ""; foreach (RuntimeTypeInfo ga in runtimeType.InternalRuntimeGenericTypeArguments) { String gaTypeName = ga.AssemblyQualifiedTypeName(); if (gaTypeName == null) return null; sb.Append(sep + "[" + gaTypeName + "]"); sep = ","; } sb.Append("]"); return sb.ToString(); } else { RuntimeNamedTypeInfo runtimeNamedTypeInfo = type.GetTypeInfo() as RuntimeNamedTypeInfo; if (runtimeNamedTypeInfo == null) return null; return runtimeNamedTypeInfo.TraceableTypeName; } } private static String AssemblyQualifiedTypeName(this Type type) { if (!type.IsRuntimeImplemented()) return null; RuntimeTypeInfo runtimeType = type.CastToRuntimeTypeInfo(); if (runtimeType == null) return null; String nonqualifiedTypeName = runtimeType.NonQualifiedTypeName(); if (nonqualifiedTypeName == null) return null; String assemblyName = runtimeType.ContainingAssemblyName(); if (assemblyName == null) return assemblyName; return nonqualifiedTypeName + ", " + assemblyName; } private static String ContainingAssemblyName(this Type type) { if (!type.IsRuntimeImplemented()) return null; RuntimeTypeInfo runtimeTypeInfo = type.CastToRuntimeTypeInfo(); if (runtimeTypeInfo is RuntimeNoMetadataNamedTypeInfo) return null; return runtimeTypeInfo.Assembly.NameString(); } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// User ///<para>SObject Name: User</para> ///<para>Custom Object: False</para> ///</summary> public class SfUser : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "User"; } } ///<summary> /// User ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Username /// <para>Name: Username</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "username")] public string Username { get; set; } ///<summary> /// Last Name /// <para>Name: LastName</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastName")] public string LastName { get; set; } ///<summary> /// First Name /// <para>Name: FirstName</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "firstName")] public string FirstName { get; set; } ///<summary> /// Full Name /// <para>Name: Name</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "name")] [Updateable(false), Createable(false)] public string Name { get; set; } ///<summary> /// Company Name /// <para>Name: CompanyName</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "companyName")] public string CompanyName { get; set; } ///<summary> /// Division /// <para>Name: Division</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "division")] public string Division { get; set; } ///<summary> /// Department /// <para>Name: Department</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "department")] public string Department { get; set; } ///<summary> /// Title /// <para>Name: Title</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "title")] public string Title { get; set; } ///<summary> /// Street /// <para>Name: Street</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "street")] public string Street { get; set; } ///<summary> /// City /// <para>Name: City</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "city")] public string City { get; set; } ///<summary> /// State/Province /// <para>Name: State</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "state")] public string State { get; set; } ///<summary> /// Zip/Postal Code /// <para>Name: PostalCode</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "postalCode")] public string PostalCode { get; set; } ///<summary> /// Country /// <para>Name: Country</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "country")] public string Country { get; set; } ///<summary> /// Latitude /// <para>Name: Latitude</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "latitude")] public double? Latitude { get; set; } ///<summary> /// Longitude /// <para>Name: Longitude</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "longitude")] public double? Longitude { get; set; } ///<summary> /// Geocode Accuracy /// <para>Name: GeocodeAccuracy</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "geocodeAccuracy")] public string GeocodeAccuracy { get; set; } ///<summary> /// Address /// <para>Name: Address</para> /// <para>SF Type: address</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "address")] [Updateable(false), Createable(false)] public Address Address { get; set; } ///<summary> /// Email /// <para>Name: Email</para> /// <para>SF Type: email</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "email")] public string Email { get; set; } ///<summary> /// AutoBcc /// <para>Name: EmailPreferencesAutoBcc</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "emailPreferencesAutoBcc")] public bool? EmailPreferencesAutoBcc { get; set; } ///<summary> /// AutoBccStayInTouch /// <para>Name: EmailPreferencesAutoBccStayInTouch</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "emailPreferencesAutoBccStayInTouch")] public bool? EmailPreferencesAutoBccStayInTouch { get; set; } ///<summary> /// StayInTouchReminder /// <para>Name: EmailPreferencesStayInTouchReminder</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "emailPreferencesStayInTouchReminder")] public bool? EmailPreferencesStayInTouchReminder { get; set; } ///<summary> /// Email Sender Address /// <para>Name: SenderEmail</para> /// <para>SF Type: email</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "senderEmail")] public string SenderEmail { get; set; } ///<summary> /// Email Sender Name /// <para>Name: SenderName</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "senderName")] public string SenderName { get; set; } ///<summary> /// Email Signature /// <para>Name: Signature</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "signature")] public string Signature { get; set; } ///<summary> /// Stay-in-Touch Email Subject /// <para>Name: StayInTouchSubject</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "stayInTouchSubject")] public string StayInTouchSubject { get; set; } ///<summary> /// Stay-in-Touch Email Signature /// <para>Name: StayInTouchSignature</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "stayInTouchSignature")] public string StayInTouchSignature { get; set; } ///<summary> /// Stay-in-Touch Email Note /// <para>Name: StayInTouchNote</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "stayInTouchNote")] public string StayInTouchNote { get; set; } ///<summary> /// Phone /// <para>Name: Phone</para> /// <para>SF Type: phone</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "phone")] public string Phone { get; set; } ///<summary> /// Fax /// <para>Name: Fax</para> /// <para>SF Type: phone</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "fax")] public string Fax { get; set; } ///<summary> /// Mobile /// <para>Name: MobilePhone</para> /// <para>SF Type: phone</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "mobilePhone")] public string MobilePhone { get; set; } ///<summary> /// Alias /// <para>Name: Alias</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "alias")] public string Alias { get; set; } ///<summary> /// Nickname /// <para>Name: CommunityNickname</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "communityNickname")] public string CommunityNickname { get; set; } ///<summary> /// User Photo badge text overlay /// <para>Name: BadgeText</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "badgeText")] [Updateable(false), Createable(false)] public string BadgeText { get; set; } ///<summary> /// Active /// <para>Name: IsActive</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isActive")] public bool? IsActive { get; set; } ///<summary> /// Time Zone /// <para>Name: TimeZoneSidKey</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "timeZoneSidKey")] public string TimeZoneSidKey { get; set; } ///<summary> /// Role ID /// <para>Name: UserRoleId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "userRoleId")] public string UserRoleId { get; set; } ///<summary> /// ReferenceTo: UserRole /// <para>RelationshipName: UserRole</para> ///</summary> [JsonProperty(PropertyName = "userRole")] [Updateable(false), Createable(false)] public SfUserRole UserRole { get; set; } ///<summary> /// Locale /// <para>Name: LocaleSidKey</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "localeSidKey")] public string LocaleSidKey { get; set; } ///<summary> /// Info Emails /// <para>Name: ReceivesInfoEmails</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "receivesInfoEmails")] public bool? ReceivesInfoEmails { get; set; } ///<summary> /// Admin Info Emails /// <para>Name: ReceivesAdminInfoEmails</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "receivesAdminInfoEmails")] public bool? ReceivesAdminInfoEmails { get; set; } ///<summary> /// Email Encoding /// <para>Name: EmailEncodingKey</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "emailEncodingKey")] public string EmailEncodingKey { get; set; } ///<summary> /// Profile ID /// <para>Name: ProfileId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "profileId")] public string ProfileId { get; set; } ///<summary> /// ReferenceTo: Profile /// <para>RelationshipName: Profile</para> ///</summary> [JsonProperty(PropertyName = "profile")] [Updateable(false), Createable(false)] public SfProfile Profile { get; set; } ///<summary> /// User Type /// <para>Name: UserType</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "userType")] [Updateable(false), Createable(false)] public string UserType { get; set; } ///<summary> /// Language /// <para>Name: LanguageLocaleKey</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "languageLocaleKey")] public string LanguageLocaleKey { get; set; } ///<summary> /// Employee Number /// <para>Name: EmployeeNumber</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "employeeNumber")] public string EmployeeNumber { get; set; } ///<summary> /// Delegated Approver ID /// <para>Name: DelegatedApproverId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "delegatedApproverId")] public string DelegatedApproverId { get; set; } ///<summary> /// Manager ID /// <para>Name: ManagerId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "managerId")] public string ManagerId { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: Manager</para> ///</summary> [JsonProperty(PropertyName = "manager")] [Updateable(false), Createable(false)] public SfUser Manager { get; set; } ///<summary> /// Last Login /// <para>Name: LastLoginDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastLoginDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastLoginDate { get; set; } ///<summary> /// Last Password Change or Reset /// <para>Name: LastPasswordChangeDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastPasswordChangeDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastPasswordChangeDate { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Failed Login Attempts /// <para>Name: NumberOfFailedLogins</para> /// <para>SF Type: int</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "numberOfFailedLogins")] [Updateable(false), Createable(false)] public int? NumberOfFailedLogins { get; set; } ///<summary> /// Offline Edition Trial Expiration Date /// <para>Name: OfflineTrialExpirationDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "offlineTrialExpirationDate")] [Updateable(false), Createable(false)] public DateTimeOffset? OfflineTrialExpirationDate { get; set; } ///<summary> /// Sales Anywhere Trial Expiration Date /// <para>Name: OfflinePdaTrialExpirationDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "offlinePdaTrialExpirationDate")] [Updateable(false), Createable(false)] public DateTimeOffset? OfflinePdaTrialExpirationDate { get; set; } ///<summary> /// Marketing User /// <para>Name: UserPermissionsMarketingUser</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPermissionsMarketingUser")] public bool? UserPermissionsMarketingUser { get; set; } ///<summary> /// Offline User /// <para>Name: UserPermissionsOfflineUser</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPermissionsOfflineUser")] public bool? UserPermissionsOfflineUser { get; set; } ///<summary> /// Auto-login To Call Center /// <para>Name: UserPermissionsCallCenterAutoLogin</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPermissionsCallCenterAutoLogin")] public bool? UserPermissionsCallCenterAutoLogin { get; set; } ///<summary> /// Salesforce CRM Content User /// <para>Name: UserPermissionsSFContentUser</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPermissionsSFContentUser")] public bool? UserPermissionsSFContentUser { get; set; } ///<summary> /// Knowledge User /// <para>Name: UserPermissionsKnowledgeUser</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPermissionsKnowledgeUser")] public bool? UserPermissionsKnowledgeUser { get; set; } ///<summary> /// Flow User /// <para>Name: UserPermissionsInteractionUser</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPermissionsInteractionUser")] public bool? UserPermissionsInteractionUser { get; set; } ///<summary> /// Service Cloud User /// <para>Name: UserPermissionsSupportUser</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPermissionsSupportUser")] public bool? UserPermissionsSupportUser { get; set; } ///<summary> /// Data.com User /// <para>Name: UserPermissionsJigsawProspectingUser</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPermissionsJigsawProspectingUser")] public bool? UserPermissionsJigsawProspectingUser { get; set; } ///<summary> /// Site.com Contributor User /// <para>Name: UserPermissionsSiteforceContributorUser</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPermissionsSiteforceContributorUser")] public bool? UserPermissionsSiteforceContributorUser { get; set; } ///<summary> /// Site.com Publisher User /// <para>Name: UserPermissionsSiteforcePublisherUser</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPermissionsSiteforcePublisherUser")] public bool? UserPermissionsSiteforcePublisherUser { get; set; } ///<summary> /// WDC User /// <para>Name: UserPermissionsWorkDotComUserFeature</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPermissionsWorkDotComUserFeature")] public bool? UserPermissionsWorkDotComUserFeature { get; set; } ///<summary> /// Allow Forecasting /// <para>Name: ForecastEnabled</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "forecastEnabled")] public bool? ForecastEnabled { get; set; } ///<summary> /// ActivityRemindersPopup /// <para>Name: UserPreferencesActivityRemindersPopup</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesActivityRemindersPopup")] public bool? UserPreferencesActivityRemindersPopup { get; set; } ///<summary> /// EventRemindersCheckboxDefault /// <para>Name: UserPreferencesEventRemindersCheckboxDefault</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesEventRemindersCheckboxDefault")] public bool? UserPreferencesEventRemindersCheckboxDefault { get; set; } ///<summary> /// TaskRemindersCheckboxDefault /// <para>Name: UserPreferencesTaskRemindersCheckboxDefault</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesTaskRemindersCheckboxDefault")] public bool? UserPreferencesTaskRemindersCheckboxDefault { get; set; } ///<summary> /// ReminderSoundOff /// <para>Name: UserPreferencesReminderSoundOff</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesReminderSoundOff")] public bool? UserPreferencesReminderSoundOff { get; set; } ///<summary> /// DisableAllFeedsEmail /// <para>Name: UserPreferencesDisableAllFeedsEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableAllFeedsEmail")] public bool? UserPreferencesDisableAllFeedsEmail { get; set; } ///<summary> /// DisableFollowersEmail /// <para>Name: UserPreferencesDisableFollowersEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableFollowersEmail")] public bool? UserPreferencesDisableFollowersEmail { get; set; } ///<summary> /// DisableProfilePostEmail /// <para>Name: UserPreferencesDisableProfilePostEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableProfilePostEmail")] public bool? UserPreferencesDisableProfilePostEmail { get; set; } ///<summary> /// DisableChangeCommentEmail /// <para>Name: UserPreferencesDisableChangeCommentEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableChangeCommentEmail")] public bool? UserPreferencesDisableChangeCommentEmail { get; set; } ///<summary> /// DisableLaterCommentEmail /// <para>Name: UserPreferencesDisableLaterCommentEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableLaterCommentEmail")] public bool? UserPreferencesDisableLaterCommentEmail { get; set; } ///<summary> /// DisProfPostCommentEmail /// <para>Name: UserPreferencesDisProfPostCommentEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisProfPostCommentEmail")] public bool? UserPreferencesDisProfPostCommentEmail { get; set; } ///<summary> /// ContentNoEmail /// <para>Name: UserPreferencesContentNoEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesContentNoEmail")] public bool? UserPreferencesContentNoEmail { get; set; } ///<summary> /// ContentEmailAsAndWhen /// <para>Name: UserPreferencesContentEmailAsAndWhen</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesContentEmailAsAndWhen")] public bool? UserPreferencesContentEmailAsAndWhen { get; set; } ///<summary> /// ApexPagesDeveloperMode /// <para>Name: UserPreferencesApexPagesDeveloperMode</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesApexPagesDeveloperMode")] public bool? UserPreferencesApexPagesDeveloperMode { get; set; } ///<summary> /// ReceiveNoNotificationsAsApprover /// <para>Name: UserPreferencesReceiveNoNotificationsAsApprover</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesReceiveNoNotificationsAsApprover")] public bool? UserPreferencesReceiveNoNotificationsAsApprover { get; set; } ///<summary> /// ReceiveNotificationsAsDelegatedApprover /// <para>Name: UserPreferencesReceiveNotificationsAsDelegatedApprover</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesReceiveNotificationsAsDelegatedApprover")] public bool? UserPreferencesReceiveNotificationsAsDelegatedApprover { get; set; } ///<summary> /// HideCSNGetChatterMobileTask /// <para>Name: UserPreferencesHideCSNGetChatterMobileTask</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesHideCSNGetChatterMobileTask")] public bool? UserPreferencesHideCSNGetChatterMobileTask { get; set; } ///<summary> /// DisableMentionsPostEmail /// <para>Name: UserPreferencesDisableMentionsPostEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableMentionsPostEmail")] public bool? UserPreferencesDisableMentionsPostEmail { get; set; } ///<summary> /// DisMentionsCommentEmail /// <para>Name: UserPreferencesDisMentionsCommentEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisMentionsCommentEmail")] public bool? UserPreferencesDisMentionsCommentEmail { get; set; } ///<summary> /// HideCSNDesktopTask /// <para>Name: UserPreferencesHideCSNDesktopTask</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesHideCSNDesktopTask")] public bool? UserPreferencesHideCSNDesktopTask { get; set; } ///<summary> /// HideChatterOnboardingSplash /// <para>Name: UserPreferencesHideChatterOnboardingSplash</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesHideChatterOnboardingSplash")] public bool? UserPreferencesHideChatterOnboardingSplash { get; set; } ///<summary> /// HideSecondChatterOnboardingSplash /// <para>Name: UserPreferencesHideSecondChatterOnboardingSplash</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesHideSecondChatterOnboardingSplash")] public bool? UserPreferencesHideSecondChatterOnboardingSplash { get; set; } ///<summary> /// DisCommentAfterLikeEmail /// <para>Name: UserPreferencesDisCommentAfterLikeEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisCommentAfterLikeEmail")] public bool? UserPreferencesDisCommentAfterLikeEmail { get; set; } ///<summary> /// DisableLikeEmail /// <para>Name: UserPreferencesDisableLikeEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableLikeEmail")] public bool? UserPreferencesDisableLikeEmail { get; set; } ///<summary> /// SortFeedByComment /// <para>Name: UserPreferencesSortFeedByComment</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesSortFeedByComment")] public bool? UserPreferencesSortFeedByComment { get; set; } ///<summary> /// DisableMessageEmail /// <para>Name: UserPreferencesDisableMessageEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableMessageEmail")] public bool? UserPreferencesDisableMessageEmail { get; set; } ///<summary> /// HideLegacyRetirementModal /// <para>Name: UserPreferencesHideLegacyRetirementModal</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesHideLegacyRetirementModal")] public bool? UserPreferencesHideLegacyRetirementModal { get; set; } ///<summary> /// JigsawListUser /// <para>Name: UserPreferencesJigsawListUser</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesJigsawListUser")] public bool? UserPreferencesJigsawListUser { get; set; } ///<summary> /// DisableBookmarkEmail /// <para>Name: UserPreferencesDisableBookmarkEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableBookmarkEmail")] public bool? UserPreferencesDisableBookmarkEmail { get; set; } ///<summary> /// DisableSharePostEmail /// <para>Name: UserPreferencesDisableSharePostEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableSharePostEmail")] public bool? UserPreferencesDisableSharePostEmail { get; set; } ///<summary> /// EnableAutoSubForFeeds /// <para>Name: UserPreferencesEnableAutoSubForFeeds</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesEnableAutoSubForFeeds")] public bool? UserPreferencesEnableAutoSubForFeeds { get; set; } ///<summary> /// DisableFileShareNotificationsForApi /// <para>Name: UserPreferencesDisableFileShareNotificationsForApi</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableFileShareNotificationsForApi")] public bool? UserPreferencesDisableFileShareNotificationsForApi { get; set; } ///<summary> /// ShowTitleToExternalUsers /// <para>Name: UserPreferencesShowTitleToExternalUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowTitleToExternalUsers")] public bool? UserPreferencesShowTitleToExternalUsers { get; set; } ///<summary> /// ShowManagerToExternalUsers /// <para>Name: UserPreferencesShowManagerToExternalUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowManagerToExternalUsers")] public bool? UserPreferencesShowManagerToExternalUsers { get; set; } ///<summary> /// ShowEmailToExternalUsers /// <para>Name: UserPreferencesShowEmailToExternalUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowEmailToExternalUsers")] public bool? UserPreferencesShowEmailToExternalUsers { get; set; } ///<summary> /// ShowWorkPhoneToExternalUsers /// <para>Name: UserPreferencesShowWorkPhoneToExternalUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowWorkPhoneToExternalUsers")] public bool? UserPreferencesShowWorkPhoneToExternalUsers { get; set; } ///<summary> /// ShowMobilePhoneToExternalUsers /// <para>Name: UserPreferencesShowMobilePhoneToExternalUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowMobilePhoneToExternalUsers")] public bool? UserPreferencesShowMobilePhoneToExternalUsers { get; set; } ///<summary> /// ShowFaxToExternalUsers /// <para>Name: UserPreferencesShowFaxToExternalUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowFaxToExternalUsers")] public bool? UserPreferencesShowFaxToExternalUsers { get; set; } ///<summary> /// ShowStreetAddressToExternalUsers /// <para>Name: UserPreferencesShowStreetAddressToExternalUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowStreetAddressToExternalUsers")] public bool? UserPreferencesShowStreetAddressToExternalUsers { get; set; } ///<summary> /// ShowCityToExternalUsers /// <para>Name: UserPreferencesShowCityToExternalUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowCityToExternalUsers")] public bool? UserPreferencesShowCityToExternalUsers { get; set; } ///<summary> /// ShowStateToExternalUsers /// <para>Name: UserPreferencesShowStateToExternalUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowStateToExternalUsers")] public bool? UserPreferencesShowStateToExternalUsers { get; set; } ///<summary> /// ShowPostalCodeToExternalUsers /// <para>Name: UserPreferencesShowPostalCodeToExternalUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowPostalCodeToExternalUsers")] public bool? UserPreferencesShowPostalCodeToExternalUsers { get; set; } ///<summary> /// ShowCountryToExternalUsers /// <para>Name: UserPreferencesShowCountryToExternalUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowCountryToExternalUsers")] public bool? UserPreferencesShowCountryToExternalUsers { get; set; } ///<summary> /// ShowProfilePicToGuestUsers /// <para>Name: UserPreferencesShowProfilePicToGuestUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowProfilePicToGuestUsers")] public bool? UserPreferencesShowProfilePicToGuestUsers { get; set; } ///<summary> /// ShowTitleToGuestUsers /// <para>Name: UserPreferencesShowTitleToGuestUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowTitleToGuestUsers")] public bool? UserPreferencesShowTitleToGuestUsers { get; set; } ///<summary> /// ShowCityToGuestUsers /// <para>Name: UserPreferencesShowCityToGuestUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowCityToGuestUsers")] public bool? UserPreferencesShowCityToGuestUsers { get; set; } ///<summary> /// ShowStateToGuestUsers /// <para>Name: UserPreferencesShowStateToGuestUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowStateToGuestUsers")] public bool? UserPreferencesShowStateToGuestUsers { get; set; } ///<summary> /// ShowPostalCodeToGuestUsers /// <para>Name: UserPreferencesShowPostalCodeToGuestUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowPostalCodeToGuestUsers")] public bool? UserPreferencesShowPostalCodeToGuestUsers { get; set; } ///<summary> /// ShowCountryToGuestUsers /// <para>Name: UserPreferencesShowCountryToGuestUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowCountryToGuestUsers")] public bool? UserPreferencesShowCountryToGuestUsers { get; set; } ///<summary> /// DisableFeedbackEmail /// <para>Name: UserPreferencesDisableFeedbackEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableFeedbackEmail")] public bool? UserPreferencesDisableFeedbackEmail { get; set; } ///<summary> /// DisableWorkEmail /// <para>Name: UserPreferencesDisableWorkEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableWorkEmail")] public bool? UserPreferencesDisableWorkEmail { get; set; } ///<summary> /// HideS1BrowserUI /// <para>Name: UserPreferencesHideS1BrowserUI</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesHideS1BrowserUI")] public bool? UserPreferencesHideS1BrowserUI { get; set; } ///<summary> /// DisableEndorsementEmail /// <para>Name: UserPreferencesDisableEndorsementEmail</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesDisableEndorsementEmail")] public bool? UserPreferencesDisableEndorsementEmail { get; set; } ///<summary> /// PathAssistantCollapsed /// <para>Name: UserPreferencesPathAssistantCollapsed</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesPathAssistantCollapsed")] public bool? UserPreferencesPathAssistantCollapsed { get; set; } ///<summary> /// CacheDiagnostics /// <para>Name: UserPreferencesCacheDiagnostics</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesCacheDiagnostics")] public bool? UserPreferencesCacheDiagnostics { get; set; } ///<summary> /// ShowEmailToGuestUsers /// <para>Name: UserPreferencesShowEmailToGuestUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowEmailToGuestUsers")] public bool? UserPreferencesShowEmailToGuestUsers { get; set; } ///<summary> /// ShowManagerToGuestUsers /// <para>Name: UserPreferencesShowManagerToGuestUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowManagerToGuestUsers")] public bool? UserPreferencesShowManagerToGuestUsers { get; set; } ///<summary> /// ShowWorkPhoneToGuestUsers /// <para>Name: UserPreferencesShowWorkPhoneToGuestUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowWorkPhoneToGuestUsers")] public bool? UserPreferencesShowWorkPhoneToGuestUsers { get; set; } ///<summary> /// ShowMobilePhoneToGuestUsers /// <para>Name: UserPreferencesShowMobilePhoneToGuestUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowMobilePhoneToGuestUsers")] public bool? UserPreferencesShowMobilePhoneToGuestUsers { get; set; } ///<summary> /// ShowFaxToGuestUsers /// <para>Name: UserPreferencesShowFaxToGuestUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowFaxToGuestUsers")] public bool? UserPreferencesShowFaxToGuestUsers { get; set; } ///<summary> /// ShowStreetAddressToGuestUsers /// <para>Name: UserPreferencesShowStreetAddressToGuestUsers</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesShowStreetAddressToGuestUsers")] public bool? UserPreferencesShowStreetAddressToGuestUsers { get; set; } ///<summary> /// LightningExperiencePreferred /// <para>Name: UserPreferencesLightningExperiencePreferred</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesLightningExperiencePreferred")] public bool? UserPreferencesLightningExperiencePreferred { get; set; } ///<summary> /// PreviewLightning /// <para>Name: UserPreferencesPreviewLightning</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesPreviewLightning")] public bool? UserPreferencesPreviewLightning { get; set; } ///<summary> /// HideEndUserOnboardingAssistantModal /// <para>Name: UserPreferencesHideEndUserOnboardingAssistantModal</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesHideEndUserOnboardingAssistantModal")] public bool? UserPreferencesHideEndUserOnboardingAssistantModal { get; set; } ///<summary> /// HideLightningMigrationModal /// <para>Name: UserPreferencesHideLightningMigrationModal</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesHideLightningMigrationModal")] public bool? UserPreferencesHideLightningMigrationModal { get; set; } ///<summary> /// HideSfxWelcomeMat /// <para>Name: UserPreferencesHideSfxWelcomeMat</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesHideSfxWelcomeMat")] public bool? UserPreferencesHideSfxWelcomeMat { get; set; } ///<summary> /// HideBiggerPhotoCallout /// <para>Name: UserPreferencesHideBiggerPhotoCallout</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesHideBiggerPhotoCallout")] public bool? UserPreferencesHideBiggerPhotoCallout { get; set; } ///<summary> /// GlobalNavBarWTShown /// <para>Name: UserPreferencesGlobalNavBarWTShown</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesGlobalNavBarWTShown")] public bool? UserPreferencesGlobalNavBarWTShown { get; set; } ///<summary> /// GlobalNavGridMenuWTShown /// <para>Name: UserPreferencesGlobalNavGridMenuWTShown</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesGlobalNavGridMenuWTShown")] public bool? UserPreferencesGlobalNavGridMenuWTShown { get; set; } ///<summary> /// CreateLEXAppsWTShown /// <para>Name: UserPreferencesCreateLEXAppsWTShown</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesCreateLEXAppsWTShown")] public bool? UserPreferencesCreateLEXAppsWTShown { get; set; } ///<summary> /// FavoritesWTShown /// <para>Name: UserPreferencesFavoritesWTShown</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesFavoritesWTShown")] public bool? UserPreferencesFavoritesWTShown { get; set; } ///<summary> /// RecordHomeSectionCollapseWTShown /// <para>Name: UserPreferencesRecordHomeSectionCollapseWTShown</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesRecordHomeSectionCollapseWTShown")] public bool? UserPreferencesRecordHomeSectionCollapseWTShown { get; set; } ///<summary> /// RecordHomeReservedWTShown /// <para>Name: UserPreferencesRecordHomeReservedWTShown</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesRecordHomeReservedWTShown")] public bool? UserPreferencesRecordHomeReservedWTShown { get; set; } ///<summary> /// FavoritesShowTopFavorites /// <para>Name: UserPreferencesFavoritesShowTopFavorites</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesFavoritesShowTopFavorites")] public bool? UserPreferencesFavoritesShowTopFavorites { get; set; } ///<summary> /// ExcludeMailAppAttachments /// <para>Name: UserPreferencesExcludeMailAppAttachments</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesExcludeMailAppAttachments")] public bool? UserPreferencesExcludeMailAppAttachments { get; set; } ///<summary> /// SuppressTaskSFXReminders /// <para>Name: UserPreferencesSuppressTaskSFXReminders</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesSuppressTaskSFXReminders")] public bool? UserPreferencesSuppressTaskSFXReminders { get; set; } ///<summary> /// SuppressEventSFXReminders /// <para>Name: UserPreferencesSuppressEventSFXReminders</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesSuppressEventSFXReminders")] public bool? UserPreferencesSuppressEventSFXReminders { get; set; } ///<summary> /// PreviewCustomTheme /// <para>Name: UserPreferencesPreviewCustomTheme</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesPreviewCustomTheme")] public bool? UserPreferencesPreviewCustomTheme { get; set; } ///<summary> /// HasCelebrationBadge /// <para>Name: UserPreferencesHasCelebrationBadge</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesHasCelebrationBadge")] public bool? UserPreferencesHasCelebrationBadge { get; set; } ///<summary> /// UserDebugModePref /// <para>Name: UserPreferencesUserDebugModePref</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesUserDebugModePref")] public bool? UserPreferencesUserDebugModePref { get; set; } ///<summary> /// SRHOverrideActivities /// <para>Name: UserPreferencesSRHOverrideActivities</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesSRHOverrideActivities")] public bool? UserPreferencesSRHOverrideActivities { get; set; } ///<summary> /// NewLightningReportRunPageEnabled /// <para>Name: UserPreferencesNewLightningReportRunPageEnabled</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesNewLightningReportRunPageEnabled")] public bool? UserPreferencesNewLightningReportRunPageEnabled { get; set; } ///<summary> /// NativeEmailClient /// <para>Name: UserPreferencesNativeEmailClient</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "userPreferencesNativeEmailClient")] public bool? UserPreferencesNativeEmailClient { get; set; } ///<summary> /// Contact ID /// <para>Name: ContactId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "contactId")] public string ContactId { get; set; } ///<summary> /// ReferenceTo: Contact /// <para>RelationshipName: Contact</para> ///</summary> [JsonProperty(PropertyName = "contact")] [Updateable(false), Createable(false)] public SfContact Contact { get; set; } ///<summary> /// Account ID /// <para>Name: AccountId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "accountId")] [Updateable(false), Createable(false)] public string AccountId { get; set; } ///<summary> /// ReferenceTo: Account /// <para>RelationshipName: Account</para> ///</summary> [JsonProperty(PropertyName = "account")] [Updateable(false), Createable(false)] public SfAccount Account { get; set; } ///<summary> /// Call Center ID /// <para>Name: CallCenterId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "callCenterId")] public string CallCenterId { get; set; } ///<summary> /// Extension /// <para>Name: Extension</para> /// <para>SF Type: phone</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "extension")] public string Extension { get; set; } ///<summary> /// SAML Federation ID /// <para>Name: FederationIdentifier</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "federationIdentifier")] public string FederationIdentifier { get; set; } ///<summary> /// About Me /// <para>Name: AboutMe</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "aboutMe")] public string AboutMe { get; set; } ///<summary> /// Url for full-sized Photo /// <para>Name: FullPhotoUrl</para> /// <para>SF Type: url</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "fullPhotoUrl")] [Updateable(false), Createable(false)] public string FullPhotoUrl { get; set; } ///<summary> /// Photo /// <para>Name: SmallPhotoUrl</para> /// <para>SF Type: url</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "smallPhotoUrl")] [Updateable(false), Createable(false)] public string SmallPhotoUrl { get; set; } ///<summary> /// Show external indicator /// <para>Name: IsExtIndicatorVisible</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isExtIndicatorVisible")] [Updateable(false), Createable(false)] public bool? IsExtIndicatorVisible { get; set; } ///<summary> /// Out of office message /// <para>Name: OutOfOfficeMessage</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "outOfOfficeMessage")] [Updateable(false), Createable(false)] public string OutOfOfficeMessage { get; set; } ///<summary> /// Url for medium profile photo /// <para>Name: MediumPhotoUrl</para> /// <para>SF Type: url</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "mediumPhotoUrl")] [Updateable(false), Createable(false)] public string MediumPhotoUrl { get; set; } ///<summary> /// Chatter Email Highlights Frequency /// <para>Name: DigestFrequency</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "digestFrequency")] public string DigestFrequency { get; set; } ///<summary> /// Default Notification Frequency when Joining Groups /// <para>Name: DefaultGroupNotificationFrequency</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "defaultGroupNotificationFrequency")] public string DefaultGroupNotificationFrequency { get; set; } ///<summary> /// Data.com Monthly Addition Limit /// <para>Name: JigsawImportLimitOverride</para> /// <para>SF Type: int</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "jigsawImportLimitOverride")] public int? JigsawImportLimitOverride { get; set; } ///<summary> /// Last Viewed Date /// <para>Name: LastViewedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastViewedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastViewedDate { get; set; } ///<summary> /// Last Referenced Date /// <para>Name: LastReferencedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastReferencedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastReferencedDate { get; set; } ///<summary> /// Url for banner photo /// <para>Name: BannerPhotoUrl</para> /// <para>SF Type: url</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "bannerPhotoUrl")] [Updateable(false), Createable(false)] public string BannerPhotoUrl { get; set; } ///<summary> /// Url for IOS banner photo /// <para>Name: SmallBannerPhotoUrl</para> /// <para>SF Type: url</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "smallBannerPhotoUrl")] [Updateable(false), Createable(false)] public string SmallBannerPhotoUrl { get; set; } ///<summary> /// Url for Android banner photo /// <para>Name: MediumBannerPhotoUrl</para> /// <para>SF Type: url</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "mediumBannerPhotoUrl")] [Updateable(false), Createable(false)] public string MediumBannerPhotoUrl { get; set; } ///<summary> /// Has Profile Photo /// <para>Name: IsProfilePhotoActive</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isProfilePhotoActive")] [Updateable(false), Createable(false)] public bool? IsProfilePhotoActive { get; set; } ///<summary> /// Individual ID /// <para>Name: IndividualId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "individualId")] public string IndividualId { get; set; } ///<summary> /// ReferenceTo: Individual /// <para>RelationshipName: Individual</para> ///</summary> [JsonProperty(PropertyName = "individual")] [Updateable(false), Createable(false)] public SfIndividual Individual { get; set; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Python.Properties; using Microsoft.Rest.Generator.Python.Templates; using Microsoft.Rest.Generator.Python.TemplateModels; using Microsoft.Rest.Generator.Utilities; using System; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Rest.Generator.Python { public class PythonCodeGenerator : CodeGenerator { private const string ClientRuntimePackage = "msrest version 0.4.0"; private string packageVersion; public PythonCodeGenerator(Settings settings) : base(settings) { Namer = new PythonCodeNamer(); this.packageVersion = Settings.PackageVersion; } public PythonCodeNamer Namer { get; set; } public override string Name { get { return "Python"; } } public override string Description { // TODO resource string. get { return "Generic Python code generator."; } } protected String PackageVersion { get { return this.packageVersion; } } public override string UsageInstructions { get { return string.Format(CultureInfo.InvariantCulture, Resources.UsageInformation, ClientRuntimePackage); } } public override string ImplementationFileExtension { get { return ".py"; } } /// <summary> /// Normalizes client model by updating names and types to be language specific. /// </summary> /// <param name="serviceClient"></param> public override void NormalizeClientModel(ServiceClient serviceClient) { Extensions.NormalizeClientModel(serviceClient, Settings); PopulateAdditionalProperties(serviceClient); Namer.NormalizeClientModel(serviceClient); Namer.ResolveNameCollisions(serviceClient, Settings.Namespace, Settings.Namespace + "_models"); } private void PopulateAdditionalProperties(ServiceClient serviceClient) { if (Settings.AddCredentials) { if (!serviceClient.Properties.Any(p => p.Type.IsPrimaryType(KnownPrimaryType.Credentials))) { serviceClient.Properties.Add(new Property { Name = "credentials", SerializedName = "credentials", Type = new PrimaryType(KnownPrimaryType.Credentials), IsRequired = true, Documentation = "Subscription credentials which uniquely identify client subscription." }); } } } /// <summary> /// Generate Python client code for given ServiceClient. /// </summary> /// <param name="serviceClient"></param> /// <returns></returns> public override async Task Generate(ServiceClient serviceClient) { var serviceClientTemplateModel = new ServiceClientTemplateModel(serviceClient); if (!string.IsNullOrWhiteSpace(this.PackageVersion)) { serviceClientTemplateModel.Version = this.PackageVersion; } // Service client var setupTemplate = new SetupTemplate { Model = serviceClientTemplateModel }; await Write(setupTemplate, "setup.py"); var serviceClientInitTemplate = new ServiceClientInitTemplate { Model = serviceClientTemplateModel }; await Write(serviceClientInitTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "__init__.py")); var serviceClientTemplate = new ServiceClientTemplate { Model = serviceClientTemplateModel, }; await Write(serviceClientTemplate, Path.Combine(serviceClientTemplateModel.PackageName, serviceClientTemplateModel.Name.ToPythonCase() + ".py")); var versionTemplate = new VersionTemplate { Model = serviceClientTemplateModel, }; await Write(versionTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "version.py")); var exceptionTemplate = new ExceptionTemplate { Model = serviceClientTemplateModel, }; await Write(exceptionTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "exceptions.py")); var credentialTemplate = new CredentialTemplate { Model = serviceClientTemplateModel, }; await Write(credentialTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "credentials.py")); //Models if (serviceClient.ModelTypes.Any()) { var modelInitTemplate = new ModelInitTemplate { Model = new ModelInitTemplateModel(serviceClient) }; await Write(modelInitTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", "__init__.py")); foreach (var modelType in serviceClientTemplateModel.ModelTemplateModels) { var modelTemplate = new ModelTemplate { Model = modelType }; await Write(modelTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", modelType.Name.ToPythonCase() + ".py")); } } //MethodGroups if (serviceClientTemplateModel.MethodGroupModels.Any()) { var methodGroupIndexTemplate = new MethodGroupInitTemplate { Model = serviceClientTemplateModel }; await Write(methodGroupIndexTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "operations", "__init__.py")); foreach (var methodGroupModel in serviceClientTemplateModel.MethodGroupModels) { var methodGroupTemplate = new MethodGroupTemplate { Model = methodGroupModel }; await Write(methodGroupTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "operations", methodGroupModel.MethodGroupType.ToPythonCase() + ".py")); } } // Enums if (serviceClient.EnumTypes.Any()) { var enumTemplate = new EnumTemplate { Model = new EnumTemplateModel(serviceClient.EnumTypes), }; await Write(enumTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", serviceClientTemplateModel.Name.ToPythonCase() + "_enums.py")); } } public static string BuildSummaryAndDescriptionString(string summary, string description) { StringBuilder builder = new StringBuilder(); if (!string.IsNullOrEmpty(summary)) { if (!summary.EndsWith(".", StringComparison.OrdinalIgnoreCase)) { summary += "."; } builder.AppendLine(summary); } if (!string.IsNullOrEmpty(summary) && !string.IsNullOrEmpty(description)) { builder.AppendLine(TemplateConstants.EmptyLine); } if (!string.IsNullOrEmpty(description)) { if (!description.EndsWith(".", StringComparison.OrdinalIgnoreCase)) { description += "."; } builder.Append(description); } return builder.ToString(); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the SysOrganismo class. /// </summary> [Serializable] public partial class SysOrganismoCollection : ActiveList<SysOrganismo, SysOrganismoCollection> { public SysOrganismoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SysOrganismoCollection</returns> public SysOrganismoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { SysOrganismo o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Sys_Organismo table. /// </summary> [Serializable] public partial class SysOrganismo : ActiveRecord<SysOrganismo>, IActiveRecord { #region .ctors and Default Settings public SysOrganismo() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public SysOrganismo(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public SysOrganismo(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public SysOrganismo(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Sys_Organismo", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdOrganismo = new TableSchema.TableColumn(schema); colvarIdOrganismo.ColumnName = "idOrganismo"; colvarIdOrganismo.DataType = DbType.Int32; colvarIdOrganismo.MaxLength = 0; colvarIdOrganismo.AutoIncrement = true; colvarIdOrganismo.IsNullable = false; colvarIdOrganismo.IsPrimaryKey = true; colvarIdOrganismo.IsForeignKey = false; colvarIdOrganismo.IsReadOnly = false; colvarIdOrganismo.DefaultSetting = @""; colvarIdOrganismo.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdOrganismo); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = 100; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Sys_Organismo",schema); } } #endregion #region Props [XmlAttribute("IdOrganismo")] [Bindable(true)] public int IdOrganismo { get { return GetColumnValue<int>(Columns.IdOrganismo); } set { SetColumnValue(Columns.IdOrganismo, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.ConAgendaGrupalOrganismoCollection colConAgendaGrupalOrganismoRecords; public DalSic.ConAgendaGrupalOrganismoCollection ConAgendaGrupalOrganismoRecords { get { if(colConAgendaGrupalOrganismoRecords == null) { colConAgendaGrupalOrganismoRecords = new DalSic.ConAgendaGrupalOrganismoCollection().Where(ConAgendaGrupalOrganismo.Columns.IdOrganismo, IdOrganismo).Load(); colConAgendaGrupalOrganismoRecords.ListChanged += new ListChangedEventHandler(colConAgendaGrupalOrganismoRecords_ListChanged); } return colConAgendaGrupalOrganismoRecords; } set { colConAgendaGrupalOrganismoRecords = value; colConAgendaGrupalOrganismoRecords.ListChanged += new ListChangedEventHandler(colConAgendaGrupalOrganismoRecords_ListChanged); } } void colConAgendaGrupalOrganismoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colConAgendaGrupalOrganismoRecords[e.NewIndex].IdOrganismo = IdOrganismo; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombre) { SysOrganismo item = new SysOrganismo(); item.Nombre = varNombre; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdOrganismo,string varNombre) { SysOrganismo item = new SysOrganismo(); item.IdOrganismo = varIdOrganismo; item.Nombre = varNombre; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdOrganismoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdOrganismo = @"idOrganismo"; public static string Nombre = @"nombre"; } #endregion #region Update PK Collections public void SetPKValues() { if (colConAgendaGrupalOrganismoRecords != null) { foreach (DalSic.ConAgendaGrupalOrganismo item in colConAgendaGrupalOrganismoRecords) { if (item.IdOrganismo != IdOrganismo) { item.IdOrganismo = IdOrganismo; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colConAgendaGrupalOrganismoRecords != null) { colConAgendaGrupalOrganismoRecords.SaveAll(); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace Flatbox.RegularExpressions.Tests { public class RegexMultipleMatchTests { [Fact] public void Matches_MultipleCapturingGroups() { string[] expectedGroupValues = { "abracadabra", "abra", "cad" }; string[] expectedGroupCaptureValues = { "abracad", "abra" }; // Another example - given by Brad Merril in an article on RegularExpressions Regex regex = new Regex(@"(abra(cad)?)+"); string input = "abracadabra1abracadabra2abracadabra3"; Match match = regex.Match(input); while (match.Success) { string expected = "abracadabra"; Assert.Equal(expected, match.Value); Assert.Equal(3, match.Groups.Count); for (int i = 0; i < match.Groups.Count; i++) { Assert.Equal(expectedGroupValues[i], match.Groups[i].Value); if (i == 1) { Assert.Equal(2, match.Groups[i].Captures.Count); for (int j = 0; j < match.Groups[i].Captures.Count; j++) { Assert.Equal(expectedGroupCaptureValues[j], match.Groups[i].Captures[j].Value); } } else if (i == 2) { Assert.Equal(1, match.Groups[i].Captures.Count); Assert.Equal("cad", match.Groups[i].Captures[0].Value); } } Assert.Equal(1, match.Captures.Count); Assert.Equal("abracadabra", match.Captures[0].Value); match = match.NextMatch(); } } public static IEnumerable<object[]> Matches_TestData() { yield return new object[] { "[0-9]", "12345asdfasdfasdfljkhsda67890", RegexOptions.None, new CaptureData[] { new CaptureData("1", 0, 1), new CaptureData("2", 1, 1), new CaptureData("3", 2, 1), new CaptureData("4", 3, 1), new CaptureData("5", 4, 1), new CaptureData("6", 24, 1), new CaptureData("7", 25, 1), new CaptureData("8", 26, 1), new CaptureData("9", 27, 1), new CaptureData("0", 28, 1), } }; yield return new object[] { "[a-z0-9]+", "[token1]? GARBAGEtoken2GARBAGE ;token3!", RegexOptions.None, new CaptureData[] { new CaptureData("token1", 1, 6), new CaptureData("token2", 17, 6), new CaptureData("token3", 32, 6) } }; yield return new object[] { "(abc){2}", " !abcabcasl dkfjasiduf 12343214-//asdfjzpiouxoifzuoxpicvql23r\\` #$3245,2345278 :asdfas & 100% @daeeffga (ryyy27343) poiweurwabcabcasdfalksdhfaiuyoiruqwer{234}/[(132387 + x)]'aaa''?", RegexOptions.None, new CaptureData[] { new CaptureData("abcabc", 2, 6), new CaptureData("abcabc", 125, 6) } }; yield return new object[] { @"foo\d+", "0123456789foo4567890foo1foo 0987", RegexOptions.RightToLeft, new CaptureData[] { new CaptureData("foo1", 20, 4), new CaptureData("foo4567890", 10, 10), } }; yield return new object[] { "[a-z]", "a", RegexOptions.None, new CaptureData[] { new CaptureData("a", 0, 1) } }; yield return new object[] { "[a-z]", "a1bc", RegexOptions.None, new CaptureData[] { new CaptureData("a", 0, 1), new CaptureData("b", 2, 1), new CaptureData("c", 3, 1) } }; // Alternation construct yield return new object[] { "(?(A)A123|C789)", "A123 B456 C789", RegexOptions.None, new CaptureData[] { new CaptureData("A123", 0, 4), new CaptureData("C789", 10, 4), } }; yield return new object[] { "(?(A)A123|C789)", "A123 B456 C789", RegexOptions.None, new CaptureData[] { new CaptureData("A123", 0, 4), new CaptureData("C789", 10, 4), } }; } [Theory] [MemberData(nameof(Matches_TestData))] public void Matches(string pattern, string input, RegexOptions options, CaptureData[] expected) { if (options == RegexOptions.None) { Regex regexBasic = new Regex(pattern); VerifyMatches(regexBasic.Matches(input), expected); VerifyMatches(regexBasic.Match(input), expected); VerifyMatches(Regex.Matches(input, pattern), expected); VerifyMatches(Regex.Match(input, pattern), expected); } Regex regexAdvanced = new Regex(pattern, options); VerifyMatches(regexAdvanced.Matches(input), expected); VerifyMatches(regexAdvanced.Match(input), expected); VerifyMatches(Regex.Matches(input, pattern, options), expected); VerifyMatches(Regex.Match(input, pattern, options), expected); } public static void VerifyMatches(Match match, CaptureData[] expected) { for (int i = 0; match.Success; i++, match = match.NextMatch()) { VerifyMatch(match, expected[i]); } } public static void VerifyMatches(MatchCollection matches, CaptureData[] expected) { Assert.Equal(expected.Length, matches.Count); for (int i = 0; i < matches.Count; i++) { VerifyMatch(matches[i], expected[i]); } } public static void VerifyMatch(Match match, CaptureData expected) { Assert.True(match.Success); Assert.Equal(expected.Value, match.Value); Assert.Equal(expected.Index, match.Index); Assert.Equal(expected.Length, match.Length); Assert.Equal(expected.Value, match.Groups[0].Value); Assert.Equal(expected.Index, match.Groups[0].Index); Assert.Equal(expected.Length, match.Groups[0].Length); Assert.Equal(1, match.Captures.Count); Assert.Equal(expected.Value, match.Captures[0].Value); Assert.Equal(expected.Index, match.Captures[0].Index); Assert.Equal(expected.Length, match.Captures[0].Length); } [Fact] public void Matches_Invalid() { // Input is null AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern")); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern", RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1))); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Matches(null)); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Matches(null, 0)); // Pattern is null AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null, RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null, RegexOptions.None, TimeSpan.FromSeconds(1))); // Options are invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)(-1))); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)(-1), TimeSpan.FromSeconds(1))); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)0x400)); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)0x400, TimeSpan.FromSeconds(1))); // MatchTimeout is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => Regex.Matches("input", "pattern", RegexOptions.None, TimeSpan.Zero)); AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => Regex.Matches("input", "pattern", RegexOptions.None, TimeSpan.Zero)); // Start is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Matches("input", -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Matches("input", 6)); } [Fact] public void NextMatch_EmptyMatch_ReturnsEmptyMatch() { Assert.Same(Match.Empty, Match.Empty.NextMatch()); } } }
// *********************************************************************** // Copyright (c) 2008-2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Builders; namespace NUnit.Framework { /// <summary> /// TestCaseSourceAttribute indicates the source to be used to /// provide test cases for a test method. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public class TestCaseSourceAttribute : NUnitAttribute, ITestBuilder, IImplyFixture { private NUnitTestCaseBuilder _builder = new NUnitTestCaseBuilder(); #region Constructors /// <summary> /// Construct with the name of the method, property or field that will provide data /// </summary> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> public TestCaseSourceAttribute(string sourceName) { this.SourceName = sourceName; } /// <summary> /// Construct with a Type and name /// </summary> /// <param name="sourceType">The Type that will provide data</param> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> /// <param name="methodParams">A set of parameters passed to the method, works only if the Source Name is a method. /// If the source name is a field or property has no effect.</param> public TestCaseSourceAttribute(Type sourceType, string sourceName, object[] methodParams) { this.MethodParams = methodParams; this.SourceType = sourceType; this.SourceName = sourceName; } /// <summary> /// Construct with a Type and name /// </summary> /// <param name="sourceType">The Type that will provide data</param> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> public TestCaseSourceAttribute(Type sourceType, string sourceName) { this.SourceType = sourceType; this.SourceName = sourceName; } /// <summary> /// Construct with a name /// </summary> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> /// <param name="methodParams">A set of parameters passed to the method, works only if the Source Name is a method. /// If the source name is a field or property has no effect.</param> public TestCaseSourceAttribute(string sourceName, object[] methodParams) { this.MethodParams = methodParams; this.SourceName = sourceName; } /// <summary> /// Construct with a Type /// </summary> /// <param name="sourceType">The type that will provide data</param> public TestCaseSourceAttribute(Type sourceType) { this.SourceType = sourceType; } #endregion #region Properties /// <summary> /// A set of parameters passed to the method, works only if the Source Name is a method. /// If the source name is a field or property has no effect. /// </summary> public object[] MethodParams { get; private set; } /// <summary> /// The name of a the method, property or fiend to be used as a source /// </summary> public string SourceName { get; private set; } /// <summary> /// A Type to be used as a source /// </summary> public Type SourceType { get; private set; } /// <summary> /// Gets or sets the category associated with every fixture created from /// this attribute. May be a single category or a comma-separated list. /// </summary> public string Category { get; set; } #endregion #region ITestBuilder Members /// <summary> /// Construct one or more TestMethods from a given MethodInfo, /// using available parameter data. /// </summary> /// <param name="method">The IMethod for which tests are to be constructed.</param> /// <param name="suite">The suite to which the tests will be added.</param> /// <returns>One or more TestMethods</returns> public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite) { foreach (TestCaseParameters parms in GetTestCasesFor(method)) yield return _builder.BuildTestMethod(method, suite, parms); } #endregion #region Helper Methods /// <summary> /// Returns a set of ITestCaseDataItems for use as arguments /// to a parameterized test method. /// </summary> /// <param name="method">The method for which data is needed.</param> /// <returns></returns> private IEnumerable<ITestCaseData> GetTestCasesFor(IMethodInfo method) { List<ITestCaseData> data = new List<ITestCaseData>(); try { IEnumerable source = GetTestCaseSource(method); if (source != null) { foreach (object item in source) { TestCaseParameters parms = null; // First handle two easy cases: // 1. Source is null. This is really an error but if we // throw an exception we simply get an invalid fixture // without good info as to what caused it. Passing a // single null argument will cause an error to be // reported at the test level, in most cases. if (item == null) parms = new TestCaseParameters(new object[] { null }); // 2. User provided an ITestCaseData and we just use it. if (item is ITestCaseData) parms = new TestCaseParameters(item as ITestCaseData); if (parms == null) { // 3. An array was passed, it may be an object[] // or possibly some other kind of array, which // TestCaseSource can accept. var args = item as object[]; if (args == null && item is Array) { Array array = item as Array; #if NETCF bool netcfOpenType = method.IsGenericMethodDefinition; #else bool netcfOpenType = false; #endif int numParameters = netcfOpenType ? array.Length : method.GetParameters().Length; if (array != null && array.Rank == 1 && array.Length == numParameters) { // Array is something like int[] - convert it to // an object[] for use as the argument array. args = new object[array.Length]; for (int i = 0; i < array.Length; i++) args[i] = array.GetValue(i); } } // Check again if we have an object[] if (args != null) { #if NETCF if (method.IsGenericMethodDefinition) { var mi = method.MakeGenericMethodEx(args); if (mi == null) throw new NotSupportedException("Cannot determine generic Type"); method = mi; } #endif var parameters = method.GetParameters(); var argsNeeded = parameters.Length; var argsProvided = args.Length; // If only one argument is needed, our array may actually // be the bare argument. If it is, we should wrap it in // an outer object[] representing the list of arguments. if (argsNeeded == 1) { var singleParmType = parameters[0].ParameterType; if (argsProvided == 0 || typeof(object[]).IsAssignableFrom(singleParmType)) { if (argsProvided > 1 || singleParmType.IsAssignableFrom(args.GetType())) { args = new object[] { item }; } } } } else // It may be a scalar or a multi-dimensioned array. Wrap it in object[] { args = new object[] { item }; } parms = new TestCaseParameters(args); } if (this.Category != null) foreach (string cat in this.Category.Split(new char[] { ',' })) parms.Properties.Add(PropertyNames.Category, cat); TestCaseAttribute.SpecialArgumentsHandling(parms, method.GetParameters()); data.Add(parms); } } } catch (Exception ex) { data.Clear(); data.Add(new TestCaseParameters(ex)); } return data; } private IEnumerable GetTestCaseSource(IMethodInfo method) { Type sourceType = SourceType ?? method.TypeInfo.Type; // Handle Type implementing IEnumerable separately if (SourceName == null) return Reflect.Construct(sourceType, null) as IEnumerable; MemberInfo[] members = sourceType.GetMember(SourceName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy); if (members.Length == 1) { MemberInfo member = members[0]; var field = member as FieldInfo; if (field != null) return field.IsStatic ? (MethodParams == null ? (IEnumerable)field.GetValue(null) : ReturnErrorAsParameter(ParamGivenToField)) : ReturnErrorAsParameter(SourceMustBeStatic); var property = member as PropertyInfo; if (property != null) return property.GetGetMethod(true).IsStatic ? (MethodParams == null ? (IEnumerable)property.GetValue(null, null) : ReturnErrorAsParameter(ParamGivenToProperty)) : ReturnErrorAsParameter(SourceMustBeStatic); var m = member as MethodInfo; if (m != null) return m.IsStatic ? (MethodParams == null || m.GetParameters().Length == MethodParams.Length ? (IEnumerable)m.Invoke(null, MethodParams) : ReturnErrorAsParameter(NumberOfArgsDoesNotMatch)) : ReturnErrorAsParameter(SourceMustBeStatic); } return null; } private static IEnumerable ReturnErrorAsParameter(string errorMessage) { var parms = new TestCaseParameters(); parms.RunState = RunState.NotRunnable; parms.Properties.Set(PropertyNames.SkipReason, errorMessage); return new TestCaseParameters[] { parms }; } private const string SourceMustBeStatic = "The sourceName specified on a TestCaseSourceAttribute must refer to a static field, property or method."; private const string ParamGivenToField = "You have specified a data source field but also given a set of parameters. Fields cannot take parameters, " + "please revise the 3rd parameter passed to the TestCaseSourceAttribute and either remove " + "it or specify a method."; private const string ParamGivenToProperty = "You have specified a data source property but also given a set of parameters. " + "Properties cannot take parameters, please revise the 3rd parameter passed to the " + "TestCaseSource attribute and either remove it or specify a method."; private const string NumberOfArgsDoesNotMatch = "You have given the wrong number of arguments to the method in the TestCaseSourceAttribute" + ", please check the number of parameters passed in the object is correct in the 3rd parameter for the " + "TestCaseSourceAttribute and this matches the number of parameters in the target method and try again."; #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 Apache.Ignite.Core.Impl.Cache.Query.Continuous { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Event; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Cache.Query.Continuous; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Resource; using Apache.Ignite.Core.Impl.Unmanaged; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; using CQU = ContinuousQueryUtils; /// <summary> /// Continuous query handle interface. /// </summary> internal interface IContinuousQueryHandleImpl : IDisposable { /// <summary> /// Process callback. /// </summary> /// <param name="stream">Stream.</param> /// <returns>Result.</returns> void Apply(IBinaryStream stream); } /// <summary> /// Continuous query handle. /// </summary> internal class ContinuousQueryHandleImpl<TK, TV> : IContinuousQueryHandleImpl, IContinuousQueryFilter, IContinuousQueryHandle<ICacheEntry<TK, TV>> { /** Marshaller. */ private readonly Marshaller _marsh; /** Keep binary flag. */ private readonly bool _keepBinary; /** Real listener. */ private readonly ICacheEntryEventListener<TK, TV> _lsnr; /** Real filter. */ private readonly ICacheEntryEventFilter<TK, TV> _filter; /** GC handle. */ private long _hnd; /** Native query. */ private volatile IUnmanagedTarget _nativeQry; /** Initial query cursor. */ private volatile IQueryCursor<ICacheEntry<TK, TV>> _initialQueryCursor; /** Disposed flag. */ private bool _disposed; /// <summary> /// Constructor. /// </summary> /// <param name="qry">Query.</param> /// <param name="marsh">Marshaller.</param> /// <param name="keepBinary">Keep binary flag.</param> public ContinuousQueryHandleImpl(ContinuousQuery<TK, TV> qry, Marshaller marsh, bool keepBinary) { _marsh = marsh; _keepBinary = keepBinary; _lsnr = qry.Listener; _filter = qry.Filter; } /// <summary> /// Start execution. /// </summary> /// <param name="grid">Ignite instance.</param> /// <param name="writer">Writer.</param> /// <param name="cb">Callback invoked when all necessary data is written to stream.</param> /// <param name="qry">Query.</param> public void Start(Ignite grid, BinaryWriter writer, Func<IUnmanagedTarget> cb, ContinuousQuery<TK, TV> qry) { // 1. Inject resources. ResourceProcessor.Inject(_lsnr, grid); ResourceProcessor.Inject(_filter, grid); // 2. Allocate handle. _hnd = grid.HandleRegistry.Allocate(this); // 3. Write data to stream. writer.WriteLong(_hnd); writer.WriteBoolean(qry.Local); writer.WriteBoolean(_filter != null); var filterHolder = _filter == null || qry.Local ? null : new ContinuousQueryFilterHolder(_filter, _keepBinary); writer.WriteObject(filterHolder); writer.WriteInt(qry.BufferSize); writer.WriteLong((long)qry.TimeInterval.TotalMilliseconds); writer.WriteBoolean(qry.AutoUnsubscribe); // 4. Call Java. _nativeQry = cb(); // 5. Initial query. var nativeInitialQryCur = UU.ContinuousQueryGetInitialQueryCursor(_nativeQry); _initialQueryCursor = nativeInitialQryCur == null ? null : new QueryCursor<TK, TV>(nativeInitialQryCur, _marsh, _keepBinary); } /** <inheritdoc /> */ public void Apply(IBinaryStream stream) { ICacheEntryEvent<TK, TV>[] evts = CQU.ReadEvents<TK, TV>(stream, _marsh, _keepBinary); _lsnr.OnEvent(evts); } /** <inheritdoc /> */ public bool Evaluate(IBinaryStream stream) { Debug.Assert(_filter != null, "Evaluate should not be called if filter is not set."); ICacheEntryEvent<TK, TV> evt = CQU.ReadEvent<TK, TV>(stream, _marsh, _keepBinary); return _filter.Evaluate(evt); } /** <inheritdoc /> */ public void Inject(Ignite grid) { throw new NotSupportedException("Should not be called."); } /** <inheritdoc /> */ public long Allocate() { throw new NotSupportedException("Should not be called."); } /** <inheritdoc /> */ public void Release() { _marsh.Ignite.HandleRegistry.Release(_hnd); } /** <inheritdoc /> */ public IQueryCursor<ICacheEntry<TK, TV>> GetInitialQueryCursor() { lock (this) { if (_disposed) throw new ObjectDisposedException("Continuous query handle has been disposed."); var cur = _initialQueryCursor; if (cur == null) throw new InvalidOperationException("GetInitialQueryCursor() can be called only once."); _initialQueryCursor = null; return cur; } } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "There is no finalizer.")] public void Dispose() { lock (this) { if (_disposed) return; Debug.Assert(_nativeQry != null); try { UU.ContinuousQueryClose(_nativeQry); } finally { _nativeQry.Dispose(); _disposed = true; } } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Analytics.Data.V1Beta.Snippets { using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedBetaAnalyticsDataClientSnippets { /// <summary>Snippet for RunReport</summary> public void RunReportRequestObject() { // Snippet: RunReport(RunReportRequest, CallSettings) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create(); // Initialize request argument(s) RunReportRequest request = new RunReportRequest { Property = "", Dimensions = { new Dimension(), }, Metrics = { new Metric(), }, DateRanges = { new DateRange(), }, DimensionFilter = new FilterExpression(), MetricFilter = new FilterExpression(), Offset = 0L, Limit = 0L, MetricAggregations = { MetricAggregation.Unspecified, }, OrderBys = { new OrderBy(), }, CurrencyCode = "", CohortSpec = new CohortSpec(), KeepEmptyRows = false, ReturnPropertyQuota = false, }; // Make the request RunReportResponse response = betaAnalyticsDataClient.RunReport(request); // End snippet } /// <summary>Snippet for RunReportAsync</summary> public async Task RunReportRequestObjectAsync() { // Snippet: RunReportAsync(RunReportRequest, CallSettings) // Additional: RunReportAsync(RunReportRequest, CancellationToken) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync(); // Initialize request argument(s) RunReportRequest request = new RunReportRequest { Property = "", Dimensions = { new Dimension(), }, Metrics = { new Metric(), }, DateRanges = { new DateRange(), }, DimensionFilter = new FilterExpression(), MetricFilter = new FilterExpression(), Offset = 0L, Limit = 0L, MetricAggregations = { MetricAggregation.Unspecified, }, OrderBys = { new OrderBy(), }, CurrencyCode = "", CohortSpec = new CohortSpec(), KeepEmptyRows = false, ReturnPropertyQuota = false, }; // Make the request RunReportResponse response = await betaAnalyticsDataClient.RunReportAsync(request); // End snippet } /// <summary>Snippet for RunPivotReport</summary> public void RunPivotReportRequestObject() { // Snippet: RunPivotReport(RunPivotReportRequest, CallSettings) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create(); // Initialize request argument(s) RunPivotReportRequest request = new RunPivotReportRequest { Property = "", Dimensions = { new Dimension(), }, Metrics = { new Metric(), }, DateRanges = { new DateRange(), }, Pivots = { new Pivot(), }, DimensionFilter = new FilterExpression(), MetricFilter = new FilterExpression(), CurrencyCode = "", CohortSpec = new CohortSpec(), KeepEmptyRows = false, ReturnPropertyQuota = false, }; // Make the request RunPivotReportResponse response = betaAnalyticsDataClient.RunPivotReport(request); // End snippet } /// <summary>Snippet for RunPivotReportAsync</summary> public async Task RunPivotReportRequestObjectAsync() { // Snippet: RunPivotReportAsync(RunPivotReportRequest, CallSettings) // Additional: RunPivotReportAsync(RunPivotReportRequest, CancellationToken) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync(); // Initialize request argument(s) RunPivotReportRequest request = new RunPivotReportRequest { Property = "", Dimensions = { new Dimension(), }, Metrics = { new Metric(), }, DateRanges = { new DateRange(), }, Pivots = { new Pivot(), }, DimensionFilter = new FilterExpression(), MetricFilter = new FilterExpression(), CurrencyCode = "", CohortSpec = new CohortSpec(), KeepEmptyRows = false, ReturnPropertyQuota = false, }; // Make the request RunPivotReportResponse response = await betaAnalyticsDataClient.RunPivotReportAsync(request); // End snippet } /// <summary>Snippet for BatchRunReports</summary> public void BatchRunReportsRequestObject() { // Snippet: BatchRunReports(BatchRunReportsRequest, CallSettings) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create(); // Initialize request argument(s) BatchRunReportsRequest request = new BatchRunReportsRequest { Property = "", Requests = { new RunReportRequest(), }, }; // Make the request BatchRunReportsResponse response = betaAnalyticsDataClient.BatchRunReports(request); // End snippet } /// <summary>Snippet for BatchRunReportsAsync</summary> public async Task BatchRunReportsRequestObjectAsync() { // Snippet: BatchRunReportsAsync(BatchRunReportsRequest, CallSettings) // Additional: BatchRunReportsAsync(BatchRunReportsRequest, CancellationToken) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync(); // Initialize request argument(s) BatchRunReportsRequest request = new BatchRunReportsRequest { Property = "", Requests = { new RunReportRequest(), }, }; // Make the request BatchRunReportsResponse response = await betaAnalyticsDataClient.BatchRunReportsAsync(request); // End snippet } /// <summary>Snippet for BatchRunPivotReports</summary> public void BatchRunPivotReportsRequestObject() { // Snippet: BatchRunPivotReports(BatchRunPivotReportsRequest, CallSettings) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create(); // Initialize request argument(s) BatchRunPivotReportsRequest request = new BatchRunPivotReportsRequest { Property = "", Requests = { new RunPivotReportRequest(), }, }; // Make the request BatchRunPivotReportsResponse response = betaAnalyticsDataClient.BatchRunPivotReports(request); // End snippet } /// <summary>Snippet for BatchRunPivotReportsAsync</summary> public async Task BatchRunPivotReportsRequestObjectAsync() { // Snippet: BatchRunPivotReportsAsync(BatchRunPivotReportsRequest, CallSettings) // Additional: BatchRunPivotReportsAsync(BatchRunPivotReportsRequest, CancellationToken) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync(); // Initialize request argument(s) BatchRunPivotReportsRequest request = new BatchRunPivotReportsRequest { Property = "", Requests = { new RunPivotReportRequest(), }, }; // Make the request BatchRunPivotReportsResponse response = await betaAnalyticsDataClient.BatchRunPivotReportsAsync(request); // End snippet } /// <summary>Snippet for GetMetadata</summary> public void GetMetadataRequestObject() { // Snippet: GetMetadata(GetMetadataRequest, CallSettings) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create(); // Initialize request argument(s) GetMetadataRequest request = new GetMetadataRequest { MetadataName = MetadataName.FromProperty("[PROPERTY]"), }; // Make the request Metadata response = betaAnalyticsDataClient.GetMetadata(request); // End snippet } /// <summary>Snippet for GetMetadataAsync</summary> public async Task GetMetadataRequestObjectAsync() { // Snippet: GetMetadataAsync(GetMetadataRequest, CallSettings) // Additional: GetMetadataAsync(GetMetadataRequest, CancellationToken) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync(); // Initialize request argument(s) GetMetadataRequest request = new GetMetadataRequest { MetadataName = MetadataName.FromProperty("[PROPERTY]"), }; // Make the request Metadata response = await betaAnalyticsDataClient.GetMetadataAsync(request); // End snippet } /// <summary>Snippet for GetMetadata</summary> public void GetMetadata() { // Snippet: GetMetadata(string, CallSettings) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create(); // Initialize request argument(s) string name = "properties/[PROPERTY]/metadata"; // Make the request Metadata response = betaAnalyticsDataClient.GetMetadata(name); // End snippet } /// <summary>Snippet for GetMetadataAsync</summary> public async Task GetMetadataAsync() { // Snippet: GetMetadataAsync(string, CallSettings) // Additional: GetMetadataAsync(string, CancellationToken) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync(); // Initialize request argument(s) string name = "properties/[PROPERTY]/metadata"; // Make the request Metadata response = await betaAnalyticsDataClient.GetMetadataAsync(name); // End snippet } /// <summary>Snippet for GetMetadata</summary> public void GetMetadataResourceNames() { // Snippet: GetMetadata(MetadataName, CallSettings) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create(); // Initialize request argument(s) MetadataName name = MetadataName.FromProperty("[PROPERTY]"); // Make the request Metadata response = betaAnalyticsDataClient.GetMetadata(name); // End snippet } /// <summary>Snippet for GetMetadataAsync</summary> public async Task GetMetadataResourceNamesAsync() { // Snippet: GetMetadataAsync(MetadataName, CallSettings) // Additional: GetMetadataAsync(MetadataName, CancellationToken) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync(); // Initialize request argument(s) MetadataName name = MetadataName.FromProperty("[PROPERTY]"); // Make the request Metadata response = await betaAnalyticsDataClient.GetMetadataAsync(name); // End snippet } /// <summary>Snippet for RunRealtimeReport</summary> public void RunRealtimeReportRequestObject() { // Snippet: RunRealtimeReport(RunRealtimeReportRequest, CallSettings) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create(); // Initialize request argument(s) RunRealtimeReportRequest request = new RunRealtimeReportRequest { Property = "", Dimensions = { new Dimension(), }, Metrics = { new Metric(), }, DimensionFilter = new FilterExpression(), MetricFilter = new FilterExpression(), Limit = 0L, MetricAggregations = { MetricAggregation.Unspecified, }, OrderBys = { new OrderBy(), }, ReturnPropertyQuota = false, MinuteRanges = { new MinuteRange(), }, }; // Make the request RunRealtimeReportResponse response = betaAnalyticsDataClient.RunRealtimeReport(request); // End snippet } /// <summary>Snippet for RunRealtimeReportAsync</summary> public async Task RunRealtimeReportRequestObjectAsync() { // Snippet: RunRealtimeReportAsync(RunRealtimeReportRequest, CallSettings) // Additional: RunRealtimeReportAsync(RunRealtimeReportRequest, CancellationToken) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync(); // Initialize request argument(s) RunRealtimeReportRequest request = new RunRealtimeReportRequest { Property = "", Dimensions = { new Dimension(), }, Metrics = { new Metric(), }, DimensionFilter = new FilterExpression(), MetricFilter = new FilterExpression(), Limit = 0L, MetricAggregations = { MetricAggregation.Unspecified, }, OrderBys = { new OrderBy(), }, ReturnPropertyQuota = false, MinuteRanges = { new MinuteRange(), }, }; // Make the request RunRealtimeReportResponse response = await betaAnalyticsDataClient.RunRealtimeReportAsync(request); // End snippet } /// <summary>Snippet for CheckCompatibility</summary> public void CheckCompatibilityRequestObject() { // Snippet: CheckCompatibility(CheckCompatibilityRequest, CallSettings) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create(); // Initialize request argument(s) CheckCompatibilityRequest request = new CheckCompatibilityRequest { Property = "", Dimensions = { new Dimension(), }, Metrics = { new Metric(), }, DimensionFilter = new FilterExpression(), MetricFilter = new FilterExpression(), CompatibilityFilter = Compatibility.Unspecified, }; // Make the request CheckCompatibilityResponse response = betaAnalyticsDataClient.CheckCompatibility(request); // End snippet } /// <summary>Snippet for CheckCompatibilityAsync</summary> public async Task CheckCompatibilityRequestObjectAsync() { // Snippet: CheckCompatibilityAsync(CheckCompatibilityRequest, CallSettings) // Additional: CheckCompatibilityAsync(CheckCompatibilityRequest, CancellationToken) // Create client BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync(); // Initialize request argument(s) CheckCompatibilityRequest request = new CheckCompatibilityRequest { Property = "", Dimensions = { new Dimension(), }, Metrics = { new Metric(), }, DimensionFilter = new FilterExpression(), MetricFilter = new FilterExpression(), CompatibilityFilter = Compatibility.Unspecified, }; // Make the request CheckCompatibilityResponse response = await betaAnalyticsDataClient.CheckCompatibilityAsync(request); // End snippet } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Sql.Fluent { using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions; using Microsoft.Azure.Management.Sql.Fluent.SqlChildrenOperations.SqlChildrenActionsDefinition; using Microsoft.Azure.Management.Sql.Fluent.SqlSyncGroupOperations.Definition; using Microsoft.Azure.Management.Sql.Fluent.SqlSyncGroupOperations.SqlSyncGroupActionsDefinition; using System; /// <summary> /// Implementation for SQL Sync Group operations. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LnNxbC5pbXBsZW1lbnRhdGlvbi5TcWxTeW5jR3JvdXBPcGVyYXRpb25zSW1wbA== internal partial class SqlSyncGroupOperationsImpl : ISqlSyncGroupOperations, ISqlSyncGroupActionsDefinition { protected ISqlManager sqlServerManager; protected string resourceGroupName; protected string sqlServerName; protected string sqlDatabaseName; protected SqlDatabaseImpl sqlDatabase; ///GENMHASH:3FC4629A94EA4CFEC41549C1F3C77668:8133340974DB918052A51C4316313E0B internal SqlSyncGroupOperationsImpl(SqlDatabaseImpl parent, ISqlManager sqlServerManager) { this.sqlDatabase = parent; this.sqlServerManager = sqlServerManager; this.resourceGroupName = parent.ResourceGroupName(); this.sqlServerName = parent.SqlServerName(); this.sqlDatabaseName = parent.Name(); } ///GENMHASH:9C2A175D65B3AA9BD179F1242A5E83B1:B9438CBADF67F717E9124756C880E7E3 internal SqlSyncGroupOperationsImpl(ISqlManager sqlServerManager) { this.sqlServerManager = sqlServerManager; } ///GENMHASH:B2B2B8F5736EAA955B6B55C297214E20:7A83944268F46EC175944AA700D1EF68 public async Task<IEnumerable<string>> ListSyncDatabaseIdsAsync(string locationName, CancellationToken cancellationToken = default(CancellationToken)) { List<string> syncDatabaseIdProperties = new List<string>(); var syncDatabaseIdPropertiesInners = await this.sqlServerManager.Inner.SyncGroups .ListSyncDatabaseIdsAsync(locationName, cancellationToken: cancellationToken); if (syncDatabaseIdPropertiesInners != null) { foreach (var syncDatabaseIdPropertiesInner in syncDatabaseIdPropertiesInners) { syncDatabaseIdProperties.Add(syncDatabaseIdPropertiesInner.Id); } } return syncDatabaseIdProperties.AsReadOnly(); } ///GENMHASH:3CD1F7482E9E8D57064F7FFA885C9443:262DD8CDE3B60A8F793BC3FBC13997AF public async Task<IEnumerable<string>> ListSyncDatabaseIdsAsync(Region region, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ListSyncDatabaseIdsAsync(region.Name, cancellationToken); } ///GENMHASH:4D33A73A344E127F784620E76B686786:3EFE936B2516F1A1DC72FD223B7C5857 public async Task DeleteByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken)) { if (id == null) { throw new ArgumentNullException(id); } var resourceId = ResourceId.FromString(id); await this.sqlServerManager.Inner.SyncGroups .DeleteAsync(resourceId.ResourceGroupName, resourceId.Parent.Parent.Name, resourceId.Parent.Name, resourceId.Name, cancellationToken); } ///GENMHASH:BEDEF34E57C25BFA34A4AB1C8430428E:1BEF321A7DF2B0978C4F56E3EAE72F1D public async Task DeleteAsync(string name, CancellationToken cancellationToken = default(CancellationToken)) { if (this.sqlDatabase == null) { return; } await this.sqlServerManager.Inner.SyncGroups .DeleteAsync(this.sqlDatabase.ResourceGroupName(), this.sqlDatabase.SqlServerName(), this.sqlDatabase.Name(), name, cancellationToken); } ///GENMHASH:AF8385463FD062B3C56A3F22F51DFEE4:1B42309E30131D730BB11A008DC5155B public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlSyncGroup> GetAsync(string name, CancellationToken cancellationToken = default(CancellationToken)) { if (this.sqlDatabase == null) { return null; } return await this.GetBySqlServerAsync(this.sqlDatabase.ResourceGroupName(), this.sqlDatabase.SqlServerName(), this.sqlDatabase.Name(), name, cancellationToken); } ///GENMHASH:7D6013E8B95E991005ED921F493EFCE4:82CB51D9E702504B0BB2055AB2FE5C2E public IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlSyncGroup> List() { return Extensions.Synchronize(() => this.ListAsync()); } ///GENMHASH:72B167BB049FE51DB5B8083E64CB40DC:EB53EBC03053F0CE299B82EBA3750086 public IEnumerable<string> ListSyncDatabaseIds(string locationName) { return Extensions.Synchronize(() => this.ListSyncDatabaseIdsAsync(locationName)); } ///GENMHASH:DEE1795636C121ED4A09DB3E168AD680:6855193ED00ADA0BF5C781DBF6E8B5B2 public IEnumerable<string> ListSyncDatabaseIds(Region region) { return Extensions.Synchronize(() => this.ListSyncDatabaseIdsAsync(region.Name)); } ///GENMHASH:184FEA122A400D19B34517FEF358ED78:2B77326A14C3E8373051D77E2DDE3136 public void Delete(string name) { Extensions.Synchronize(() => this.DeleteAsync(name)); } ///GENMHASH:634DD8CD411508E79BD0EE40A623FCA3:7EB51BE3FE7CCB3478933AF6B330F607 public ISqlSyncGroup GetBySqlServer(string resourceGroupName, string sqlServerName, string databaseName, string name) { return Extensions.Synchronize(() => this.GetBySqlServerAsync(resourceGroupName, sqlServerName, databaseName, name)); } ///GENMHASH:5002116800CBAC02BBC1B4BF62BC4942:102DA0863A9F7ADA031615BC8A7EEB38 public ISqlSyncGroup GetById(string id) { if (id == null) { throw new ArgumentNullException(id); } var resourceId = ResourceId.FromString(id); return this.GetBySqlServer(resourceId.ResourceGroupName, resourceId.Parent.Parent.Name, resourceId.Parent.Name, resourceId.Name); } ///GENMHASH:206E829E50B031B66F6EA9C7402231F9:87595AD99EF4B1BE16FAF71135180FA9 public ISqlSyncGroup Get(string name) { if (this.sqlDatabase == null) { return null; } return this.GetBySqlServer(this.sqlDatabase.ResourceGroupName(), this.sqlDatabase.SqlServerName(), this.sqlDatabase.Name(), name); } ///GENMHASH:E776888E46F8A3FC56D24DF4A74E5B74:2514AD4015276121B15CE4CC444256B6 public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlSyncGroup> GetByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken)) { if (id == null) { throw new ArgumentNullException(id); } var resourceId = ResourceId.FromString(id); return await this.GetBySqlServerAsync(resourceId.ResourceGroupName, resourceId.Parent.Parent.Name, resourceId.Parent.Name, resourceId.Name, cancellationToken); } ///GENMHASH:02608B45CAA81355380819DD3EAA1DFB:34B2990F9E19C36265E12F2621574371 public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlSyncGroup> GetBySqlServerAsync(string resourceGroupName, string sqlServerName, string databaseName, string name, CancellationToken cancellationToken = default(CancellationToken)) { var syncGroupInner = await this.sqlServerManager.Inner.SyncGroups .GetAsync(resourceGroupName, sqlServerName, databaseName, name, cancellationToken); return syncGroupInner != null ? new SqlSyncGroupImpl(resourceGroupName, sqlServerName, databaseName, name, syncGroupInner, sqlServerManager) : null; } ///GENMHASH:8ACFB0E23F5F24AD384313679B65F404:AAFB116D45DCF8ADB3D006750373417E public SqlSyncGroupImpl Define(string name) { SqlSyncGroupImpl result = new SqlSyncGroupImpl(name, new Models.SyncGroupInner(), this.sqlServerManager); return (this.sqlDatabase != null) ? result.WithExistingSqlDatabase(this.sqlDatabase) : result; } ///GENMHASH:CFA8F482B43AF8D63CC08E2DEC651ED3:00B47599BF2DE4AD280FC21725DD6888 public void DeleteById(string id) { Extensions.Synchronize(() => this.DeleteByIdAsync(id)); } ///GENMHASH:7F5BEBF638B801886F5E13E6CCFF6A4E:6E8560C4CFD45325BAB666227553CDAE public async Task<IReadOnlyList<ISqlSyncGroup>> ListAsync(CancellationToken cancellationToken = default(CancellationToken)) { List<ISqlSyncGroup> syncGroups = new List<ISqlSyncGroup>(); if (this.sqlDatabase != null) { var syncGroupInners = await this.sqlServerManager.Inner.SyncGroups .ListByDatabaseAsync(this.sqlDatabase.ResourceGroupName(), this.sqlDatabase.SqlServerName(), this.sqlDatabase.Name(), cancellationToken); if (syncGroupInners != null) { foreach (var syncGroupInner in syncGroupInners) { syncGroups.Add(new SqlSyncGroupImpl(syncGroupInner.Name, this.sqlDatabase, syncGroupInner, this.sqlServerManager)); } } } return syncGroups.AsReadOnly(); } } }
// 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()); FileAttributes original = testDir.Attributes; try { testDir.Attributes = attributes; Assert.Equal(testDir.FullName, Create(testDir.FullName).FullName); } finally { testDir.Attributes = original; } } [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 = IOInputs.ExtendedPrefix + 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)); }); } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(PlatformID.Windows)] public void DirectoryLongerThanMaxPath_Succeeds() { var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath()); Assert.All(paths, (path) => { DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void DirectoryLongerThanMaxLongPath_ThrowsPathTooLongException() { var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath()); Assert.All(paths, (path) => { Assert.Throws<PathTooLongException>(() => Create(path)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] [OuterLoop] // takes more than a minute public void DirectoryLongerThanMaxLongPathWithExtendedSyntax_ThrowsPathTooLongException() { var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath(), useExtendedSyntax: true); Assert.All(paths, (path) => { Assert.Throws<PathTooLongException>(() => Create(path)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void ExtendedDirectoryLongerThanLegacyMaxPath_Succeeds() { var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath(), useExtendedSyntax: true); Assert.All(paths, (path) => { Assert.True(Create(path).Exists); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void DirectoryLongerThanMaxDirectoryAsPath_Succeeds() { var paths = IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath()); Assert.All(paths, (path) => { var result = Create(path); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] 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 UnixPathWithDeeplyNestedDirectories() { DirectoryInfo parent = Create(GetTestFilePath()); for (int i = 1; i <= 100; i++) // 100 == arbitrarily large number of directories { parent = Create(Path.Combine(parent.FullName, "dir" + i)); Assert.True(Directory.Exists(parent.FullName)); } } [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(IOInputs.ExtendedPrefix + directory.Path, path); Directory.CreateDirectory(extendedPath); Assert.True(Directory.Exists(extendedPath), 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)] // device name prefixes public void PathWithReservedDeviceNameAsExtendedPath() { var paths = IOInputs.GetReservedDeviceNames(); using (TemporaryDirectory directory = new TemporaryDirectory()) { Assert.All(paths, (path) => { Assert.True(Create(IOInputs.ExtendedPrefix + Path.Combine(directory.Path, path)).Exists, 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)] // UNC shares public void UNCPathWithOnlySlashes() { Assert.Throws<ArgumentException>(() => Create("//")); } [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 } }
// 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; namespace System.Numerics { internal static partial class BigIntegerCalculator { // Executes different exponentiation algorithms, which are // based on the classic square-and-multiply method. // https://en.wikipedia.org/wiki/Exponentiation_by_squaring public static uint[] Pow(uint value, uint power) { // The basic pow method for a 32-bit integer. // To spare memory allocations we first roughly // estimate an upper bound for our buffers. int size = PowBound(power, 1, 1); BitsBuffer v = new BitsBuffer(size, value); return PowCore(power, ref v); } public static uint[] Pow(uint[] value, uint power) { Debug.Assert(value != null); // The basic pow method for a big integer. // To spare memory allocations we first roughly // estimate an upper bound for our buffers. int size = PowBound(power, value.Length, 1); BitsBuffer v = new BitsBuffer(size, value); return PowCore(power, ref v); } private static uint[] PowCore(uint power, ref BitsBuffer value) { // Executes the basic pow algorithm. int size = value.GetSize(); BitsBuffer temp = new BitsBuffer(size, 0); BitsBuffer result = new BitsBuffer(size, 1); PowCore(power, ref value, ref result, ref temp); return result.GetBits(); } private static int PowBound(uint power, int valueLength, int resultLength) { // The basic pow algorithm, but instead of squaring // and multiplying we just sum up the lengths. while (power != 0) { checked { if ((power & 1) == 1) resultLength += valueLength; if (power != 1) valueLength += valueLength; } power = power >> 1; } return resultLength; } private static void PowCore(uint power, ref BitsBuffer value, ref BitsBuffer result, ref BitsBuffer temp) { // The basic pow algorithm using square-and-multiply. while (power != 0) { if ((power & 1) == 1) result.MultiplySelf(ref value, ref temp); if (power != 1) value.SquareSelf(ref temp); power = power >> 1; } } public static uint Pow(uint value, uint power, uint modulus) { // The 32-bit modulus pow method for a 32-bit integer // raised by a 32-bit integer... return PowCore(power, modulus, value, 1); } public static uint Pow(uint[] value, uint power, uint modulus) { Debug.Assert(value != null); // The 32-bit modulus pow method for a big integer // raised by a 32-bit integer... uint v = Remainder(value, modulus); return PowCore(power, modulus, v, 1); } public static uint Pow(uint value, uint[] power, uint modulus) { Debug.Assert(power != null); // The 32-bit modulus pow method for a 32-bit integer // raised by a big integer... return PowCore(power, modulus, value, 1); } public static uint Pow(uint[] value, uint[] power, uint modulus) { Debug.Assert(value != null); Debug.Assert(power != null); // The 32-bit modulus pow method for a big integer // raised by a big integer... uint v = Remainder(value, modulus); return PowCore(power, modulus, v, 1); } private static uint PowCore(uint[] power, uint modulus, ulong value, ulong result) { // The 32-bit modulus pow algorithm for all but // the last power limb using square-and-multiply. for (int i = 0; i < power.Length - 1; i++) { uint p = power[i]; for (int j = 0; j < 32; j++) { if ((p & 1) == 1) result = (result * value) % modulus; value = (value * value) % modulus; p = p >> 1; } } return PowCore(power[power.Length - 1], modulus, value, result); } private static uint PowCore(uint power, uint modulus, ulong value, ulong result) { // The 32-bit modulus pow algorithm for the last or // the only power limb using square-and-multiply. while (power != 0) { if ((power & 1) == 1) result = (result * value) % modulus; if (power != 1) value = (value * value) % modulus; power = power >> 1; } return (uint)(result % modulus); } public static uint[] Pow(uint value, uint power, uint[] modulus) { Debug.Assert(modulus != null); // The big modulus pow method for a 32-bit integer // raised by a 32-bit integer... int size = modulus.Length + modulus.Length; BitsBuffer v = new BitsBuffer(size, value); return PowCore(power, modulus, ref v); } public static uint[] Pow(uint[] value, uint power, uint[] modulus) { Debug.Assert(value != null); Debug.Assert(modulus != null); // The big modulus pow method for a big integer // raised by a 32-bit integer... if (value.Length > modulus.Length) value = Remainder(value, modulus); int size = modulus.Length + modulus.Length; BitsBuffer v = new BitsBuffer(size, value); return PowCore(power, modulus, ref v); } public static uint[] Pow(uint value, uint[] power, uint[] modulus) { Debug.Assert(power != null); Debug.Assert(modulus != null); // The big modulus pow method for a 32-bit integer // raised by a big integer... int size = modulus.Length + modulus.Length; BitsBuffer v = new BitsBuffer(size, value); return PowCore(power, modulus, ref v); } public static uint[] Pow(uint[] value, uint[] power, uint[] modulus) { Debug.Assert(value != null); Debug.Assert(power != null); Debug.Assert(modulus != null); // The big modulus pow method for a big integer // raised by a big integer... if (value.Length > modulus.Length) value = Remainder(value, modulus); int size = modulus.Length + modulus.Length; BitsBuffer v = new BitsBuffer(size, value); return PowCore(power, modulus, ref v); } // Mutable for unit testing... private static int ReducerThreshold = 32; private static uint[] PowCore(uint[] power, uint[] modulus, ref BitsBuffer value) { // Executes the big pow algorithm. int size = value.GetSize(); BitsBuffer temp = new BitsBuffer(size, 0); BitsBuffer result = new BitsBuffer(size, 1); if (modulus.Length < ReducerThreshold) { PowCore(power, modulus, ref value, ref result, ref temp); } else { FastReducer reducer = new FastReducer(modulus); PowCore(power, ref reducer, ref value, ref result, ref temp); } return result.GetBits(); } private static uint[] PowCore(uint power, uint[] modulus, ref BitsBuffer value) { // Executes the big pow algorithm. int size = value.GetSize(); BitsBuffer temp = new BitsBuffer(size, 0); BitsBuffer result = new BitsBuffer(size, 1); if (modulus.Length < ReducerThreshold) { PowCore(power, modulus, ref value, ref result, ref temp); } else { FastReducer reducer = new FastReducer(modulus); PowCore(power, ref reducer, ref value, ref result, ref temp); } return result.GetBits(); } private static void PowCore(uint[] power, uint[] modulus, ref BitsBuffer value, ref BitsBuffer result, ref BitsBuffer temp) { // The big modulus pow algorithm for all but // the last power limb using square-and-multiply. // NOTE: we're using an ordinary remainder here, // since the reducer overhead doesn't pay off. for (int i = 0; i < power.Length - 1; i++) { uint p = power[i]; for (int j = 0; j < 32; j++) { if ((p & 1) == 1) { result.MultiplySelf(ref value, ref temp); result.Reduce(modulus); } value.SquareSelf(ref temp); value.Reduce(modulus); p = p >> 1; } } PowCore(power[power.Length - 1], modulus, ref value, ref result, ref temp); } private static void PowCore(uint power, uint[] modulus, ref BitsBuffer value, ref BitsBuffer result, ref BitsBuffer temp) { // The big modulus pow algorithm for the last or // the only power limb using square-and-multiply. // NOTE: we're using an ordinary remainder here, // since the reducer overhead doesn't pay off. while (power != 0) { if ((power & 1) == 1) { result.MultiplySelf(ref value, ref temp); result.Reduce(modulus); } if (power != 1) { value.SquareSelf(ref temp); value.Reduce(modulus); } power = power >> 1; } } private static void PowCore(uint[] power, ref FastReducer reducer, ref BitsBuffer value, ref BitsBuffer result, ref BitsBuffer temp) { // The big modulus pow algorithm for all but // the last power limb using square-and-multiply. // NOTE: we're using a special reducer here, // since it's additional overhead does pay off. for (int i = 0; i < power.Length - 1; i++) { uint p = power[i]; for (int j = 0; j < 32; j++) { if ((p & 1) == 1) { result.MultiplySelf(ref value, ref temp); result.Reduce(ref reducer); } value.SquareSelf(ref temp); value.Reduce(ref reducer); p = p >> 1; } } PowCore(power[power.Length - 1], ref reducer, ref value, ref result, ref temp); } private static void PowCore(uint power, ref FastReducer reducer, ref BitsBuffer value, ref BitsBuffer result, ref BitsBuffer temp) { // The big modulus pow algorithm for the last or // the only power limb using square-and-multiply. // NOTE: we're using a special reducer here, // since it's additional overhead does pay off. while (power != 0) { if ((power & 1) == 1) { result.MultiplySelf(ref value, ref temp); result.Reduce(ref reducer); } if (power != 1) { value.SquareSelf(ref temp); value.Reduce(ref reducer); } power = power >> 1; } } private static int ActualLength(uint[] value) { // Since we're reusing memory here, the actual length // of a given value may be less then the array's length return ActualLength(value, value.Length); } private static int ActualLength(uint[] value, int length) { Debug.Assert(value != null); Debug.Assert(length <= value.Length); while (length > 0 && value[length - 1] == 0) --length; return length; } } }
// 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. #define DEBUG // The behavior of this contract library should be consistent regardless of build type. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Reflection; using DeveloperExperience = Internal.DeveloperExperience.DeveloperExperience; #if FEATURE_RELIABILITY_CONTRACTS using System.Runtime.ConstrainedExecution; #endif #if FEATURE_UNTRUSTED_CALLERS using System.Security; using System.Security.Permissions; #endif namespace System.Diagnostics.Contracts { public static partial class Contract { #region Private Methods [ThreadStatic] private static bool t_assertingMustUseRewriter; /// <summary> /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// </summary> #if FEATURE_UNTRUSTED_CALLERS #endif static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind) { //TODO: Implement CodeContract failure mechanics including enabling CCIRewrite if (t_assertingMustUseRewriter) { System.Diagnostics.Debug.Fail("Asserting that we must use the rewriter went reentrant. Didn't rewrite this System.Private.CoreLib?"); return; } t_assertingMustUseRewriter = true; //// For better diagnostics, report which assembly is at fault. Walk up stack and //// find the first non-mscorlib assembly. //Assembly thisAssembly = typeof(Contract).Assembly; // In case we refactor mscorlib, use Contract class instead of Object. //StackTrace stack = new StackTrace(); //Assembly probablyNotRewritten = null; //for (int i = 0; i < stack.FrameCount; i++) //{ // Assembly caller = stack.GetFrame(i).GetMethod().DeclaringType.Assembly; // if (caller != thisAssembly) // { // probablyNotRewritten = caller; // break; // } //} //if (probablyNotRewritten == null) // probablyNotRewritten = thisAssembly; //String simpleName = probablyNotRewritten.GetName().Name; String simpleName = "System.Private.CoreLib"; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null); t_assertingMustUseRewriter = false; } #endregion Private Methods #region Failure Behavior /// <summary> /// Without contract rewriting, failing Assert/Assumes end up calling this method. /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// </summary> [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); Contract.EndContractBlock(); // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message String displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); if (displayMessage == null) return; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException); } #if !FEATURE_CORECLR /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) /// to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust, because it will inform you of bugs in the appdomain and because the event handler /// could allow you to continue execution. /// </summary> public static event EventHandler<ContractFailedEventArgs> ContractFailed { #if FEATURE_UNTRUSTED_CALLERS #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif add { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value; } #if FEATURE_UNTRUSTED_CALLERS #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif remove { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value; } } #endif // !FEATURE_CORECLR #endregion FailureBehavior } #if !FEATURE_CORECLR // Not usable on Silverlight by end users due to security, and full trust users have not yet expressed an interest. public sealed class ContractFailedEventArgs : EventArgs { private ContractFailureKind _failureKind; private String _message; private String _condition; private Exception _originalException; private bool _handled; private bool _unwind; internal Exception thrownDuringHandler; #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException) { Contract.Requires(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); _failureKind = failureKind; _message = message; _condition = condition; _originalException = originalException; } public String Message { get { return _message; } } public String Condition { get { return _condition; } } public ContractFailureKind FailureKind { get { return _failureKind; } } public Exception OriginalException { get { return _originalException; } } // Whether the event handler "handles" this contract failure, or to fail via escalation policy. public bool Handled { get { return _handled; } } #if FEATURE_UNTRUSTED_CALLERS #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif public void SetHandled() { _handled = true; } public bool Unwind { get { return _unwind; } } #if FEATURE_UNTRUSTED_CALLERS #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif public void SetUnwind() { _unwind = true; } } #endif // !FEATURE_CORECLR [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] // Needs to be public for type forwarding serialization support. public sealed class ContractException : Exception { private readonly ContractFailureKind _kind; private readonly string _userMessage; private readonly string _condition; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public ContractFailureKind Kind { get { return _kind; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Failure { get { return this.Message; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string UserMessage { get { return _userMessage; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Condition { get { return _condition; } } // Called by COM Interop, if we see COR_E_CODECONTRACTFAILED as an HRESULT. private ContractException() { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; } public ContractException(ContractFailureKind kind, string failure, string userMessage, string condition, Exception innerException) : base(failure, innerException) { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; _kind = kind; _userMessage = userMessage; _condition = condition; } private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { _kind = (ContractFailureKind)info.GetInt32("Kind"); _userMessage = info.GetString("UserMessage"); _condition = info.GetString("Condition"); } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Kind", _kind); info.AddValue("UserMessage", _userMessage); info.AddValue("Condition", _condition); } } } namespace System.Runtime.CompilerServices { public static partial class ContractHelper { #region Private fields #if !FEATURE_CORECLR private static volatile EventHandler<ContractFailedEventArgs> s_contractFailedEvent; private static readonly Object s_lockObject = new Object(); #endif // !FEATURE_CORECLR internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); #endregion #if !FEATURE_CORECLR /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) or a /// web browser host (Jolt hosting Silverlight in IE) to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust. /// </summary> internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed { #if FEATURE_UNTRUSTED_CALLERS #endif add { // Eagerly prepare each event handler _marked with a reliability contract_, to // attempt to reduce out of memory exceptions while reporting contract violations. // This only works if the new handler obeys the constraints placed on // constrained execution regions. Eagerly preparing non-reliable event handlers // would be a perf hit and wouldn't significantly improve reliability. // UE: Please mention reliable event handlers should also be marked with the // PrePrepareMethodAttribute to avoid CER eager preparation work when ngen'ed. //#if !FEATURE_CORECLR // System.Runtime.CompilerServices.RuntimeHelpers.PrepareContractedDelegate(value); //#endif lock (s_lockObject) { s_contractFailedEvent += value; } } #if FEATURE_UNTRUSTED_CALLERS #endif remove { lock (s_lockObject) { s_contractFailedEvent -= value; } } } #endif // !FEATURE_CORECLR /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// This method has 3 functions: /// 1. Call any contract hooks (such as listeners to Contract failed events) /// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null) /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently. /// </summary> /// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough. /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</param> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS #endif static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); Contract.EndContractBlock(); string returnValue; String displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... #if !FEATURE_CORECLR ContractFailedEventArgs eventArgs = null; // In case of OOM. #endif // !FEATURE_CORECLR #if FEATURE_RELIABILITY_CONTRACTS System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif try { displayMessage = GetDisplayMessage(failureKind, userMessage, conditionText); #if !FEATURE_CORECLR if (s_contractFailedEvent != null) { eventArgs = new ContractFailedEventArgs(failureKind, displayMessage, conditionText, innerException); foreach (EventHandler<ContractFailedEventArgs> handler in s_contractFailedEvent.GetInvocationList()) { try { handler(null, eventArgs); } catch (Exception e) { eventArgs.thrownDuringHandler = e; eventArgs.SetUnwind(); } } if (eventArgs.Unwind) { //if (Environment.IsCLRHosted) // TriggerCodeContractEscalationPolicy(failureKind, displayMessage, conditionText, innerException); // unwind if (innerException == null) { innerException = eventArgs.thrownDuringHandler; } throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException); } } #endif // !FEATURE_CORECLR } finally { #if !FEATURE_CORECLR if (eventArgs != null && eventArgs.Handled) { returnValue = null; // handled } else #endif // !FEATURE_CORECLR { returnValue = displayMessage; } } resultFailureMessage = returnValue; } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "conditionText")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "innerException")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_UNTRUSTED_CALLERS && !FEATURE_CORECLR #endif static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { // If we're here, our intent is to pop up a dialog box (if we can). For developers // interacting live with a debugger, this is a good experience. For Silverlight // hosted in Internet Explorer, the assert window is great. If we cannot // pop up a dialog box, throw an exception (consider a library compiled with // "Assert On Failure" but used in a process that can't pop up asserts, like an // NT Service). For the CLR hosted by server apps like SQL or Exchange, we should // trigger escalation policy. //#if !FEATURE_CORECLR // if (Environment.IsCLRHosted) // { // TriggerCodeContractEscalationPolicy(kind, displayMessage, conditionText, innerException); // // Hosts like SQL may choose to abort the thread, so we will not get here in all cases. // // But if the host's chosen action was to throw an exception, we should throw an exception // // here (which is easier to do in managed code with the right parameters). // throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); // } //#endif // !FEATURE_CORECLR //TODO: Implement CodeContract failure mechanics including enabling CCIRewrite String stackTrace = null; //@todo: Any reasonable way to get a stack trace here? bool userSelectedIgnore = DeveloperExperience.Default.OnContractFailure(stackTrace, kind, displayMessage, userMessage, conditionText, innerException); if (userSelectedIgnore) return; //if (!Environment.UserInteractive) { throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); //} //// May need to rethink Assert.Fail w/ TaskDialogIndirect as a model. Window title. Main instruction. Content. Expanded info. //// Optional info like string for collapsed text vs. expanded text. //String windowTitle = SR.Format(GetResourceNameForFailure(kind)); //const int numStackFramesToSkip = 2; // To make stack traces easier to read //System.Diagnostics.Debug.Assert(conditionText, displayMessage, windowTitle, COR_E_CODECONTRACTFAILED, StackTrace.TraceFormat.Normal, numStackFramesToSkip); // If we got here, the user selected Ignore. Continue. } private static String GetFailureMessage(ContractFailureKind failureKind, String conditionText) { bool hasConditionText = !String.IsNullOrEmpty(conditionText); switch (failureKind) { case ContractFailureKind.Assert: return hasConditionText ? SR.Format(SR.AssertionFailed_Cnd, conditionText) : SR.AssertionFailed; case ContractFailureKind.Assume: return hasConditionText ? SR.Format(SR.AssumptionFailed_Cnd, conditionText) : SR.AssumptionFailed; case ContractFailureKind.Precondition: return hasConditionText ? SR.Format(SR.PreconditionFailed_Cnd, conditionText) : SR.PreconditionFailed; case ContractFailureKind.Postcondition: return hasConditionText ? SR.Format(SR.PostconditionFailed_Cnd, conditionText) : SR.PostconditionFailed; case ContractFailureKind.Invariant: return hasConditionText ? SR.Format(SR.InvariantFailed_Cnd, conditionText) : SR.InvariantFailed; case ContractFailureKind.PostconditionOnException: return hasConditionText ? SR.Format(SR.PostconditionOnExceptionFailed_Cnd, conditionText) : SR.PostconditionOnExceptionFailed; default: Contract.Assume(false, "Unreachable code"); return SR.AssumptionFailed; } } #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText) { // Well-formatted English messages will take one of four forms. A sentence ending in // either a period or a colon, the condition string, then the message tacked // on to the end with two spaces in front. // Note that both the conditionText and userMessage may be null. Also, // on Silverlight we may not be able to look up a friendly string for the // error message. Let's leverage Silverlight's default error message there. String failureMessage = GetFailureMessage(failureKind, conditionText); // Now add in the user message, if present. if (!String.IsNullOrEmpty(userMessage)) { return failureMessage + " " + userMessage; } else { return failureMessage; } } //#if !FEATURE_CORECLR // // Will trigger escalation policy, if hosted and the host requested us to do something (such as // // abort the thread or exit the process). Starting in Dev11, for hosted apps the default behavior // // is to throw an exception. // // Implementation notes: // // We implement our default behavior of throwing an exception by simply returning from our native // // method inside the runtime and falling through to throw an exception. // // We must call through this method before calling the method on the Environment class // // because our security team does not yet support SecuritySafeCritical on P/Invoke methods. // // Note this can be called in the context of throwing another exception (EnsuresOnThrow). //#if FEATURE_UNTRUSTED_CALLERS //#endif //#if FEATURE_RELIABILITY_CONTRACTS // [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] //#endif // [DebuggerNonUserCode] // private static void TriggerCodeContractEscalationPolicy(ContractFailureKind failureKind, String message, String conditionText, Exception innerException) // { // String exceptionAsString = null; // if (innerException != null) // exceptionAsString = innerException.ToString(); // Environment.TriggerCodeContractFailure(failureKind, message, conditionText, exceptionAsString); // } //#endif // !FEATURE_CORECLR } } // namespace System.Runtime.CompilerServices
using ClosedXML.Excel.CalcEngine.Exceptions; using System; using System.Collections.Generic; using System.Globalization; namespace ClosedXML.Excel.CalcEngine.Functions { internal static class Information { public static void Register(CalcEngine ce) { //TODO: Add documentation ce.RegisterFunction("ERRORTYPE", 1, ErrorType); ce.RegisterFunction("ISBLANK", 1, int.MaxValue, IsBlank); ce.RegisterFunction("ISERR", 1, int.MaxValue, IsErr); ce.RegisterFunction("ISERROR", 1, int.MaxValue, IsError); ce.RegisterFunction("ISEVEN", 1, IsEven); ce.RegisterFunction("ISLOGICAL", 1, int.MaxValue, IsLogical); ce.RegisterFunction("ISNA", 1, int.MaxValue, IsNa); ce.RegisterFunction("ISNONTEXT", 1, int.MaxValue, IsNonText); ce.RegisterFunction("ISNUMBER", 1, int.MaxValue, IsNumber); ce.RegisterFunction("ISODD", 1, IsOdd); ce.RegisterFunction("ISREF", 1, int.MaxValue, IsRef); ce.RegisterFunction("ISTEXT", 1, int.MaxValue, IsText); ce.RegisterFunction("N", 1, N); ce.RegisterFunction("NA", 0, NA); ce.RegisterFunction("TYPE", 1, Type); } static IDictionary<ErrorExpression.ExpressionErrorType, int> errorTypes = new Dictionary<ErrorExpression.ExpressionErrorType, int>() { [ErrorExpression.ExpressionErrorType.NullValue] = 1, [ErrorExpression.ExpressionErrorType.DivisionByZero] = 2, [ErrorExpression.ExpressionErrorType.CellValue] = 3, [ErrorExpression.ExpressionErrorType.CellReference] = 4, [ErrorExpression.ExpressionErrorType.NameNotRecognized] = 5, [ErrorExpression.ExpressionErrorType.NumberInvalid] = 6, [ErrorExpression.ExpressionErrorType.NoValueAvailable] = 7 }; static object ErrorType(List<Expression> p) { var v = p[0].Evaluate(); if (v is ErrorExpression.ExpressionErrorType) return errorTypes[(ErrorExpression.ExpressionErrorType)v]; else throw new NoValueAvailableException(); } static object IsBlank(List<Expression> p) { var v = (string) p[0]; var isBlank = string.IsNullOrEmpty(v); if (isBlank && p.Count > 1) { var sublist = p.GetRange(1, p.Count); isBlank = (bool)IsBlank(sublist); } return isBlank; } static object IsErr(List<Expression> p) { var v = p[0].Evaluate(); return v is ErrorExpression.ExpressionErrorType && ((ErrorExpression.ExpressionErrorType)v) != ErrorExpression.ExpressionErrorType.NoValueAvailable; } static object IsError(List<Expression> p) { var v = p[0].Evaluate(); return v is ErrorExpression.ExpressionErrorType; } static object IsEven(List<Expression> p) { var v = p[0].Evaluate(); if (v is double) { return Math.Abs((double) v%2) < 1; } //TODO: Error Exceptions throw new ArgumentException("Expression doesn't evaluate to double"); } static object IsLogical(List<Expression> p) { var v = p[0].Evaluate(); var isLogical = v is bool; if (isLogical && p.Count > 1) { var sublist = p.GetRange(1, p.Count); isLogical = (bool) IsLogical(sublist); } return isLogical; } static object IsNa(List<Expression> p) { var v = p[0].Evaluate(); return v is ErrorExpression.ExpressionErrorType && ((ErrorExpression.ExpressionErrorType)v) == ErrorExpression.ExpressionErrorType.NoValueAvailable; } static object IsNonText(List<Expression> p) { return !(bool) IsText(p); } static object IsNumber(List<Expression> p) { var v = p[0].Evaluate(); var isNumber = v is double; //Normal number formatting if (!isNumber) { isNumber = v is DateTime; //Handle DateTime Format } if (!isNumber) { //Handle Number Styles try { var stringValue = (string) v; return double.TryParse(stringValue.TrimEnd('%', ' '), NumberStyles.Any, null, out double dv); } catch (Exception) { isNumber = false; } } if (isNumber && p.Count > 1) { var sublist = p.GetRange(1, p.Count); isNumber = (bool)IsNumber(sublist); } return isNumber; } static object IsOdd(List<Expression> p) { return !(bool) IsEven(p); } static object IsRef(List<Expression> p) { var oe = p[0] as XObjectExpression; if (oe == null) return false; var crr = oe.Value as CellRangeReference; return crr != null; } static object IsText(List<Expression> p) { //Evaluate Expressions var isText = !(bool) IsBlank(p); if (isText) { isText = !(bool) IsNumber(p); } if (isText) { isText = !(bool) IsLogical(p); } return isText; } static object N(List<Expression> p) { return (double) p[0]; } static object NA(List<Expression> p) { return ErrorExpression.ExpressionErrorType.NoValueAvailable; } static object Type(List<Expression> p) { if ((bool) IsNumber(p)) { return 1; } if ((bool) IsText(p)) { return 2; } if ((bool) IsLogical(p)) { return 4; } if ((bool) IsError(p)) { return 16; } if(p.Count > 1) { return 64; } return null; } } }
using System; using System.Threading.Tasks; using NUnit.Framework; using Zu.AsyncChromeDriver.Tests.Environment; using Zu.AsyncWebDriver; using Zu.AsyncWebDriver.Remote; using Zu.WebBrowser.AsyncInteractions; using Zu.WebBrowser.BasicTypes; namespace Zu.AsyncChromeDriver.Tests { [TestFixture] public class FrameSwitchingTest : DriverTestFixture { // ---------------------------------------------------------------------------------------------- // // Tests that WebDriver doesn't do anything fishy when it navigates to a page with frames. // // ---------------------------------------------------------------------------------------------- [Test] public async Task ShouldAlwaysFocusOnTheTopMostFrameAfterANavigationEvent() { await driver.GoToUrl(framesetPage); IWebElement element = await driver.FindElement(By.TagName("frameset")); Assert.That(element, Is.Not.Null); } [Test] public async Task ShouldNotAutomaticallySwitchFocusToAnIFrameWhenAPageContainingThemIsLoaded() { await driver.GoToUrl(iframePage); await driver.Options().Timeouts.SetImplicitWait(TimeSpan.FromSeconds(1)); IWebElement element = await driver.FindElement(By.Id("iframe_page_heading")); await driver.Options().Timeouts.SetImplicitWait(TimeSpan.FromSeconds(0)); Assert.That(element, Is.Not.Null); } [Test] public async Task ShouldOpenPageWithBrokenFrameset() { await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.WhereIs("framesetPage3.html")); IWebElement frame1 = await driver.FindElement(By.Id("first")); await driver.SwitchTo().Frame(frame1); await driver.SwitchTo().DefaultContent(); IWebElement frame2 = await driver.FindElement(By.Id("second")); try { await driver.SwitchTo().Frame(frame2); } catch (WebDriverException) { // IE9 can not switch to this broken frame - it has no window. } } // ---------------------------------------------------------------------------------------------- // // Tests that WebDriver can switch to frames as expected. // // ---------------------------------------------------------------------------------------------- [Test] public async Task ShouldBeAbleToSwitchToAFrameByItsIndex() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame(1); Assert.AreEqual("2", await driver.FindElement(By.Id("pageNumber")).Text()); } [Test] public async Task ShouldBeAbleToSwitchToAnIframeByItsIndex() { await driver.GoToUrl(iframePage); await driver.SwitchTo().Frame(0); Assert.AreEqual("name", await driver.FindElement(By.Name("id-name1")).GetAttribute("value")); } [Test] public async Task ShouldBeAbleToSwitchToAFrameByItsName() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame("fourth"); Assert.AreEqual("child1", await driver.FindElement(By.TagName("frame")).GetAttribute("name")); } [Test] public async Task ShouldBeAbleToSwitchToAnIframeByItsName() { await driver.GoToUrl(iframePage); await driver.SwitchTo().Frame("iframe1-name"); Assert.AreEqual("name", await driver.FindElement(By.Name("id-name1")).GetAttribute("value")); } [Test] public async Task ShouldBeAbleToSwitchToAFrameByItsID() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame("fifth"); Assert.AreEqual("Open new window", await driver.FindElement(By.Name("windowOne")).Text()); } [Test] public async Task ShouldBeAbleToSwitchToAnIframeByItsID() { await driver.GoToUrl(iframePage); await driver.SwitchTo().Frame("iframe1"); Assert.AreEqual("name", await driver.FindElement(By.Name("id-name1")).GetAttribute("value")); } [Test] public async Task ShouldBeAbleToSwitchToFrameWithNameContainingDot() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame("sixth.iframe1"); Assert.That(await driver.FindElement(By.TagName("body")).Text(), Does.Contain("Page number 3")); } [Test] public async Task ShouldBeAbleToSwitchToAFrameUsingAPreviouslyLocatedWebElement() { await driver.GoToUrl(framesetPage); IWebElement frame = await driver.FindElement(By.TagName("frame")); await driver.SwitchTo().Frame(frame); Assert.AreEqual("1", await driver.FindElement(By.Id("pageNumber")).Text()); } [Test] public async Task ShouldBeAbleToSwitchToAnIFrameUsingAPreviouslyLocatedWebElement() { await driver.GoToUrl(iframePage); IWebElement frame = await driver.FindElement(By.TagName("iframe")); await driver.SwitchTo().Frame(frame); Assert.AreEqual("name", await driver.FindElement(By.Name("id-name1")).GetAttribute("value")); } [Test] public async Task ShouldEnsureElementIsAFrameBeforeSwitching() { await driver.GoToUrl(framesetPage); IWebElement frame = await driver.FindElement(By.TagName("frameset")); //Assert.That(async () => await driver.SwitchTo().Frame(frame), Throws.InstanceOf<NoSuchFrameException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => await driver.SwitchTo().Frame(frame), exception => Assert.AreEqual("NoSuchFrameException", exception.Error)); } [Test] public async Task FrameSearchesShouldBeRelativeToTheCurrentlySelectedFrame() { await driver.GoToUrl(framesetPage); IWebElement frameElement = await WaitFor(async () => await driver.FindElement(By.Name("second")), "did not find frame"); await driver.SwitchTo().Frame(frameElement); Assert.AreEqual("2", await driver.FindElement(By.Id("pageNumber")).Text()); try { await driver.SwitchTo().Frame("third"); Assert.Fail(); } catch (NoSuchFrameException) { // Do nothing } await driver.SwitchTo().DefaultContent(); await driver.SwitchTo().Frame("third"); try { await driver.SwitchTo().Frame("second"); Assert.Fail(); } catch (NoSuchFrameException) { // Do nothing } await driver.SwitchTo().DefaultContent(); await driver.SwitchTo().Frame("second"); Assert.AreEqual("2", await driver.FindElement(By.Id("pageNumber")).Text()); } [Test] public async Task ShouldSelectChildFramesByChainedCalls() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame("fourth").SwitchTo().Frame("child2"); Assert.AreEqual("11", await driver.FindElement(By.Id("pageNumber")).Text()); } [Test] public async Task ShouldThrowFrameNotFoundExceptionLookingUpSubFramesWithSuperFrameNames() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame("fourth"); //Assert.That(async () => await driver.SwitchTo().Frame("second"), Throws.InstanceOf<NoSuchFrameException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => await driver.SwitchTo().Frame("second"), exception => Assert.AreEqual("NoSuchFrameException", exception.Error)); } [Test] public async Task ShouldThrowAnExceptionWhenAFrameCannotBeFound() { await driver.GoToUrl(xhtmlTestPage); //Assert.That(async () => await driver.SwitchTo().Frame("Nothing here"), Throws.InstanceOf<NoSuchFrameException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => await driver.SwitchTo().Frame("Nothing here"), exception => Assert.AreEqual("NoSuchFrameException", exception.Error)); } [Test] public async Task ShouldThrowAnExceptionWhenAFrameCannotBeFoundByIndex() { await driver.GoToUrl(xhtmlTestPage); //Assert.That(async () => await driver.SwitchTo().Frame(27), Throws.InstanceOf<NoSuchFrameException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => await driver.SwitchTo().Frame(27), exception => Assert.AreEqual("NoSuchFrameException", exception.Error)); } [Test] public async Task ShouldBeAbleToSwitchToParentFrame() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame("fourth").SwitchTo().ParentFrame().SwitchTo().Frame("first"); Assert.AreEqual("1", await driver.FindElement(By.Id("pageNumber")).Text()); } [Test] public async Task ShouldBeAbleToSwitchToParentFrameFromASecondLevelFrame() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame("fourth").SwitchTo().Frame("child1").SwitchTo().ParentFrame().SwitchTo().Frame("child2"); Assert.AreEqual("11", await driver.FindElement(By.Id("pageNumber")).Text()); } [Test] public async Task SwitchingToParentFrameFromDefaultContextIsNoOp() { await driver.GoToUrl(xhtmlTestPage); await driver.SwitchTo().ParentFrame(); Assert.AreEqual("XHTML Test Page", await driver.Title()); } [Test] public async Task ShouldBeAbleToSwitchToParentFromAnIframe() { await driver.GoToUrl(iframePage); await driver.SwitchTo().Frame(0); await driver.SwitchTo().ParentFrame(); await driver.FindElement(By.Id("iframe_page_heading")); } // ---------------------------------------------------------------------------------------------- // // General frame handling behavior tests // // ---------------------------------------------------------------------------------------------- [Test] public async Task ShouldContinueToReferToTheSameFrameOnceItHasBeenSelected() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame(2); IWebElement checkbox = await driver.FindElement(By.XPath("//input[@name='checky']")); await checkbox.Click(); await checkbox.Submit(); Assert.AreEqual("Success!", await driver.FindElement(By.XPath("//p")).Text()); } [Test] public async Task ShouldFocusOnTheReplacementWhenAFrameFollowsALinkToA_TopTargettedPage() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame(0); await driver.FindElement(By.LinkText("top")).Click(); // TODO(simon): Avoid going too fast when native events are there. System.Threading.Thread.Sleep(1000); Assert.AreEqual("XHTML Test Page", await driver.Title()); } [Test] public async Task ShouldAllowAUserToSwitchFromAnIframeBackToTheMainContentOfThePage() { await driver.GoToUrl(iframePage); await driver.SwitchTo().Frame(0); await driver.SwitchTo().DefaultContent(); await driver.FindElement(By.Id("iframe_page_heading")); } [Test] public async Task ShouldAllowTheUserToSwitchToAnIFrameAndRemainFocusedOnIt() { await driver.GoToUrl(iframePage); await driver.SwitchTo().Frame(0); await driver.FindElement(By.Id("submitButton")).Click(); string hello = await GetTextOfGreetingElement(); Assert.AreEqual(hello, "Success!"); } [Test] public async Task ShouldBeAbleToClickInAFrame() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame("third"); // This should replace frame "third" ... await driver.FindElement(By.Id("submitButton")).Click(); // driver should still be focused on frame "third" ... Assert.AreEqual("Success!", await GetTextOfGreetingElement()); // Make sure it was really frame "third" which was replaced ... await driver.SwitchTo().DefaultContent().SwitchTo().Frame("third"); Assert.AreEqual("Success!", await GetTextOfGreetingElement()); } [Test] public async Task ShouldBeAbleToClickInAFrameThatRewritesTopWindowLocation() { await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/issue5237.html")); await driver.SwitchTo().Frame("search"); await driver.FindElement(By.Id("submit")).Click(); await driver.SwitchTo().DefaultContent(); await WaitFor(driver.Title(), "Target page for issue 5237", "Browser title was not 'Target page for issue 5237'"); } [Test] public async Task ShouldBeAbleToClickInASubFrame() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame("sixth").SwitchTo().Frame("iframe1"); // This should replaxe frame "iframe1" inside frame "sixth" ... await driver.FindElement(By.Id("submitButton")).Click(); // driver should still be focused on frame "iframe1" inside frame "sixth" ... Assert.AreEqual("Success!", await GetTextOfGreetingElement()); // Make sure it was really frame "iframe1" inside frame "sixth" which was replaced ... await driver.SwitchTo().DefaultContent().SwitchTo().Frame("sixth").SwitchTo().Frame("iframe1"); Assert.AreEqual("Success!", await driver.FindElement(By.Id("greeting")).Text()); } [Test] public async Task ShouldBeAbleToFindElementsInIframesByXPath() { await driver.GoToUrl(iframePage); await driver.SwitchTo().Frame("iframe1"); IWebElement element = await driver.FindElement(By.XPath("//*[@id = 'changeme']")); Assert.That(element, Is.Not.Null); } [Test] public async Task GetCurrentUrlShouldReturnTopLevelBrowsingContextUrl() { await driver.GoToUrl(framesetPage); Assert.AreEqual(framesetPage, await driver.GetUrl()); await driver.SwitchTo().Frame("second"); Assert.AreEqual(framesetPage, await driver.GetUrl()); } [Test] public async Task GetCurrentUrlShouldReturnTopLevelBrowsingContextUrlForIframes() { await driver.GoToUrl(iframePage); Assert.AreEqual(iframePage, await driver.GetUrl()); await driver.SwitchTo().Frame("iframe1"); Assert.AreEqual(iframePage, await driver.GetUrl()); } [Test] public async Task ShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUs() { await driver.GoToUrl(deletingFrame); await driver.SwitchTo().Frame("iframe1"); IWebElement killIframe = await driver.FindElement(By.Id("killIframe")); await killIframe.Click(); await driver.SwitchTo().DefaultContent(); await AssertFrameNotPresent("iframe1"); IWebElement addIFrame = await driver.FindElement(By.Id("addBackFrame")); await addIFrame.Click(); await WaitFor(() => driver.FindElement(By.Id("iframe1")), "Did not find frame element"); await driver.SwitchTo().Frame("iframe1"); await WaitFor(() => driver.FindElement(By.Id("success")), "Did not find element in frame"); } [Test] public async Task ShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUsWithFrameIndex() { await driver.GoToUrl(deletingFrame); int iframe = 0; await WaitFor(() => FrameExistsAndSwitchedTo(iframe), "Did not switch to frame"); // we should be in the frame now IWebElement killIframe = await driver.FindElement(By.Id("killIframe")); await killIframe.Click(); await driver.SwitchTo().DefaultContent(); IWebElement addIFrame = await driver.FindElement(By.Id("addBackFrame")); await addIFrame.Click(); await WaitFor(() => FrameExistsAndSwitchedTo(iframe), "Did not switch to frame"); await WaitFor(() => driver.FindElement(By.Id("success")), "Did not find element in frame"); } [Test] public async Task ShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUsWithWebelement() { await driver.GoToUrl(deletingFrame); IWebElement iframe = await driver.FindElement(By.Id("iframe1")); await WaitFor(() => FrameExistsAndSwitchedTo(iframe), "Did not switch to frame"); // we should be in the frame now IWebElement killIframe = await driver.FindElement(By.Id("killIframe")); await killIframe.Click(); await driver.SwitchTo().DefaultContent(); IWebElement addIFrame = await driver.FindElement(By.Id("addBackFrame")); await addIFrame.Click(); iframe = await driver.FindElement(By.Id("iframe1")); await WaitFor(() => FrameExistsAndSwitchedTo(iframe), "Did not switch to frame"); await WaitFor(() => driver.FindElement(By.Id("success")), "Did not find element in frame"); } [Test] public async Task ShouldReturnWindowTitleInAFrameset() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame("third"); Assert.AreEqual("Unique title", await driver.Title()); } [Test] public async Task JavaScriptShouldExecuteInTheContextOfTheCurrentFrame() { IJavaScriptExecutor executor = driver as IJavaScriptExecutor; await driver.GoToUrl(framesetPage); Assert.That((bool)await executor.ExecuteScript("return window == window.top"), Is.True); await driver.SwitchTo().Frame("third"); Assert.That((bool)await executor.ExecuteScript("return window != window.top"), Is.True); } [Test] public async Task ShouldNotSwitchMagicallyToTheTopWindow() { string baseUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("frame_switching_tests/"); await driver.GoToUrl(baseUrl + "bug4876.html"); await driver.SwitchTo().Frame(0); await WaitFor(() => driver.FindElement(By.Id("inputText")), "Could not find element"); for (int i = 0; i < 20; i++) { try { IWebElement input = await WaitFor(async () => await driver.FindElement(By.Id("inputText")), "Did not find element"); IWebElement submit = await WaitFor(async () => await driver.FindElement(By.Id("submitButton")), "Did not find input element"); await input.Clear(); await input.SendKeys("rand" + new Random().Next()); await submit.Click(); } finally { string url = (string)await ((IJavaScriptExecutor)driver).ExecuteScript("return window.location.href"); // IE6 and Chrome add "?"-symbol to the end of the URL if (url.EndsWith("?")) { url = url.Substring(0, url.Length - 1); } Assert.AreEqual(baseUrl + "bug4876_iframe.html", url); } } } [Test] [NeedsFreshDriver(IsCreatedAfterTest = true)] public async Task GetShouldSwitchToDefaultContext() { await driver.GoToUrl(iframePage); await driver.SwitchTo().Frame(await driver.FindElement(By.Id("iframe1"))); await driver.FindElement(By.Id("cheese")); // Found on formPage.html but not on iframes.html. await driver.GoToUrl(iframePage); // This must effectively switchTo().defaultContent(), too. await driver.FindElement(By.Id("iframe1")); } // ---------------------------------------------------------------------------------------------- // // Frame handling behavior tests not included in Java tests // // ---------------------------------------------------------------------------------------------- [Test] public async Task ShouldBeAbleToFlipToAFrameIdentifiedByItsId() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame("fifth"); await driver.FindElement(By.Id("username")); } [Test] public async Task ShouldBeAbleToSelectAFrameByName() { await driver.GoToUrl(framesetPage); await driver.SwitchTo().Frame("second"); Assert.AreEqual(await driver.FindElement(By.Id("pageNumber")).Text(), "2"); await driver.SwitchTo().DefaultContent().SwitchTo().Frame("third"); await driver.FindElement(By.Id("changeme")).Click(); await driver.SwitchTo().DefaultContent().SwitchTo().Frame("second"); Assert.AreEqual(await driver.FindElement(By.Id("pageNumber")).Text(), "2"); } [Test] public async Task ShouldBeAbleToFindElementsInIframesByName() { await driver.GoToUrl(iframePage); await driver.SwitchTo().Frame("iframe1"); IWebElement element = await driver.FindElement(By.Name("id-name1")); Assert.That(element, Is.Not.Null); } private async Task<string> GetTextOfGreetingElement() { string text = string.Empty; DateTime end = DateTime.Now.Add(TimeSpan.FromMilliseconds(3000)); while (DateTime.Now < end) { try { IWebElement element = await driver.FindElement(By.Id("greeting")); text = await element.Text(); break; } catch (NoSuchElementException) { } } return text; } private async Task AssertFrameNotPresent(string locator) { await driver.SwitchTo().DefaultContent(); await WaitFor(async () => !(await FrameExistsAndSwitchedTo(locator)), "Frame still present after timeout"); await driver.SwitchTo().DefaultContent(); } private async Task<bool> FrameExistsAndSwitchedTo(string locator) { try { await driver.SwitchTo().Frame(locator); return true; } catch (NoSuchFrameException) { } return false; } private async Task<bool> FrameExistsAndSwitchedTo(int index) { try { await driver.SwitchTo().Frame(index); return true; } catch (NoSuchFrameException) { } return false; } private async Task<bool> FrameExistsAndSwitchedTo(IWebElement frameElement) { try { await driver.SwitchTo().Frame(frameElement); return true; } catch (NoSuchFrameException) { } return false; } } }
using System.Text.RegularExpressions; using Xunit; namespace jmespath.net.tests { public sealed class RegexTest { [Fact] public void Regex_UnquotedString() { /* * * unquoted-string = (%x41-5A / %x61-7A / %x5F) *( ; a-zA-Z_ * %x30-39 / ; 0-9 * %x41-5A / ; A-Z * %x5F / ; _ * %x61-7A) ; a-z */ // [A-Za-z_][0-9A-Za-z_]* const string pattern = "[A-Za-z_][0-9A-Za-z_]*"; Assert.True(Match("foo_42", pattern)); Assert.False(Match("42_should_not_start_with_digit", pattern)); Assert.False(Match("should_not_contain_!_special_chars", pattern)); } [Fact] public void Regex_QuotedString() { /* * * quoted-string = quote 1*(unescaped-char / escaped-char) quote * unescaped-char = %x20-21 / %x23-5B / %x5D-10FFFF * escape = %x5C ; Back slash: \ * quote = %x22 ; Double quote: '"' * escaped-char = escape ( * %x22 / ; " quotation mark U+0022 * %x5C / ; \ reverse solidus U+005C * %x2F / ; / solidus U+002F * %x62 / ; b backspace U+0008 * %x66 / ; f form feed U+000C * %x6E / ; n line feed U+000A * %x72 / ; r carriage return U+000D * %x74 / ; t tab U+0009 * %x75 4HEXDIG ) ; uXXXX U+XXXX * */ Regex_JsonString(); } [Fact] public void Regex_JsonString() { /* * RFC 7159: * * string = quotation-mark *char quotation-mark * char = unescaped / * escape ( * %x22 / ; " quotation mark U+0022 * %x5C / ; \ reverse solidus U+005C * %x2F / ; / solidus U+002F * %x62 / ; b backspace U+0008 * %x66 / ; f form feed U+000C * %x6E / ; n line feed U+000A * %x72 / ; r carriage return U+000D * %x74 / ; t tab U+0009 * %x75 4HEXDIG ) ; uXXXX U+XXXX * escape = %x5C ; \ * quotation-mark = %x22 ; " * unescaped = %x20-21 / %x23-5B / %x5D-10FFFF * */ // "[^"\\\b\f\n\r\t]*((\\["\\/bfnrt]|\\u[0-9a-fA-F]{4})+[^"\\\b\f\n\r\t]*)*" const string pattern = @"""[^""\\\b\f\n\r\t]*((\\[""\\/bfnrt]|\\u[0-9a-fA-F]{4})+[^""\\\b\f\n\r\t]*)*"""; Assert.True(Match("\"Hello, world!\"", pattern)); Assert.True(Match("\"Enclosing \\\"name\\\" in double quotes\"", pattern)); Assert.True(Match("\"Escaped \\\\ \"", pattern)); Assert.True(Match("\"Escaped \\b \"", pattern)); Assert.True(Match("\"Escaped \\f \"", pattern)); Assert.True(Match("\"Escaped \\n \"", pattern)); Assert.True(Match("\"Escaped \\r \"", pattern)); Assert.True(Match("\"Escaped \\t \"", pattern)); Assert.True(Match("\"Escaped \\u2713 \"", pattern)); Assert.False(Match("\" tab character in string \"", pattern)); Assert.False(Match("\"Incomplete \\unicode sequence\"", pattern)); } [Fact] public void Regex_JsonNumber() { /* * RFC 7159: * number = [ minus ] int [ frac ] [ exp ] * decimal-point = %x2E ; . * digit1-9 = %x31-39 ; 1-9 * e = %x65 / %x45 ; e E * exp = e [ minus / plus ] 1*DIGIT * frac = decimal-point 1*DIGIT * int = zero / ( digit1-9 *DIGIT ) * minus = %x2D ; - * plus = %x2B ; + * zero = %x30 ; 0 * */ const string pattern = @"\-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][\+\-]?[0-9]+)?"; Assert.True(Match("42", pattern)); Assert.True(Match("42e12", pattern)); Assert.True(Match("42e+12", pattern)); Assert.True(Match("42e-12", pattern)); Assert.True(Match("42E12", pattern)); Assert.True(Match("42E+12", pattern)); Assert.True(Match("42E-12", pattern)); Assert.True(Match("-42", pattern)); Assert.True(Match("-42e12", pattern)); Assert.True(Match("-42e+12", pattern)); Assert.True(Match("-42e-12", pattern)); Assert.True(Match("-42E12", pattern)); Assert.True(Match("-42E+12", pattern)); Assert.True(Match("-42E-12", pattern)); Assert.True(Match("42.3", pattern)); Assert.True(Match("42.3e12", pattern)); Assert.True(Match("42.3e+12", pattern)); Assert.True(Match("42.3e-12", pattern)); Assert.True(Match("42.3E12", pattern)); Assert.True(Match("42.3E+12", pattern)); Assert.True(Match("42.3E-12", pattern)); Assert.True(Match("-42.3", pattern)); Assert.True(Match("-42.3e12", pattern)); Assert.True(Match("-42.3e+12", pattern)); Assert.True(Match("-42.3e-12", pattern)); Assert.True(Match("-42.3E12", pattern)); Assert.True(Match("-42.3E+12", pattern)); Assert.True(Match("-42.3E-12", pattern)); Assert.False(Match("01.50", pattern)); Assert.True(Match("1.05e+03", pattern)); } [Fact] public void Regex_RawString() { /* * * raw-string = "'" *raw-string-char "'" * raw-string-char = (%x20-26 / %x28-5B / %x5D-10FFFF) / preserved-escape / * raw-string-escape * preserved-escape = escape (%x20-26 / %28-5B / %x5D-10FFFF) * raw-string-escape = escape ("'" / escape) * * escape = %x5C ; Back slash: \ */ // '(\\?[^'\\])*((\\['\\])+(\\?[^'\\])*)*' const string pattern = @"'(\\?[^'\\])*((\\['\\])+(\\?[^'\\])*)*'"; Assert.True(Match("'abcd'", pattern)); Assert.True(Match("'\\a\\b\\c'", pattern)); Assert.True(Match("'\\'Hello\\''", pattern)); } [Fact] public void Regex_JsonLiteral_String() { /* * ; The ``json-value`` is any valid JSON value with the one exception that the ; ``%x60`` character must be escaped. While it's encouraged that implementations ; use any existing JSON parser for this grammar rule (after handling the escaped ; literal characters), the grammar rule is shown below for completeness:: */ // `[^`]*((\\`)*[^`]*)*` const string pattern = @"`[^`]*((\\`)*[^`]*)*`"; Assert.True(Match("`abcd`", pattern)); Assert.True(Match("`\\a\\b\\c`", pattern)); Assert.True(Match("`\\`Hello\\``", pattern)); Assert.False(Match("`\\`Hel`lo\\``", pattern)); } private static bool Match(string input, string pattern) { var regex = new Regex("^" + pattern + "$", RegexOptions.Singleline); var match = regex.Match(input); return match.Success; } } }
// // Copyright (c) 2004-2016 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.Globalization; using System.Linq; using NLog.Internal.Pooling; using NLog.Layouts; namespace NLog.Config { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using JetBrains.Annotations; using NLog.Common; using NLog.Internal; using NLog.Targets; /// <summary> /// Keeps logging configuration and provides simple API /// to modify it. /// </summary> ///<remarks>This class is thread-safe.<c>.ToList()</c> is used for that purpose.</remarks> public class LoggingConfiguration { private readonly IDictionary<string, Target> targets = new Dictionary<string, Target>(StringComparer.OrdinalIgnoreCase); private List<object> configItems = new List<object>(); /// <summary> /// Variables defined in xml or in API. name is case case insensitive. /// </summary> private readonly Dictionary<string, SimpleLayout> variables = new Dictionary<string, SimpleLayout>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Initializes a new instance of the <see cref="LoggingConfiguration" /> class. /// </summary> public LoggingConfiguration() { this.LoggingRules = new List<LoggingRule>(); this.PoolConfiguration = new PoolConfiguration(this); this.PoolFactory = new PoolFactory(this.PoolConfiguration); } /// <summary> /// Use the old exception log handling of NLog 3.0? /// </summary> [Obsolete("This option will be removed in NLog 5")] public bool ExceptionLoggingOldStyle { get; set; } /// <summary> /// Gets the variables defined in the configuration. /// </summary> public IDictionary<string, SimpleLayout> Variables { get { return variables; } } /// <summary> /// Gets a collection of named targets specified in the configuration. /// </summary> /// <returns> /// A list of named targets. /// </returns> /// <remarks> /// Unnamed targets (such as those wrapped by other targets) are not returned. /// </remarks> public ReadOnlyCollection<Target> ConfiguredNamedTargets { get { return new List<Target>(this.targets.Values).AsReadOnly(); } } /// <summary> /// Gets the collection of file names which should be watched for changes by NLog. /// </summary> public virtual IEnumerable<string> FileNamesToWatch { get { return new string[0]; } } /// <summary> /// Gets the collection of logging rules. /// </summary> public IList<LoggingRule> LoggingRules { get; private set; } /// <summary> /// Gets or sets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>. /// </summary> /// <value> /// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/> /// </value> [CanBeNull] public CultureInfo DefaultCultureInfo { get; set; } /// <summary> /// Gets or sets the current object pool configuration. /// </summary> public PoolConfiguration PoolConfiguration { get; set; } /// <summary> /// Gets the current object pool /// </summary> internal PoolFactory PoolFactory { get; private set; } /// <summary> /// Gets all targets. /// </summary> public ReadOnlyCollection<Target> AllTargets { get { var configTargets = this.configItems.OfType<Target>(); return configTargets.Concat(targets.Values).Distinct(TargetNameComparer).ToList().AsReadOnly(); } } /// <summary> /// Compare on name /// </summary> private static IEqualityComparer<Target> TargetNameComparer = new TargetNameEq(); /// <summary> /// Compare on name /// </summary> private class TargetNameEq : IEqualityComparer<Target> { public bool Equals(Target x, Target y) { return string.Equals(x.Name, y.Name); } public int GetHashCode(Target obj) { return (obj.Name != null ? obj.Name.GetHashCode() : 0); } } /// <summary> /// Registers the specified target object. The name of the target is read from <see cref="Target.Name"/>. /// </summary> /// <param name="target"> /// The target object with a non <see langword="null"/> <see cref="Target.Name"/> /// </param> /// <exception cref="ArgumentNullException">when <paramref name="target"/> is <see langword="null"/></exception> public void AddTarget([NotNull] Target target) { if (target == null) throw new ArgumentNullException("target"); AddTarget(target.Name, target); } /// <summary> /// Registers the specified target object under a given name. /// </summary> /// <param name="name"> /// Name of the target. /// </param> /// <param name="target"> /// The target object. /// </param> public void AddTarget(string name, Target target) { if (name == null) { throw new ArgumentException("Target name cannot be null", "name"); } InternalLogger.Debug("Registering target {0}: {1}", name, target.GetType().FullName); this.targets[name] = target; } /// <summary> /// Finds the target with the specified name. /// </summary> /// <param name="name"> /// The name of the target to be found. /// </param> /// <returns> /// Found target or <see langword="null"/> when the target is not found. /// </returns> public Target FindTargetByName(string name) { Target value; if (!this.targets.TryGetValue(name, out value)) { return null; } return value; } /// <summary> /// Finds the target with the specified name and specified type. /// </summary> /// <param name="name"> /// The name of the target to be found. /// </param> /// <typeparam name="TTarget">Type of the target</typeparam> /// <returns> /// Found target or <see langword="null"/> when the target is not found of not of type <typeparamref name="TTarget"/> /// </returns> public TTarget FindTargetByName<TTarget>(string name) where TTarget : Target { return FindTargetByName(name) as TTarget; } /// <summary> /// Add a rule with min- and maxLevel. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> /// <param name="targetName">Name of the target to be written when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRule(LogLevel minLevel, LogLevel maxLevel, string targetName, string loggerNamePattern = "*") { var target = FindTargetByName(targetName); if (target == null) { throw new NLogRuntimeException("Target '{0}' not found", targetName); } AddRule(minLevel, maxLevel, target, loggerNamePattern); } /// <summary> /// Add a rule with min- and maxLevel. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRule(LogLevel minLevel, LogLevel maxLevel, Target target, string loggerNamePattern = "*") { LoggingRules.Add(new LoggingRule(loggerNamePattern, minLevel, maxLevel, target)); } /// <summary> /// Add a rule for one loglevel. /// </summary> /// <param name="level">log level needed to trigger this rule. </param> /// <param name="targetName">Name of the target to be written when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForOneLevel(LogLevel level, string targetName, string loggerNamePattern = "*") { var target = FindTargetByName(targetName); if (target == null) { throw new NLogConfigurationException("Target '{0}' not found", targetName); } AddRuleForOneLevel(level, target, loggerNamePattern); } /// <summary> /// Add a rule for one loglevel. /// </summary> /// <param name="level">log level needed to trigger this rule. </param> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForOneLevel(LogLevel level, Target target, string loggerNamePattern = "*") { var loggingRule = new LoggingRule(loggerNamePattern, target); loggingRule.EnableLoggingForLevel(level); LoggingRules.Add(loggingRule); } /// <summary> /// Add a rule for alle loglevels. /// </summary> /// <param name="targetName">Name of the target to be written when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForAllLevels(string targetName, string loggerNamePattern = "*") { var target = FindTargetByName(targetName); if (target == null) { throw new NLogRuntimeException("Target '{0}' not found", targetName); } AddRuleForAllLevels(target, loggerNamePattern); } /// <summary> /// Add a rule for alle loglevels. /// </summary> /// <param name="target">Target to be written to when the rule matches.</param> /// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param> public void AddRuleForAllLevels(Target target, string loggerNamePattern = "*") { var loggingRule = new LoggingRule(loggerNamePattern, target); loggingRule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); LoggingRules.Add(loggingRule); } /// <summary> /// Called by LogManager when one of the log configuration files changes. /// </summary> /// <returns> /// A new instance of <see cref="LoggingConfiguration"/> that represents the updated configuration. /// </returns> public virtual LoggingConfiguration Reload() { return this; } /// <summary> /// Removes the specified named target. /// </summary> /// <param name="name"> /// Name of the target. /// </param> public void RemoveTarget(string name) { this.targets.Remove(name); } /// <summary> /// Installs target-specific objects on current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Installation typically runs with administrative permissions. /// </remarks> public void Install(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException("installationContext"); } this.InitializeAll(); var configItemsList = GetInstallableItems(); foreach (IInstallable installable in configItemsList) { installationContext.Info("Installing '{0}'", installable); try { installable.Install(installationContext); installationContext.Info("Finished installing '{0}'.", installable); } catch (Exception exception) { InternalLogger.Error(exception, "Install of '{0}' failed.", installable); if (exception.MustBeRethrownImmediately()) { throw; } installationContext.Error("Install of '{0}' failed: {1}.", installable, exception); } } } /// <summary> /// Uninstalls target-specific objects from current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Uninstallation typically runs with administrative permissions. /// </remarks> public void Uninstall(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException("installationContext"); } this.InitializeAll(); var configItemsList = GetInstallableItems(); foreach (IInstallable installable in configItemsList) { installationContext.Info("Uninstalling '{0}'", installable); try { installable.Uninstall(installationContext); installationContext.Info("Finished uninstalling '{0}'.", installable); } catch (Exception exception) { InternalLogger.Error(exception, "Uninstall of '{0}' failed.", installable); if (exception.MustBeRethrownImmediately()) { throw; } installationContext.Error("Uninstall of '{0}' failed: {1}.", installable, exception); } } } /// <summary> /// Closes all targets and releases any unmanaged resources. /// </summary> internal void Close() { InternalLogger.Debug("Closing logging configuration..."); var supportsInitializesList = GetSupportsInitializes(); foreach (ISupportsInitialize initialize in supportsInitializesList) { InternalLogger.Trace("Closing {0}", initialize); try { initialize.Close(); } catch (Exception exception) { InternalLogger.Warn(exception, "Exception while closing."); if (exception.MustBeRethrown()) { throw; } } } InternalLogger.Debug("Finished closing logging configuration."); } /// <summary> /// Log to the internal (NLog) logger the information about the <see cref="Target"/> and <see /// cref="LoggingRule"/> associated with this <see cref="LoggingConfiguration"/> instance. /// </summary> /// <remarks> /// The information are only recorded in the internal logger if Debug level is enabled, otherwise nothing is /// recorded. /// </remarks> internal void Dump() { if (!InternalLogger.IsDebugEnabled) { return; } InternalLogger.Debug("--- NLog configuration dump ---"); InternalLogger.Debug("Targets:"); var targetList = this.targets.Values.ToList(); foreach (Target target in targetList) { InternalLogger.Debug("{0}", target); } InternalLogger.Debug("Rules:"); var loggingRules = this.LoggingRules.ToList(); foreach (LoggingRule rule in loggingRules) { InternalLogger.Debug("{0}", rule); } InternalLogger.Debug("--- End of NLog configuration dump ---"); } /// <summary> /// Flushes any pending log messages on all appenders. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> internal void FlushAllTargets(AsyncContinuation asyncContinuation) { if (asyncContinuation == null) { throw new ArgumentNullException("asyncContinuation"); } var uniqueTargets = new List<Target>(); var loggingRules = this.LoggingRules.ToList(); foreach (var rule in loggingRules) { var targetList = rule.Targets.ToList(); foreach (var target in targetList) { if (!uniqueTargets.Contains(target)) { uniqueTargets.Add(target); } } } var exceptions = new List<Exception>(); foreach (var target in uniqueTargets) { target.Flush(ex => { if (ex != null) { exceptions.Add(ex); } }); } asyncContinuation(AsyncHelpers.GetCombinedException(exceptions)); //AsyncHelpers.ForEachItemInParallel(this, uniqueTargets, asyncContinuation, (target, cont) => target.Flush(cont)); } /// <summary> /// Validates the configuration. /// </summary> internal void ValidateConfig() { var roots = new List<object>(); var loggingRules = this.LoggingRules.ToList(); foreach (LoggingRule rule in loggingRules) { roots.Add(rule); } var targetList = this.targets.Values.ToList(); foreach (Target target in targetList) { roots.Add(target); } this.configItems = ObjectGraphScanner.FindReachableObjects<object>(roots.ToArray()); this.configItems.Add(this.PoolFactory); // initialize all config items starting from most nested first // so that whenever the container is initialized its children have already been InternalLogger.Info("Found {0} configuration items", this.configItems.Count); foreach (object o in this.configItems) { PropertyHelper.CheckRequiredParameters(o); } } internal void InitializeAll() { this.ValidateConfig(); var supportsInitializes = GetSupportsInitializes(true); foreach (ISupportsInitialize initialize in supportsInitializes) { InternalLogger.Trace("Initializing {0}", initialize); try { initialize.Initialize(this); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error during initialization of " + initialize, exception); } } } } internal void EnsureInitialized() { this.InitializeAll(); } private List<IInstallable> GetInstallableItems() { return this.configItems.OfType<IInstallable>().ToList(); } private List<ISupportsInitialize> GetSupportsInitializes(bool reverse = false) { var items = this.configItems.OfType<ISupportsInitialize>(); if (reverse) { items = items.Reverse(); } return items.ToList(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Modeling; using Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter; using System.Diagnostics.CodeAnalysis; namespace Microsoft.Protocols.TestSuites.FileSharing.FSA.Model { /// <summary> /// MS-FSA model program /// </summary> public static partial class ModelProgram { #region variables /// <summary> /// FSA initialization state. /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static FSStates fsStates = FSStates.ReadyInitial; /// <summary> /// Global variable of SUT platform, to save the SUT platform. /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static PlatformType sutPlatForm; /// <summary> /// Used to get sut information. /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static SutOSInfo sutOSInfo = SutOSInfo.ReadyGetSutInfo; /// <summary> /// A list of waiting operations that can be canceled by adding them to the /// CancelableOperations.CancelableOperationList as defined in section 3.1.1.12 /// </summary> static SequenceContainer<IORequest> sequenceIORequest = new SequenceContainer<IORequest>(); /// <summary> /// Judge if requirement 507 is implemented. /// </summary> static bool isR507Implemented; /// <summary> /// judge 405 requirement if implement /// </summary> static bool isR405Implemented; /// <summary> /// Security context. /// </summary> static SSecurityContext gSecurityContext; #endregion #region FSA Model State #region 3.1.5.1 global variables /// <summary> /// The access granted for this open as specified in [MS-SMB2] section 2.2.13.1. /// Open.GrantedAccess used in 3.1.5.1 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static FileAccess gOpenGrantedAccess; /// <summary> /// The access requested for this Open but not yet granted, as specified in [MS-SMB2] section 2.2.13.1. /// Open.RemainingDesiredAccess used in 3.1.5.1 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static FileAccess gOpenRemainingDesiredAccess; /// <summary> /// The sharing mode for this Open as specified in [MS-SMB2] section 2.2.13. /// Open.SharingMode used in 3.1.5.1 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static ShareAccess gOpenSharingMode; /// <summary> /// The mode flags for this Open as specified in [MS-FSCC] section 2.4.24. /// Open.Mode used in 3.1.5.1 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static CreateOptions gOpenMode; /// <summary> /// A boolean that is true if the Open was performed by a user who is allowed to perform backup operations. /// Open.HasBackupAccess used in 3.1.5.1 and 3.1.5.9.5 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool isOpenHasBackupAccess; /// <summary> /// A boolean that is true if the Open was performed by a user who is allowed to perform restore operations. /// Open.HasRestoreAccess used in 3.1.5.1 and 3.1.5.9.23 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool isOpenHasRestoreAccess; /// <summary> /// A boolean that is true if the Open was performed by a user who is allowed to create symbolic links. /// Open.HasCreateSymbolicLinkAccess used in 3.1.5.1 and 3.1.5.9.25 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool isOpenHasCreateSymbolicLinkAccess; /// <summary> /// Open.HasManageVolumeAccess used in 3.1.5.1 and 3.1.5.9.5 and 3.1.5.14.14 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool isOpenHasManageVolumeAccess; /// <summary> /// A boolean that is true if the Open was performed by a user who is allowed to manage the volume. /// Open.IsAdministrator used in 3.1.5.1 and 3.1.5.9.30 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool isOpenIsAdministrator; /// <summary> /// The type of file to open. This value MUST be either DataFile or DirectoryFile. /// FileTypeToOpen used in 3.1.5.1 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static FileType gfileTypeToOpen; /// <summary> /// A code defining the action taken by the open operation, as specified in [MS-SMB2] /// section 2.2.14 for the CreateAction field /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static CreateAction gCreateAction; /// <summary> /// A list of zero or more ByteRangeLocks describing the bytes ranges of /// this stream that are currently locked. /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static SequenceContainer<ByteRangeLock> ByteRangeLockList = new SequenceContainer<ByteRangeLock>(); /// <summary> /// The type of stream. This value MUST be either DataStream or DirectoryStream. /// Stream.StreamType /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static StreamType gStreamType; /// <summary> /// A boolean that is true if the volume is read-only and MUST NOT be modified; /// otherwise, the volume is both readable and writable. /// true: If RootOpen.Volume.IsReadOnly /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool isFileVolumeReadOnly; /// <summary> /// A boolean that is true if Open.File.Volume.IsUsnJournalActive is TRUE and MUST NOT be modified; /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool isFileVolumeUsnJournalActive; /// <summary> /// The DirectoryFile for the root of this volume. /// True: If File == File.Volume.RootDirectory /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool isFileEqualRootDirectory; /// <summary> /// Indicate if Open.File.Volume is NTFS file system. /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool isFileVolumeNtfsFileSystem; #endregion #region 3.1.5.2 global variables /// <summary> /// The byte offset immediately following the most recent successful synchronous read or write operation /// of one or more bytes, or 0 if there have not been any. /// Open.CurrentByteOffset seted in 3.1.5.2 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static long gOpenCurrentOffset; /// <summary> /// file volume size /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static long gOpenFileVolumeSize; #endregion #region 3.1.5.12 global variable /// <summary> /// get if Quotas is supported. /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool gisQuotasSupported; /// <summary> /// get if ObjectIDs is supported /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool gisObjectIDsSupported; #endregion #region 3.1.5.17 global variable /// <summary> /// The current state of the oplock, expressed as a combination of one or more flags. /// Oplock.State set in 3.1.5.17.1 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static OplockState gOplockState; #endregion #region 3.1.5.14 global variable /// <summary> /// Attributes of the file in the form specified in [MS-FSCC] section 2.6. /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static FileAttribute gFileAttribute; /// <summary> /// A boolean that is true if the contents of the stream are compressed. /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool gOpenStreamIsCompressed; /// <summary> /// A boolean that is true if the object store is storing a sparse representation of the stream. /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool gOpenStreamIsSparse; /// <summary> /// A boolean that is true if short name creation support is enabled on this Volume. /// FALSE if short name creation is not supported on this Volume. /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool gOpenGenerateShortNames; /// <summary> /// True if TargetStream is found. Used in section 3.1.5.14.11.1 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool gIsTargetStreamFound; /// <summary> /// True if the size of TargetStream is not 0. Used in section 3.1.5.14.11.1 /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool gIsTargetStreamSizeNotZero; #endregion 3.1.5.14 global variable #region 3.1.5.14 call return #region get if gOpenGenerateShortNames /// <summary> /// The call part of the method GetIFQuotasSupported which is used to /// get if ObjectIDs is supported. /// This is a call-return pattern /// </summary> [Rule(Action = "call GetOpenGenerateShortNames(out _)")] public static void CallGetOpenGenerateShortNames() { } /// <summary> /// The return part of the method GetIFQuotasSupported which is used to /// get if ObjectIDs is supported. /// This is a call-returns pattern. /// </summary> /// <param name="GenerateShortNames">true: if ObjectIDs is supported</param> [Rule(Action = "return GetOpenGenerateShortNames(out GenerateShortNames)")] public static void ReturnGetOpenGenerateShortNames(bool GenerateShortNames) { gOpenGenerateShortNames = GenerateShortNames; } #endregion get if gOpenGenerateShortNames /// <summary> /// True if file.Openlist contains the stream specified. /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool gIsOpenListContains; /// <summary> /// Call function GetIsOpenListContains. /// </summary> [Rule(Action = "call GetIsOpenListContains(out _)")] public static void CallGetIsOpenListContains() { } /// <summary> /// Return the result of function GetIsOpenListContains. /// </summary> /// <param name="IsOpenListContains">A flag</param> [Rule(Action = "return GetIsOpenListContains(out IsOpenListContains)")] public static void ReturnGetIsOpenListContains(bool IsOpenListContains) { gIsOpenListContains = IsOpenListContains; } //Search DestinationDirectory.File.DirectoryList for an ExistingLink where ExistingLink.Name //or ExistingLink.ShortName matches FileName using case-sensitivity according to Open.IsCaseSensitive //If such a link is found: /// <summary> /// True if the link is found. /// </summary> /// Disable warning CA2211, because this action confuses with the actual model design if modify it. [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static bool gIsLinkFound; /// <summary> /// Call function GetIsLinkFound. /// </summary> [Rule(Action = "call GetIsLinkFound(out _)")] public static void CallGetIsLinkFound() { } /// <summary> /// Return the result of function GetIsLinkFound. /// </summary> /// <param name="IsLinkFound">A flag</param> [Rule(Action = "return GetIsLinkFound(out IsLinkFound)")] public static void ReturnGetIsLinkFound(bool IsLinkFound) { gIsLinkFound = IsLinkFound; } #endregion 3.1.5.14 call return #endregion #region Initialize /// <summary> /// FSA initialize, it contains the follow operations: /// 1. The client connects to server. /// 2. The client sets up a session with server. /// 3. The client connects to a share on server. /// </summary> [Rule] public static void FsaInitial() { Condition.IsTrue(fsStates == FSStates.ReadyInitial); fsStates = FSStates.FinsihInitial; } #endregion #region rule methods #region get sut information /// <summary> /// The call part of the method GetOSInfo which is used to /// get the SUT platform. /// This is a call-return pattern /// </summary> [Rule(Action = "call GetOSInfo(out _)")] public static void CallGetSutInfo() { Condition.IsTrue(fsStates == FSStates.FinsihInitial); Condition.IsTrue(sutOSInfo == SutOSInfo.ReadyGetSutInfo); sutOSInfo = SutOSInfo.RequestGetSutInfo; } /// <summary> /// The return part of the method GetOSInfo which is used to /// get the SUT platform. /// This is a call-returns pattern. /// </summary> /// <param name="platForm">SUT platform</param> [Rule(Action = "return GetOSInfo(out platForm)")] public static void ReturnGetSutInfo(PlatformType platForm) { Condition.IsTrue(fsStates == FSStates.FinsihInitial); Condition.IsTrue(sutOSInfo == SutOSInfo.RequestGetSutInfo); sutPlatForm = platForm; sutOSInfo = SutOSInfo.FinishGetSutInfo; // Force Spec Explorer to expand sutPlatForm. Condition.IsTrue(sutPlatForm == PlatformType.NoneWindows || sutPlatForm == PlatformType.Windows); } #endregion #region get system config /// <summary> /// The call part of the method GetOSInfo which is used to /// get the system config information. /// This is a call-return pattern /// </summary> [Rule(Action = "call GetSystemConfig(out _)")] public static void CallGetystemConfig() { } /// <summary> /// The return part of the method GetOSInfo which is used to /// get the system config information. /// This is a call-returns pattern. /// </summary> /// <param name="securityContext">SSecurityContext</param> [Rule(Action = "return GetSystemConfig(out securityContext)")] public static void ReturnGetystemConfig(SSecurityContext securityContext) { Condition.IsTrue(securityContext.privilegeSet == PrivilegeSet.SeRestorePrivilege); Condition.IsTrue(!securityContext.isImplementsEncryption); Condition.IsTrue(!securityContext.isSecurityContextSIDsContainWellKnown); gSecurityContext = securityContext; } #endregion #region get file volum size /// <summary> /// The call part of the method GetFileVolumSize which is used to /// get file volum size. /// This is a call-return pattern /// </summary> [Rule(Action = "call GetFileVolumSize(out _)")] public static void CallGetFileVolumSize() { } /// <summary> /// The return part of the method GetFileVolumSize which is used to /// get file volum size. /// This is a call-returns pattern. /// </summary> /// <param name="openFileVolumeSize">file volum size</param> [Rule(Action = "return GetFileVolumSize(out openFileVolumeSize)")] public static void ReturnGetFileVolumSize(long openFileVolumeSize) { // It need openFileVolumeSize equal to 4096 Condition.IsTrue(openFileVolumeSize == 4096); gOpenFileVolumeSize = openFileVolumeSize; } #endregion #region get if Quotas is Supported /// <summary> /// The call part of the method GetIFQuotasSupported which is used to /// get if Quotas is supported. /// This is a call-return pattern /// </summary> [Rule(Action = "call GetIFQuotasSupported(out _)")] public static void CallGetIFQuotasSupported() { } /// <summary> /// The return part of the method GetIFQuotasSupported which is used to /// get if Quotas is supported. /// This is a call-returns pattern. /// </summary> /// <param name="isQuotasSupported">true: if Quotas is supported</param> [Rule(Action = "return GetIFQuotasSupported(out isQuotasSupported)")] public static void ReturnGetIFQuotasSupported(bool isQuotasSupported) { gisQuotasSupported = isQuotasSupported; } #endregion #region get if ObjectIDs is supported /// <summary> /// The call part of the method GetIFQuotasSupported which is used to /// get if ObjectIDs is supported. /// This is a call-return pattern /// </summary> [Rule(Action = "call GetIFObjectIDsSupported(out _)")] public static void CallGetIFObjectIDsSupported() { } /// <summary> /// The return part of the method GetIFQuotasSupported which is used to /// get if ObjectIDs is supported. /// This is a call-returns pattern. /// </summary> /// <param name="isObjectIDsSupported">true: if ObjectIDs is supported</param> [Rule(Action = "return GetIFObjectIDsSupported(out isObjectIDsSupported)")] public static void ReturnGetIFObjectIDsSupported(bool isObjectIDsSupported) { gisObjectIDsSupported = isObjectIDsSupported; } #endregion #endregion } }
using System; using System.Xml.Serialization; using Wolfram.NETLink; using DAQ.Environment; using DAQ.Pattern; using DAQ.Mathematica; using DecelerationConfig; using ScanMaster.Acquire.Patterns; using ScanMaster.Acquire.Plugin; namespace ScanMaster.Acquire.Plugins { /// <summary> /// A plugin for deceleration patterns. Make sure that the sequenceLength setting is always a multiple of 2 (see /// documentation for PumpProbePatternPlugin to find out why). /// /// </summary> [Serializable] public class DecelerationPatternPlugin : SupersonicPGPluginBase { [NonSerialized] private DecelerationPatternBuilder decelPatternBuilder; private TimingSequence decelSequence = null; protected override void InitialiseCustomSettings() { settings["delayToDeceleration"] = 0; settings["molecule"] = "YbF"; settings["voltage"] = 10.0; settings["initspeed"] = 337; settings["initposition"] = 0; settings["onposition"] = 24.0; settings["offposition"] = 32.0; settings["numberOfStages"] = 21; settings["sequenceLength"] = 2; settings["resonanceOrder"] = 1; settings["decelOnStart"] = 300; settings["decelOnDuration"] = 800; settings["modulationMode"] = "BurstAndOff"; settings["jState"] = 0; settings["mState"] = 0; } protected override void DoAcquisitionStarting() { decelPatternBuilder = new DecelerationPatternBuilder(); // prepare the deceleration sequence buildDecelerationSequence(); } protected override IPatternSource GetScanPattern() { decelPatternBuilder.Clear(); decelPatternBuilder.ShotSequence( (int)settings["padStart"], (int)settings["sequenceLength"], (int)settings["padShots"], (int)settings["flashlampPulseInterval"], (int)settings["valvePulseLength"], (int)settings["valveToQ"], (int)settings["flashToQ"], GateStartTimePGUnits, (int)settings["delayToDeceleration"], decelSequence, (string)settings["modulationMode"], (int)settings["decelOnStart"], (int)settings["decelOnDuration"], (bool)config.switchPlugin.Settings["switchActive"] ); decelPatternBuilder.BuildPattern(2 * ((int)settings["padShots"] + 1) * (int)settings["sequenceLength"] * (int)settings["flashlampPulseInterval"]); return decelPatternBuilder; } private void buildDecelerationSequence() { //get the settings we need double voltage = (double)settings["voltage"]; int initspeed = (int)settings["initspeed"]; double onposition = (double)settings["onposition"] / 1000; double offposition = (double)settings["offposition"] / 1000; int numberOfStages = (int)settings["numberOfStages"]; int resonanceOrder = (int)settings["resonanceOrder"]; int jState = (int)settings["jState"]; int mState = (int)settings["mState"]; // make the FieldMap FieldMap map = new FieldMap((string)Environs.FileSystem.Paths["decelerationUtilitiesPath"] + (string)Environs.Hardware.GetInfo("deceleratorFieldMap"), (int)Environs.Hardware.GetInfo("mapPoints"), (double)Environs.Hardware.GetInfo("mapStartPoint"), (double)Environs.Hardware.GetInfo("mapResolution")); //make the molecule Molecule mol = new Molecule((string)Environs.Hardware.GetInfo("moleculeName"), (double)Environs.Hardware.GetInfo("moleculeMass"), (double)Environs.Hardware.GetInfo("moleculeRotationalConstant"), (double)Environs.Hardware.GetInfo("moleculeDipoleMoment")); //make the decelerator and the experiment Decelerator decel = new Decelerator(); DecelerationExperiment experiment = new DecelerationExperiment(); //assign a map and a lens spacing to the decelerator decel.Map = map; decel.LensSpacing = (double)Environs.Hardware.GetInfo("deceleratorLensSpacing"); //assign decelerator, molecule, quantum state and switch structure to the experiment experiment.Decelerator = decel; experiment.Molecule = mol; experiment.QuantumState = new int[] { jState, mState }; experiment.Structure = (DecelerationExperiment.SwitchStructure)Environs.Hardware.GetInfo("deceleratorStructure"); //get the timing sequence double[] timesdouble = experiment.GetTimingSequence(voltage, onposition, offposition, initspeed, numberOfStages, resonanceOrder); // The list of times is in seconds and is measured from the moment when the synchronous molecule // reaches the decelerator. Add on the amount of time it takes to reach this point. // Then convert to the units of the clockFrequency and round to the nearest unit. double nominalTimeToDecelerator = (double)Environs.Hardware.GetInfo("sourceToSoftwareDecelerator") / initspeed; int[] times = new int[timesdouble.Length]; for (int i = 0; i < timesdouble.Length; i++) { times[i] = (int)Math.Round((int)settings["clockFrequency"] * (nominalTimeToDecelerator + timesdouble[i])); } int[] structure = new int[times.Length]; // the last switch must send all electrodes to ground structure[structure.Length - 1] = 0; // build the rest of the structure int k = 0; switch (experiment.Structure) { case DecelerationExperiment.SwitchStructure.H_Off_V_Off: while (k < structure.Length - 1) { if (k < structure.Length - 1) { structure[k] = 2; k++; } if (k < structure.Length - 1) { structure[k] = 0; k++; } if (k < structure.Length - 1) { structure[k] = 1; k++; } if (k < structure.Length - 1) { structure[k] = 0; k++; } } break; case DecelerationExperiment.SwitchStructure.V_Off_H_Off: while (k < structure.Length - 1) { if (k < structure.Length - 1) { structure[k] = 1; k++; } if (k < structure.Length - 1) { structure[k] = 0; k++; } if (k < structure.Length - 1) { structure[k] = 2; k++; } if (k < structure.Length - 1) { structure[k] = 0; k++; } } break; case DecelerationExperiment.SwitchStructure.H_V: while (k < structure.Length - 1) { if (k < structure.Length - 1) { structure[k] = 2; k++; } if (k < structure.Length - 1) { structure[k] = 1; k++; } } break; case DecelerationExperiment.SwitchStructure.V_H: while (k < structure.Length - 1) { if (k < structure.Length - 1) { structure[k] = 1; k++; } if (k < structure.Length - 1) { structure[k] = 2; k++; } } break; } // keep track of the state of the horizontal and vertical electrodes bool[] states = { false, false }; //{horizontal, vertical} decelSequence = new TimingSequence(); // The timing sequence is built within this for loop. The structure of the decelerator is encoded // as follows: 0 means everything off, 1 means V on, H off, 2 means H on V off and 3 means both on. for (int i = 0; i < times.Length && i < structure.Length; i++) { if (structure[i] == 0) //horizontal = false, vertical = false { if (states[0] != false) { decelSequence.Add("decelhplus", times[i], false); decelSequence.Add("decelhminus", times[i], false); states[0] = false; } if (states[1] != false) { decelSequence.Add("decelvplus", times[i], false); decelSequence.Add("decelvminus", times[i], false); states[1] = false; } } if (structure[i] == 1) //horizontal = false, vertical = true { if (states[0] != false) { decelSequence.Add("decelhplus", times[i], false); decelSequence.Add("decelhminus", times[i], false); states[0] = false; } if (states[1] != true) { decelSequence.Add("decelvplus", times[i], true); decelSequence.Add("decelvminus", times[i], true); states[1] = true; } } if (structure[i] == 2) //horizontal = true, vertical = false { if (states[0] != true) { decelSequence.Add("decelhplus", times[i], true); decelSequence.Add("decelhminus", times[i], true); states[0] = true; } if (states[1] != false) { decelSequence.Add("decelvplus", times[i], false); decelSequence.Add("decelvminus", times[i], false); states[1] = false; } } if (structure[i] == 3) //horizontal = true, vertical = true { if (states[0] != true) { decelSequence.Add("decelhplus", times[i], true); decelSequence.Add("decelhminus", times[i], true); states[0] = true; } if (states[1] != true) { decelSequence.Add("decelvplus", times[i], true); decelSequence.Add("decelvminus", times[i], true); states[1] = true; } } } Console.WriteLine(decelSequence.ToString()); } //// This is old code that uses a Mathematica package to generate the timing sequence //// Keep it here for now, so that we can make sure the two codes do the same thing. //private void buildDecelerationSequence() //{ // String molecule = (string)settings["molecule"]; // double voltage = (double)settings["voltage"]; // int initspeed = (int)settings["initspeed"]; // int initposition = (int)settings["initposition"]; // double onposition = (double)settings["onposition"]; // double offposition = (double)settings["offposition"]; // int numberOfStages = (int)settings["numberOfStages"]; // int resonanceOrder = (int)settings["resonanceOrder"]; // IKernelLink ml = MathematicaService.GetKernel(); // MathematicaService.LoadPackage((String)Environs.Info["SwitchSequenceCode"], false); // if (ml != null) // { // //Here's the call to the Mathematica makeSequence function // String argString = "makeSequence[" + molecule + ", " + voltage + ", " + initspeed + ", " + initposition + ", " + // onposition + ", " + offposition + ", " + numberOfStages + ", " + resonanceOrder + "]"; // ml.Evaluate(argString); // ml.WaitForAnswer(); // double[] timesdouble = (double[]) ml.GetArray(typeof(double),1); // get the list of switch times // // The list of times is in seconds and is measured from the moment when the synchronous molecule // // reaches the decelerator. Add on the amount of time it takes to reach this point. // // Then convert to the units of the clockFrequency and round to the nearest unit. // double nominalTimeToDecelerator = (double)Environs.Hardware.GetInfo("sourceToSoftwareDecelerator") / initspeed; // int[] times = new int[timesdouble.Length]; // for(int i = 0; i < timesdouble.Length; i++) // { // times[i] = (int)Math.Round((int)settings["clockFrequency"]*(nominalTimeToDecelerator + timesdouble[i])); // } // //Console.WriteLine("Generated Timing Sequence"); // decelSequence = new TimingSequence(); // ml.Evaluate("getVersion[]"); // ml.WaitForAnswer(); // decelSequence.Version = ml.GetString(); // ml.Evaluate("getDeceleratorName[]"); // ml.WaitForAnswer(); // decelSequence.Name = ml.GetString(); // // Get the decelerator structure // ml.Evaluate("getStructure[" + resonanceOrder + "]"); // ml.WaitForAnswer(); // int[] structure = (int[])ml.GetArray(typeof(int),1); // // keep track of the state of the horizontal and vertical electrodes // bool[] states = {false, false}; //{horizontal, vertical} // // The timing sequence is built within this for loop. The structure of the decelerator is encoded // // as follows: 0 means everything off, 1 means V on, H off, 2 means H on V off and 3 means both on. // for (int i = 0; i < times.Length && i < structure.Length; i++) // { // if (structure[i] == 0) //horizontal = false, vertical = false // { // if (states[0] != false) // { // decelSequence.Add("decelhplus", times[i], false); // decelSequence.Add("decelhminus", times[i], false); // states[0] = false; // } // if (states[1] != false) // { // decelSequence.Add("decelvplus", times[i], false); // decelSequence.Add("decelvminus", times[i], false); // states[1] = false; // } // } // if (structure[i] == 1) //horizontal = false, vertical = true // { // if (states[0] != false) // { // decelSequence.Add("decelhplus", times[i], false); // decelSequence.Add("decelhminus", times[i], false); // states[0] = false; // } // if (states[1] != true) // { // decelSequence.Add("decelvplus", times[i], true); // decelSequence.Add("decelvminus", times[i], true); // states[1] = true; // } // } // if (structure[i] == 2) //horizontal = true, vertical = false // { // if (states[0] != true) // { // decelSequence.Add("decelhplus", times[i], true); // decelSequence.Add("decelhminus", times[i], true); // states[0] = true; // } // if (states[1] != false) // { // decelSequence.Add("decelvplus", times[i], false); // decelSequence.Add("decelvminus", times[i], false); // states[1] = false; // } // } // if (structure[i] == 3) //horizontal = true, vertical = true // { // if (states[0] != true) // { // decelSequence.Add("decelhplus", times[i], true); // decelSequence.Add("decelhminus", times[i], true); // states[0] = true; // } // if (states[1] != true) // { // decelSequence.Add("decelvplus", times[i], true); // decelSequence.Add("decelvminus", times[i], true); // states[1] = true; // } // } // } // Console.WriteLine(decelSequence.ToString()); // } //} } }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Media; using Fluent.Internal; /// <summary> /// Represent panel with ribbon tab items. /// It is automatically adjusting size of tabs /// </summary> public class RibbonTabsContainer : Panel, IScrollInfo { /// <summary> /// Initializes a new instance of the <see cref="RibbonTabsContainer"/> class. /// </summary> public RibbonTabsContainer() { this.Focusable = false; } static RibbonTabsContainer() { KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(RibbonTabsContainer), new FrameworkPropertyMetadata(KeyboardNavigationMode.Once)); KeyboardNavigation.DirectionalNavigationProperty.OverrideMetadata(typeof(RibbonTabsContainer), new FrameworkPropertyMetadata(KeyboardNavigationMode.Cycle)); } #region Layout Overridings /// <inheritdoc /> protected override Size MeasureOverride(Size availableSize) { if (this.InternalChildren.Count == 0) { return base.MeasureOverride(availableSize); } var desiredSize = this.MeasureChildrenDesiredSize(availableSize); // Step 1. If all tabs already fit, just return. if (availableSize.Width >= desiredSize.Width || DoubleUtil.AreClose(availableSize.Width, desiredSize.Width)) { // Hide separator lines between tabs this.UpdateSeparators(false, false); this.VerifyScrollData(availableSize.Width, desiredSize.Width); return desiredSize; } // Size reduction: // - calculate the overflow width // - get all visible tabs ordered by: // - non context tabs first // - largest tabs first // - then loop over all tabs and reduce their size in steps // - during each tabs reduction check if it's still the largest tab // - if it's still the largest tab reduce it's size further till there is no larger tab left var overflowWidth = desiredSize.Width - availableSize.Width; var visibleTabs = this.InternalChildren.Cast<RibbonTabItem>() .Where(x => x.Visibility != Visibility.Collapsed) .OrderBy(x => x.IsContextual) .ToList(); // did we change the size of any contextual tabs? var contextualTabsSizeChanged = false; // step size for reducing the size of tabs const int sizeChangeStepSize = 4; // loop while we got overflow left (still need to reduce more) and all tabs are larger than the minimum size while (overflowWidth > 0 && AreAnyTabsAboveMinimumSize(visibleTabs)) { var tabsChangedInSize = 0; foreach (var tab in visibleTabs.OrderByDescending(x => x.DesiredSize.Width)) { var widthBeforeMeasure = tab.DesiredSize.Width; // ignore tabs that are smaller or equal to the minimum size if (widthBeforeMeasure < MinimumRegularTabWidth || DoubleUtil.AreClose(widthBeforeMeasure, MinimumRegularTabWidth)) { continue; } var wasLargestTab = IsLargestTab(visibleTabs, tab.DesiredSize.Width, tab.IsContextual); // measure with reduced size, but at least the minimum size tab.Measure(new Size(Math.Max(MinimumRegularTabWidth, tab.DesiredSize.Width - sizeChangeStepSize), tab.DesiredSize.Height)); // calculate diff of measure before and after possible reduction var widthDifference = widthBeforeMeasure - tab.DesiredSize.Width; var didWidthChange = widthDifference > 0; // count as changed if diff is greater than zero tabsChangedInSize += didWidthChange ? 1 : 0; // was it a changed contextual tab? if (tab.IsContextual && didWidthChange) { contextualTabsSizeChanged = true; } // reduce remaining overflow width overflowWidth -= widthDifference; // break if no overflow width is left if (overflowWidth <= 0) { break; } // if the current tab was the largest tab break to reduce it's size further if (wasLargestTab && didWidthChange) { break; } } // break if no tabs changed their size if (tabsChangedInSize == 0) { break; } } desiredSize = this.GetChildrenDesiredSize(); // Add separator lines between // tabs to assist readability this.UpdateSeparators(true, contextualTabsSizeChanged || AreAnyTabsAboveMinimumSize(visibleTabs) == false); this.VerifyScrollData(availableSize.Width, desiredSize.Width); return desiredSize; } private static bool AreAnyTabsAboveMinimumSize(List<RibbonTabItem> tabs) { return tabs.Any(item => item.DesiredSize.Width > MinimumRegularTabWidth); } private static bool IsLargestTab(List<RibbonTabItem> tabs, double width, bool isContextual) { return tabs.Count > 1 && tabs.Any(x => x.IsContextual == isContextual && x.DesiredSize.Width > width) == false; } private Size MeasureChildrenDesiredSize(Size availableSize) { double width = 0; double height = 0; foreach (UIElement child in this.InternalChildren) { child.Measure(availableSize); width += child.DesiredSize.Width; height = Math.Max(height, child.DesiredSize.Height); } return new Size(width, height); } private Size GetChildrenDesiredSize() { double width = 0; double height = 0; foreach (UIElement child in this.InternalChildren) { width += child.DesiredSize.Width; height = Math.Max(height, child.DesiredSize.Height); } return new Size(width, height); } /// <inheritdoc /> protected override Size ArrangeOverride(Size finalSize) { var finalRect = new Rect(finalSize) { X = -this.HorizontalOffset }; var orderedChildren = this.InternalChildren.OfType<RibbonTabItem>() .OrderBy(x => x.Group != null); foreach (var item in orderedChildren) { finalRect.Width = item.DesiredSize.Width; finalRect.Height = Math.Max(finalSize.Height, item.DesiredSize.Height); item.Arrange(finalRect); finalRect.X += item.DesiredSize.Width; } return finalSize; } /// <summary> /// Updates separator visibility /// </summary> /// <param name="regularTabs">If this parameter true, regular tabs will have separators</param> /// <param name="contextualTabs">If this parameter true, contextual tabs will have separators</param> private void UpdateSeparators(bool regularTabs, bool contextualTabs) { foreach (RibbonTabItem tab in this.Children) { if (tab.IsContextual) { if (tab.IsSeparatorVisible != contextualTabs) { tab.IsSeparatorVisible = contextualTabs; } } else if (tab.IsSeparatorVisible != regularTabs) { tab.IsSeparatorVisible = regularTabs; } } } #endregion #region IScrollInfo Members /// <inheritdoc /> public ScrollViewer ScrollOwner { get { return this.ScrollData.ScrollOwner; } set { this.ScrollData.ScrollOwner = value; } } /// <inheritdoc /> public void SetHorizontalOffset(double offset) { var newValue = CoerceOffset(ValidateInputOffset(offset, nameof(this.HorizontalOffset)), this.scrollData.ExtentWidth, this.scrollData.ViewportWidth); if (DoubleUtil.AreClose(this.ScrollData.OffsetX, newValue) == false) { this.scrollData.OffsetX = newValue; this.InvalidateMeasure(); this.ScrollOwner?.InvalidateScrollInfo(); } } /// <inheritdoc /> public double ExtentWidth => this.ScrollData.ExtentWidth; /// <inheritdoc /> public double HorizontalOffset => this.ScrollData.OffsetX; /// <inheritdoc /> public double ViewportWidth => this.ScrollData.ViewportWidth; /// <inheritdoc /> public void LineLeft() { this.SetHorizontalOffset(this.HorizontalOffset - 16.0); } /// <inheritdoc /> public void LineRight() { this.SetHorizontalOffset(this.HorizontalOffset + 16.0); } /// <inheritdoc /> public Rect MakeVisible(Visual visual, Rect rectangle) { // We can only work on visuals that are us or children. // An empty rect has no size or position. We can't meaningfully use it. if (rectangle.IsEmpty || visual is null || ReferenceEquals(visual, this) || this.IsAncestorOf(visual) == false) { return Rect.Empty; } // Compute the child's rect relative to (0,0) in our coordinate space. var childTransform = visual.TransformToAncestor(this); rectangle = childTransform.TransformBounds(rectangle); // Initialize the viewport var viewport = new Rect(this.HorizontalOffset, rectangle.Top, this.ViewportWidth, rectangle.Height); rectangle.X += viewport.X; // Compute the offsets required to minimally scroll the child maximally into view. var minX = ComputeScrollOffsetWithMinimalScroll(viewport.Left, viewport.Right, rectangle.Left, rectangle.Right); // We have computed the scrolling offsets; scroll to them. this.SetHorizontalOffset(minX); // Compute the visible rectangle of the child relative to the viewport. viewport.X = minX; rectangle.Intersect(viewport); rectangle.X -= viewport.X; // Return the rectangle return rectangle; } private static double ComputeScrollOffsetWithMinimalScroll( double topView, double bottomView, double topChild, double bottomChild) { // # CHILD POSITION CHILD SIZE SCROLL REMEDY // 1 Above viewport <= viewport Down Align top edge of child & viewport // 2 Above viewport > viewport Down Align bottom edge of child & viewport // 3 Below viewport <= viewport Up Align bottom edge of child & viewport // 4 Below viewport > viewport Up Align top edge of child & viewport // 5 Entirely within viewport NA No scroll. // 6 Spanning viewport NA No scroll. // // Note: "Above viewport" = childTop above viewportTop, childBottom above viewportBottom // "Below viewport" = childTop below viewportTop, childBottom below viewportBottom // These child thus may overlap with the viewport, but will scroll the same direction /*bool fAbove = DoubleUtil.LessThan(topChild, topView) && DoubleUtil.LessThan(bottomChild, bottomView); bool fBelow = DoubleUtil.GreaterThan(bottomChild, bottomView) && DoubleUtil.GreaterThan(topChild, topView);*/ var fAbove = (topChild < topView) && (bottomChild < bottomView); var fBelow = (bottomChild > bottomView) && (topChild > topView); var fLarger = bottomChild - topChild > bottomView - topView; // Handle Cases: 1 & 4 above if ((fAbove && !fLarger) || (fBelow && fLarger)) { return topChild; } // Handle Cases: 2 & 3 above if (fAbove || fBelow) { return bottomChild - (bottomView - topView); } // Handle cases: 5 & 6 above. return topView; } /// <summary> /// Not implemented /// </summary> public void MouseWheelDown() { } /// <inheritdoc /> public void MouseWheelLeft() { this.SetHorizontalOffset(this.HorizontalOffset - 16); } /// <inheritdoc /> public void MouseWheelRight() { this.SetHorizontalOffset(this.HorizontalOffset + 16); } /// <summary> /// Not implemented /// </summary> public void MouseWheelUp() { } /// <summary> /// Not implemented /// </summary> public void LineDown() { } /// <summary> /// Not implemented /// </summary> public void LineUp() { } /// <summary> /// Not implemented /// </summary> public void PageDown() { } /// <inheritdoc /> public void PageLeft() { this.SetHorizontalOffset(this.HorizontalOffset - this.ViewportWidth); } /// <inheritdoc /> public void PageRight() { this.SetHorizontalOffset(this.HorizontalOffset + this.ViewportWidth); } /// <summary> /// Not implemented /// </summary> public void PageUp() { } /// <summary> /// Not implemented /// </summary> public void SetVerticalOffset(double offset) { } /// <inheritdoc /> public bool CanVerticallyScroll { get => false; set { } } /// <inheritdoc /> public bool CanHorizontallyScroll { get => true; set { } } /// <summary> /// Not implemented /// </summary> public double ExtentHeight => 0.0; /// <summary> /// Not implemented /// </summary> public double VerticalOffset => 0.0; /// <summary> /// Not implemented /// </summary> public double ViewportHeight => 0.0; // Gets scroll data info private ScrollData ScrollData => this.scrollData ?? (this.scrollData = new ScrollData()); // Scroll data info private ScrollData scrollData; private const double MinimumRegularTabWidth = 30D; // Validates input offset private static double ValidateInputOffset(double offset, string parameterName) { if (double.IsNaN(offset)) { throw new ArgumentOutOfRangeException(parameterName); } return Math.Max(0.0, offset); } // Verifies scrolling data using the passed viewport and extent as newly computed values. // Checks the X/Y offset and coerces them into the range [0, Extent - ViewportSize] // If extent, viewport, or the newly coerced offsets are different than the existing offset, // caches are updated and InvalidateScrollInfo() is called. private void VerifyScrollData(double viewportWidth, double extentWidth) { var isValid = true; if (double.IsInfinity(viewportWidth)) { viewportWidth = extentWidth; } var offsetX = CoerceOffset(this.ScrollData.OffsetX, extentWidth, viewportWidth); isValid &= DoubleUtil.AreClose(viewportWidth, this.ScrollData.ViewportWidth); isValid &= DoubleUtil.AreClose(extentWidth, this.ScrollData.ExtentWidth); isValid &= DoubleUtil.AreClose(this.ScrollData.OffsetX, offsetX); this.ScrollData.ViewportWidth = viewportWidth; // Prevent flickering by only using extentWidth if it's at least 2 larger than viewportWidth if (viewportWidth + 2 < extentWidth) { this.scrollData.ExtentWidth = extentWidth; } else { // Or we show show the srollbar if all tabs are at their minimum width or smaller // but do this early (if extent + 2 is equal or larger than the viewport, or they are equal) if (extentWidth + 2 >= viewportWidth || DoubleUtil.AreClose(extentWidth, viewportWidth)) { var visibleTabs = this.InternalChildren.Cast<RibbonTabItem>().Where(item => item.Visibility != Visibility.Collapsed).ToList(); var newExtentWidth = viewportWidth; if (visibleTabs.Any() && visibleTabs.All(item => DoubleUtil.AreClose(item.DesiredSize.Width, MinimumRegularTabWidth) || item.DesiredSize.Width < MinimumRegularTabWidth)) { if (DoubleUtil.AreClose(newExtentWidth, viewportWidth)) { newExtentWidth += 1; } this.ScrollData.ExtentWidth = newExtentWidth; } else { this.scrollData.ExtentWidth = viewportWidth; } } else { this.scrollData.ExtentWidth = viewportWidth; } } this.ScrollData.OffsetX = offsetX; if (isValid == false) { this.ScrollOwner?.InvalidateScrollInfo(); } } // Returns an offset coerced into the [0, Extent - Viewport] range. private static double CoerceOffset(double offset, double extent, double viewport) { if (offset > extent - viewport) { offset = extent - viewport; } if (offset < 0) { offset = 0; } return offset; } #endregion } #region ScrollData /// <summary> /// Helper class to hold scrolling data. /// This class exists to reduce working set when SCP is delegating to another implementation of ISI. /// Standard "extra pointer always for less data sometimes" cache savings model: /// </summary> internal class ScrollData { /// <summary> /// Scroll viewer /// </summary> internal ScrollViewer ScrollOwner { get; set; } /// <summary> /// Scroll offset /// </summary> internal double OffsetX { get; set; } /// <summary> /// ViewportSize is computed from our FinalSize, but may be in different units. /// </summary> internal double ViewportWidth { get; set; } /// <summary> /// Extent is the total size of our content. /// </summary> internal double ExtentWidth { get; set; } } #endregion ScrollData }
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 SocialNetwork.Services.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>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
//----------------------------------------------------------------------------- // Filename: SIPConstants.cs // // Description: SIP constants. // // History: // 17 Sep 2005 Aaron Clauson Created. // // License: // This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php // // Copyright (c) 2006 Aaron Clauson (aaron@sipsorcery.com), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com) // 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 SIP Sorcery PTY LTD. // nor the names of its contributors may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, // BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- using System; using SIPSorcery.Sys; #if UNITTEST using NUnit.Framework; #endif namespace SIPSorcery.SIP { public class SIPConstants { public const string CRLF = "\r\n"; public const string SIP_VERSION_STRING = "SIP"; public const int SIP_MAJOR_VERSION = 2; public const int SIP_MINOR_VERSION = 0; public const string SIP_FULLVERSION_STRING = "SIP/2.0"; public const int NONCE_TIMEOUT_MINUTES = 5; // Length of time an issued nonce is valid for. public const int SIP_MAXIMUM_RECEIVE_LENGTH = 65535; // Any SIP messages over this size will generate an error. public const int SIP_MAXIMUM_UDP_SEND_LENGTH = 1300; // Any SIP messages over this size should be prevented from using a UDP transport. public const string SIP_USERAGENT_STRING = "www.sipsorcery.com"; public const string SIP_SERVER_STRING = "www.sipsorcery.com"; public const string SIP_REQUEST_REGEX = @"^\w+ .* SIP/.*"; // bnf: Request-Line = Method SP Request-URI SP SIP-Version CRLF public const string SIP_RESPONSE_REGEX = @"^SIP/.* \d{3}"; // bnf: Status-Line = SIP-Version SP Status-Code SP Reason-Phrase CRLF public const string SIP_BRANCH_MAGICCOOKIE = "z9hG4bK"; public const string SIP_DEFAULT_USERNAME = "Anonymous"; public const string SIP_DEFAULT_FROMURI = "sip:thisis@anonymous.invalid"; public const string SIP_REGISTER_REMOVEALL = "*"; // The value in a REGISTER request id a UA wishes to remove all REGISTER bindings. public const string SIP_LOOSEROUTER_PARAMETER = "lr"; public const string SIP_REMOTEHANGUP_CAUSE = "remote end hungup"; public const char HEADER_DELIMITER_CHAR = ':'; public const int DEFAULT_MAX_FORWARDS = 70; public const int DEFAULT_REGISTEREXPIRY_SECONDS = 600; public const int DEFAULT_SIP_PORT = 5060; public const int DEFAULT_SIP_TLS_PORT = 5061; public const int MAX_SIP_PORT = 65535; public const string NAT_SENDKEEPALIVES_VALUE = "y"; //public const string SWITCHBOARD_USER_AGENT_PREFIX = "sipsorcery-switchboard"; } public enum SIPMessageTypesEnum { Unknown = 0, Request = 1, Response = 2, } public class SIPTimings { public const int T1 = 500; // Value of the SIP defined timer T1 in milliseconds and is the time for the first retransmit. public const int T2 = 4000; // Value of the SIP defined timer T2 in milliseconds and is the maximum time between retransmits. public const int T6 = 64 * T1; // Value of the SIP defined timer T6 in milliseconds and is the period after which a transaction has timed out. public const int MAX_RING_TIME = 180000; // The number of milliseconds a transaction can stay in the proceeding state (i.e. an INVITE will ring for) before the call is given up and timed out. } public enum SIPSchemesEnum { sip = 1, sips = 2, } public class SIPSchemesType { public static SIPSchemesEnum GetSchemeType(string schemeType) { return (SIPSchemesEnum)Enum.Parse(typeof(SIPSchemesEnum), schemeType, true); } public static bool IsAllowedScheme(string schemeType) { try { Enum.Parse(typeof(SIPSchemesEnum), schemeType, true); return true; } catch { return false; } } } public enum SIPProtocolsEnum { udp = 1, tcp = 2, tls = 3, // sctp = 4, // Not supported. } public class SIPProtocolsType { public static SIPProtocolsEnum GetProtocolType(string protocolType) { return (SIPProtocolsEnum)Enum.Parse(typeof(SIPProtocolsEnum), protocolType, true); } public static SIPProtocolsEnum GetProtocolTypeFromId(int protocolTypeId) { return (SIPProtocolsEnum)Enum.Parse(typeof(SIPProtocolsEnum), protocolTypeId.ToString(), true); } public static bool IsAllowedProtocol(string protocol) { try { Enum.Parse(typeof(SIPProtocolsEnum), protocol, true); return true; } catch { return false; } } } public class SIPHeaders { // SIP Header Keys. public const string SIP_HEADER_ACCEPT = "Accept"; public const string SIP_HEADER_ACCEPTENCODING = "Accept-Encoding"; public const string SIP_HEADER_ACCEPTLANGUAGE = "Accept-Language"; public const string SIP_HEADER_ALERTINFO = "Alert-Info"; public const string SIP_HEADER_ALLOW = "Allow"; public const string SIP_HEADER_ALLOW_EVENTS = "Allow-Events"; // RC3265 (SIP Events). public const string SIP_HEADER_AUTHENTICATIONINFO = "Authentication-Info"; public const string SIP_HEADER_AUTHORIZATION = "Authorization"; public const string SIP_HEADER_CALLID = "Call-ID"; public const string SIP_HEADER_CALLINFO = "Call-Info"; public const string SIP_HEADER_CONTACT = "Contact"; public const string SIP_HEADER_CONTENT_DISPOSITION = "Content-Disposition"; public const string SIP_HEADER_CONTENT_ENCODING = "Content-Encoding"; public const string SIP_HEADER_CONTENT_LANGUAGE = "Content-Language"; public const string SIP_HEADER_CONTENTLENGTH = "Content-Length"; public const string SIP_HEADER_CONTENTTYPE = "Content-Type"; public const string SIP_HEADER_CSEQ = "CSeq"; public const string SIP_HEADER_DATE = "Date"; public const string SIP_HEADER_ERROR_INFO = "Error-Info"; public const string SIP_HEADER_EVENT = "Event"; // RC3265 (SIP Events). public const string SIP_HEADER_ETAG = "SIP-ETag"; // RFC3903 public const string SIP_HEADER_EXPIRES = "Expires"; public const string SIP_HEADER_FROM = "From"; public const string SIP_HEADER_IN_REPLY_TO = "In-Reply-To"; public const string SIP_HEADER_MAXFORWARDS = "Max-Forwards"; public const string SIP_HEADER_MINEXPIRES = "Min-Expires"; public const string SIP_HEADER_MIME_VERSION = "MIME-Version"; public const string SIP_HEADER_ORGANIZATION = "Organization"; public const string SIP_HEADER_PRIORITY = "Priority"; public const string SIP_HEADER_PROXYAUTHENTICATION = "Proxy-Authenticate"; public const string SIP_HEADER_PROXYAUTHORIZATION = "Proxy-Authorization"; public const string SIP_HEADER_PROXY_REQUIRE = "Proxy-Require"; public const string SIP_HEADER_REASON = "Reason"; public const string SIP_HEADER_RECORDROUTE = "Record-Route"; public const string SIP_HEADER_REFERREDBY = "Referred-By"; // RFC 3515 "The Session Initiation Protocol (SIP) Refer Method". public const string SIP_HEADER_REFERSUB = "Refer-Sub"; // RFC 4488 Used to stop the implicit SIP event subscription on a REFER request. public const string SIP_HEADER_REFERTO = "Refer-To"; // RFC 3515 "The Session Initiation Protocol (SIP) Refer Method". public const string SIP_HEADER_REPLY_TO = "Reply-To"; public const string SIP_HEADER_REQUIRE = "Require"; public const string SIP_HEADER_RETRY_AFTER = "Retry-After"; public const string SIP_HEADER_ROUTE = "Route"; public const string SIP_HEADER_SERVER = "Server"; public const string SIP_HEADER_SUBJECT = "Subject"; public const string SIP_HEADER_SUBSCRIPTION_STATE = "Subscription-State"; // RC3265 (SIP Events). public const string SIP_HEADER_SUPPORTED = "Supported"; public const string SIP_HEADER_TIMESTAMP = "Timestamp"; public const string SIP_HEADER_TO = "To"; public const string SIP_HEADER_UNSUPPORTED = "Unsupported"; public const string SIP_HEADER_USERAGENT = "User-Agent"; public const string SIP_HEADER_VIA = "Via"; public const string SIP_HEADER_WARNING = "Warning"; public const string SIP_HEADER_WWWAUTHENTICATE = "WWW-Authenticate"; // SIP Compact Header Keys. public const string SIP_COMPACTHEADER_ALLOWEVENTS = "u"; // RC3265 (SIP Events). public const string SIP_COMPACTHEADER_CALLID = "i"; public const string SIP_COMPACTHEADER_CONTACT = "m"; public const string SIP_COMPACTHEADER_CONTENTLENGTH = "l"; public const string SIP_COMPACTHEADER_CONTENTTYPE = "c"; public const string SIP_COMPACTHEADER_EVENT = "o"; // RC3265 (SIP Events). public const string SIP_COMPACTHEADER_FROM = "f"; public const string SIP_COMPACTHEADER_REFERTO = "r"; // RFC 3515 "The Session Initiation Protocol (SIP) Refer Method". public const string SIP_COMPACTHEADER_SUBJECT = "s"; public const string SIP_COMPACTHEADER_SUPPORTED = "k"; public const string SIP_COMPACTHEADER_TO = "t"; public const string SIP_COMPACTHEADER_VIA = "v"; // Custom SIP headers to allow proxy to communicate network info to internal servers. public const string SIP_HEADER_PROXY_RECEIVEDON = "Proxy-ReceivedOn"; public const string SIP_HEADER_PROXY_RECEIVEDFROM = "Proxy-ReceivedFrom"; public const string SIP_HEADER_PROXY_SENDFROM = "Proxy-SendFrom"; // Custom SIP headers to interact with the SIP Sorcery switchboard. public const string SIP_HEADER_SWITCHBOARD_ORIGINAL_CALLID = "Switchboard-OriginalCallID"; //public const string SIP_HEADER_SWITCHBOARD_CALLER_DESCRIPTION = "Switchboard-CallerDescription"; public const string SIP_HEADER_SWITCHBOARD_LINE_NAME = "Switchboard-LineName"; //public const string SIP_HEADER_SWITCHBOARD_ORIGINAL_FROM = "Switchboard-OriginalFrom"; //public const string SIP_HEADER_SWITCHBOARD_FROM_CONTACT_URL = "Switchboard-FromContactURL"; public const string SIP_HEADER_SWITCHBOARD_OWNER = "Switchboard-Owner"; //public const string SIP_HEADER_SWITCHBOARD_ORIGINAL_TO = "Switchboard-OriginalTo"; public const string SIP_HEADER_SWITCHBOARD_TERMINATE = "Switchboard-Terminate"; //public const string SIP_HEADER_SWITCHBOARD_TOKEN = "Switchboard-Token"; //public const string SIP_HEADER_SWITCHBOARD_TOKENREQUEST = "Switchboard-TokenRequest"; // Custom SIP headers for CRM integration. public const string SIP_HEADER_CRM_PERSON_NAME = "CRM-PersonName"; public const string SIP_HEADER_CRM_COMPANY_NAME = "CRM-CompanyName"; public const string SIP_HEADER_CRM_PICTURE_URL = "CRM-PictureURL"; } public class SIPHeaderAncillary { // Header parameters used in the core SIP protocol. public const string SIP_HEADERANC_TAG = "tag"; public const string SIP_HEADERANC_BRANCH = "branch"; public const string SIP_HEADERANC_RECEIVED = "received"; public const string SIP_HEADERANC_TRANSPORT = "transport"; // Via header parameter, documented in RFC 3581 "An Extension to the Session Initiation Protocol (SIP) // for Symmetric Response Routing". public const string SIP_HEADERANC_RPORT = "rport"; // SIP header parameter from RFC 3515 "The Session Initiation Protocol (SIP) Refer Method". public const string SIP_REFER_REPLACES = "Replaces"; } /// <summary> /// Authorization Headers /// </summary> public class AuthHeaders { public const string AUTH_DIGEST_KEY = "Digest"; public const string AUTH_REALM_KEY = "realm"; public const string AUTH_NONCE_KEY = "nonce"; public const string AUTH_USERNAME_KEY = "username"; public const string AUTH_RESPONSE_KEY = "response"; public const string AUTH_URI_KEY = "uri"; public const string AUTH_ALGORITHM_KEY = "algorithm"; public const string AUTH_CNONCE_KEY = "cnonce"; public const string AUTH_NONCECOUNT_KEY = "nc"; public const string AUTH_QOP_KEY = "qop"; public const string AUTH_OPAQUE_KEY = "opaque"; } public enum SIPMethodsEnum { NONE = 0, UNKNOWN = 1, // Core. REGISTER = 2, INVITE = 3, BYE = 4, ACK = 5, CANCEL = 6, OPTIONS = 7, INFO = 8, // RFC2976. NOTIFY = 9, // RFC3265. SUBSCRIBE = 10, // RFC3265. PUBLISH = 11, // RFC3903. PING = 13, REFER = 14, // RFC3515 "The Session Initiation Protocol (SIP) Refer Method" MESSAGE = 15, // RFC3428. PRACK = 16, // RFC3262. UPDATE = 17, // RFC3311. } public class SIPMethods { public static SIPMethodsEnum GetMethod(string method) { SIPMethodsEnum sipMethod = SIPMethodsEnum.UNKNOWN; try { sipMethod = (SIPMethodsEnum)Enum.Parse(typeof(SIPMethodsEnum), method, true); } catch{} return sipMethod; } } public enum SIPResponseStatusCodesEnum { None = 0, // Informational Trying = 100, Ringing = 180, CallIsBeingForwarded = 181, Queued = 182, SessionProgress = 183, // Success Ok = 200, Accepted = 202, // RC3265 (SIP Events). NoNotification = 204, // Redirection MultipleChoices = 300, MovedPermanently = 301, MovedTemporarily = 302, UseProxy = 303, AlternativeService = 304, // Client-Error BadRequest = 400, Unauthorised = 401, PaymentRequired = 402, Forbidden = 403, NotFound = 404, MethodNotAllowed = 405, NotAcceptable = 406, ProxyAuthenticationRequired = 407, RequestTimeout = 408, Gone = 410, ConditionalRequestFailed = 412, RequestEntityTooLarge = 413, RequestURITooLong = 414, UnsupportedMediaType = 415, UnsupportedURIScheme = 416, UnknownResourcePriority = 417, BadExtension = 420, ExtensionRequired = 421, SessionIntervalTooSmall = 422, IntervalTooBrief = 423, UseIdentityHeader = 428, ProvideReferrerIdentity = 429, FlowFailed = 430, AnonymityDisallowed = 433, BadIdentityInfo = 436, UnsupportedCertificate = 437, InvalidIdentityHeader = 438, FirstHopLacksOutboundSupport = 439, MaxBreadthExceeded = 440, ConsentNeeded = 470, TemporarilyUnavailable = 480, CallLegTransactionDoesNotExist = 481, LoopDetected = 482, TooManyHops = 483, AddressIncomplete = 484, Ambiguous = 485, BusyHere = 486, RequestTerminated = 487, NotAcceptableHere = 488, BadEvent = 489, // RC3265 (SIP Events). RequestPending = 491, Undecipherable = 493, SecurityAgreementRequired = 580, // Server Failure. InternalServerError = 500, NotImplemented = 501, BadGateway = 502, ServiceUnavailable = 503, ServerTimeout = 504, SIPVersionNotSupported = 505, MessageTooLarge = 513, PreconditionFailure = 580, // Global Failures. BusyEverywhere = 600, Decline = 603, DoesNotExistAnywhere = 604, NotAcceptableAnywhere = 606, } public class SIPResponseStatusCodes { public static SIPResponseStatusCodesEnum GetStatusTypeForCode(int statusCode) { return (SIPResponseStatusCodesEnum)Enum.Parse(typeof(SIPResponseStatusCodesEnum), statusCode.ToString(), true); } } public enum SIPUserAgentRoles { Unknown = 0, Client = 1, // UAC. Server = 2, // UAS. } public class SIPMIMETypes { public const string DIALOG_INFO_CONTENT_TYPE = "application/dialog-info+xml"; // RFC4235 INVITE dialog event package. public const string MWI_CONTENT_TYPE = "application/simple-message-summary"; // RFC3842 MWI event package. public const string REFER_CONTENT_TYPE = "message/sipfrag"; // RFC3515 REFER event package. public const string MWI_TEXT_TYPE = "text/text"; public const string PRESENCE_NOTIFY_CONTENT_TYPE = "application/pidf+xml"; // RFC3856 presence event package. } /// <summary> /// For SIP URI user portion the reserved characters below need to be escaped. /// reserved = ";" / "/" / "?" / ":" / "@" / "&" / "=" / "+" / "$" / "," /// user-unreserved = "&" / "=" / "+" / "$" / "," / ";" / "?" / "/" /// Leaving to be escaped = ":" / "@" /// /// For SIP URI parameters different characters are unreserved (just to amke life difficult). /// reserved = ";" / "/" / "?" / ":" / "@" / "&" / "=" / "+" / "$" / "," /// param-unreserved = "[" / "]" / "/" / ":" / "&" / "+" / "$" /// Leaving to be escaped = ";" / "?" / "@" / "=" / "," /// </summary> public static class SIPEscape { public static string SIPURIUserEscape(string unescapedString) { string result = unescapedString; if (!result.IsNullOrBlank()) { result = result.Replace(":", "%3A"); result = result.Replace("@", "%40"); result = result.Replace(" ", "%20"); } return result; } public static string SIPURIUserUnescape(string escapedString) { string result = escapedString; if (!result.IsNullOrBlank()) { result = result.Replace("%3A", ":"); result = result.Replace("%3a", ":"); result = result.Replace("%20", " "); } return result; } public static string SIPURIParameterEscape(string unescapedString) { string result = unescapedString; if (!result.IsNullOrBlank()) { result = result.Replace(";", "%3B"); result = result.Replace("?", "%3F"); result = result.Replace("@", "%40"); result = result.Replace("=", "%3D"); result = result.Replace(",", "%2C"); result = result.Replace(" ", "%20"); } return result; } public static string SIPURIParameterUnescape(string escapedString) { string result = escapedString; if (!result.IsNullOrBlank()) { result = result.Replace("%3B", ";"); result = result.Replace("%3b", ";"); //result = result.Replace("%2F", "/"); //result = result.Replace("%2f", "/"); result = result.Replace("%3F", "?"); result = result.Replace("%3f", "?"); //result = result.Replace("%3A", ":"); //result = result.Replace("%3a", ":"); result = result.Replace("%40", "@"); //result = result.Replace("%26", "&"); result = result.Replace("%3D", "="); result = result.Replace("%3d", "="); //result = result.Replace("%2B", "+"); //result = result.Replace("%2b", "+"); //result = result.Replace("%24", "$"); result = result.Replace("%2C", ","); result = result.Replace("%2c", ","); result = result.Replace("%20", " "); } return result; } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Provisioning.Cloud.Async.Console { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// 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. #if WINDOWS using Microsoft.Diagnostics.Tracing; using Microsoft.Diagnostics.Tracing.Etlx; using Microsoft.Diagnostics.Tracing.Parsers.Clr; using Microsoft.Diagnostics.Tracing.Parsers.Kernel; using Microsoft.Diagnostics.Tracing.Stacks; using System; using System.Collections.Generic; using System.Diagnostics; #if HAS_PRIVATE_GC_EVENTS using Microsoft.Diagnostics.Tracing.Parsers.ClrPrivate; #endif namespace GCPerfTestFramework.Metrics.Builders { /// <summary> /// GCProcess holds information about GCs in a particular process. /// </summary> /// // Notes on parsing GC events: // GC events need to be interpreted in sequence and if we attach we // may not get the whole sequence of a GC. We discard the incomplete // GC from the beginning and ending. // // We can make the assumption if we have the events from the private // provider it means we have events from public provider, but not the // other way around. // // All GC events are at informational level except the following: // AllocTick from the public provider // GCJoin from the private provider // We may only have events at the informational level, not verbose level. // internal class GCProcess { internal static IDictionary<int, GCProcess> Collect( TraceEventSource source, float sampleIntervalMSec, IDictionary<int, GCProcess> perProc = null, MutableTraceEventStackSource stackSource = null, Predicate<TraceEvent> filterFunc = null) { if (perProc == null) { perProc = new Dictionary<int, GCProcess>(); } source.Kernel.AddCallbackForEvents(delegate (ProcessCtrTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } var stats = perProc.GetOrCreate(data.ProcessID); stats.PeakVirtualMB = ((double)data.PeakVirtualSize) / 1000000.0; stats.PeakWorkingSetMB = ((double)data.PeakWorkingSetSize) / 1000000.0; }); Action<RuntimeInformationTraceData> doAtRuntimeStart = delegate (RuntimeInformationTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } var stats = perProc.GetOrCreate(data.ProcessID); stats.RuntimeVersion = "V " + data.VMMajorVersion.ToString() + "." + data.VMMinorVersion + "." + data.VMBuildNumber + "." + data.VMQfeNumber; stats.StartupFlags = data.StartupFlags; stats.Bitness = (data.RuntimeDllPath.ToLower().Contains("framework64") ? 64 : 32); if (stats.CommandLine == null) stats.CommandLine = data.CommandLine; }; // log at both startup and rundown //var clrRundown = new ClrRundownTraceEventParser(source); //clrRundown.RuntimeStart += doAtRuntimeStart; source.Clr.AddCallbackForEvent("Runtime/Start", doAtRuntimeStart); Action<ProcessTraceData> processStartCallback = data => { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } var stats = perProc.GetOrCreate(data.ProcessID); if (!string.IsNullOrEmpty(data.KernelImageFileName)) { // When we just have an EventSource (eg, the source was created by // ETWTraceEventSource), we don't necessarily have the process names // decoded - it all depends on whether we have seen a ProcessStartGroup // event or not. When the trace was taken after the process started we // know we didn't see such an event. string name = GetImageName(data.KernelImageFileName); // Strictly speaking, this is not really fixing it 'cause // it doesn't handle when a process with the same name starts // with the same pid. The chance of that happening is really small. if (stats.isDead == true) { stats = new GCProcess(); stats.Init(data); perProc[data.ProcessID] = stats; } } var commandLine = data.CommandLine; if (!string.IsNullOrEmpty(commandLine)) stats.CommandLine = commandLine; }; source.Kernel.AddCallbackForEvent("Process/Start", processStartCallback); source.Kernel.AddCallbackForEvent("Process/DCStart", processStartCallback); Action<ProcessTraceData> processEndCallback = delegate (ProcessTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } var stats = perProc.GetOrCreate(data.ProcessID); if (string.IsNullOrEmpty(stats.ProcessName)) { stats.ProcessName = GetImageName(data.KernelImageFileName); } if (data.OpcodeName == "Stop") { stats.isDead = true; } }; source.Kernel.AddCallbackForEvent("Process/Stop", processEndCallback); source.Kernel.AddCallbackForEvent("Process/DCStop", processEndCallback); #if (!CAP) CircularBuffer<ThreadWorkSpan> RecentThreadSwitches = new CircularBuffer<ThreadWorkSpan>(10000); source.Kernel.AddCallbackForEvent("Thread/CSwitch", delegate (CSwitchTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } RecentThreadSwitches.Add(new ThreadWorkSpan(data)); GCProcess stats; if (perProc.TryGetValue(data.ProcessID, out stats)) { stats.ThreadId2Priority[data.NewThreadID] = data.NewThreadPriority; if (stats.IsServerGCThread(data.ThreadID) > -1) { stats.ServerGcHeap2ThreadId[data.ProcessorNumber] = data.ThreadID; } } foreach (var gcProcess in perProc.Values) { GCEvent _event = gcProcess.GetCurrentGC(); // If we are in the middle of a GC. if (_event != null) { if ((_event.Type != GCType.BackgroundGC) && (gcProcess.isServerGCUsed == 1)) { _event.AddServerGcThreadSwitch(new ThreadWorkSpan(data)); } } } }); CircularBuffer<ThreadWorkSpan> RecentCpuSamples = new CircularBuffer<ThreadWorkSpan>(1000); StackSourceSample sample = new StackSourceSample(stackSource); source.Kernel.AddCallbackForEvent("PerfInfo/Sample", delegate (SampledProfileTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } RecentCpuSamples.Add(new ThreadWorkSpan(data)); GCProcess processWithGc = null; foreach (var gcProcess in perProc.Values) { GCEvent e = gcProcess.GetCurrentGC(); // If we are in the middle of a GC. if (e != null) { if ((e.Type != GCType.BackgroundGC) && (gcProcess.isServerGCUsed == 1)) { e.AddServerGcSample(new ThreadWorkSpan(data)); processWithGc = gcProcess; } } } if (stackSource != null && processWithGc != null) { GCEvent e = processWithGc.GetCurrentGC(); sample.Metric = 1; sample.TimeRelativeMSec = data.TimeStampRelativeMSec; var nodeName = string.Format("Server GCs #{0} in {1} (PID:{2})", e.GCNumber, processWithGc.ProcessName, processWithGc.ProcessID); var nodeIndex = stackSource.Interner.FrameIntern(nodeName); sample.StackIndex = stackSource.Interner.CallStackIntern(nodeIndex, stackSource.GetCallStack(data.CallStackIndex(), data)); stackSource.AddSample(sample); } GCProcess stats; if (perProc.TryGetValue(data.ProcessID, out stats)) { if (stats.IsServerGCThread(data.ThreadID) > -1) { stats.ServerGcHeap2ThreadId[data.ProcessorNumber] = data.ThreadID; } var cpuIncrement = sampleIntervalMSec; stats.ProcessCpuMSec += cpuIncrement; GCEvent _event = stats.GetCurrentGC(); // If we are in the middle of a GC. if (_event != null) { bool isThreadDoingGC = false; if ((_event.Type != GCType.BackgroundGC) && (stats.isServerGCUsed == 1)) { int heapIndex = stats.IsServerGCThread(data.ThreadID); if (heapIndex != -1) { _event.AddServerGCThreadTime(heapIndex, cpuIncrement); isThreadDoingGC = true; } } else if (data.ThreadID == stats.suspendThreadIDGC) { _event.GCCpuMSec += cpuIncrement; isThreadDoingGC = true; } else if (stats.IsBGCThread(data.ThreadID)) { Debug.Assert(stats.currentBGC != null); if (stats.currentBGC != null) stats.currentBGC.GCCpuMSec += cpuIncrement; isThreadDoingGC = true; } if (isThreadDoingGC) { stats.GCCpuMSec += cpuIncrement; } } } }); #endif source.Clr.AddCallbackForEvent("GC/SuspendEEStart", delegate (GCSuspendEETraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } var stats = perProc.GetOrCreate(data.ProcessID); switch (data.Reason) { case GCSuspendEEReason.SuspendForGC: stats.suspendThreadIDGC = data.ThreadID; break; case GCSuspendEEReason.SuspendForGCPrep: stats.suspendThreadIDBGC = data.ThreadID; break; default: stats.suspendThreadIDOther = data.ThreadID; break; } stats.suspendTimeRelativeMSec = data.TimeStampRelativeMSec; }); // In 2.0 we didn't have this event. source.Clr.AddCallbackForEvent("GC/SuspendEEStop", delegate (GCNoUserDataTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc.GetOrCreate(data.ProcessID); if ((stats.suspendThreadIDBGC > 0) && (stats.currentBGC != null)) { stats.currentBGC._SuspendDurationMSec += data.TimeStampRelativeMSec - stats.suspendTimeRelativeMSec; } stats.suspendEndTimeRelativeMSec = data.TimeStampRelativeMSec; }); source.Clr.AddCallbackForEvent("GC/RestartEEStop", delegate (GCNoUserDataTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc.GetOrCreate(data.ProcessID); GCEvent _event = stats.GetCurrentGC(); if (_event != null) { if (_event.Type == GCType.BackgroundGC) { stats.AddConcurrentPauseTime(_event, data.TimeStampRelativeMSec); } else { Debug.Assert(_event.PauseStartRelativeMSec != 0); // In 2.0 Concurrent GC, since we don't know the GC's type we can't tell if it's concurrent // or not. But we know we don't have nested GCs there so simply check if we have received the // GCStop event; if we have it means it's a blocking GC; otherwise it's a concurrent GC so // simply add the pause time to the GC without making the GC complete. if (_event.GCDurationMSec == 0) { Debug.Assert(_event.is20Event); _event.isConcurrentGC = true; stats.AddConcurrentPauseTime(_event, data.TimeStampRelativeMSec); } else { _event.PauseDurationMSec = data.TimeStampRelativeMSec - _event.PauseStartRelativeMSec; if (_event.HeapStats != null) { _event.isComplete = true; stats.lastCompletedGC = _event; } } } } // We don't change between a GC end and the pause resume. //Debug.Assert(stats.allocTickAtLastGC == stats.allocTickCurrentMB); // Mark that we are not in suspension anymore. stats.suspendTimeRelativeMSec = -1; stats.suspendThreadIDOther = -1; stats.suspendThreadIDBGC = -1; stats.suspendThreadIDGC = -1; }); source.Clr.AddCallbackForEvent("GC/AllocationTick", delegate (GCAllocationTickTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc.GetOrCreate(data.ProcessID); if (stats.HasAllocTickEvents == false) { stats.HasAllocTickEvents = true; } double valueMB = data.GetAllocAmount(ref stats.SeenBadAllocTick) / 1000000.0; if (data.AllocationKind == GCAllocationKind.Small) { // Would this do the right thing or is it always 0 for SOH since AllocationAmount // is an int??? stats.allocTickCurrentMB[0] += valueMB; } else { stats.allocTickCurrentMB[1] += valueMB; } }); source.Clr.AddCallbackForEvent("GC/Start", delegate (GCStartTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc.GetOrCreate(data.ProcessID); // We need to filter the scenario where we get 2 GCStart events for each GC. if ((stats.suspendThreadIDGC > 0) && !((stats.events.Count > 0) && stats.events[stats.events.Count - 1].GCNumber == data.Count)) { GCEvent _event = new GCEvent(stats); Debug.Assert(0 <= data.Depth && data.Depth <= 2); // _event.GCGeneration = data.Depth; Old style events only have this in the GCStop event. _event.Reason = data.Reason; _event.GCNumber = data.Count; _event.Type = data.Type; _event.Index = stats.events.Count; _event.is20Event = data.IsClassicProvider; bool isEphemeralGCAtBGCStart = false; // Detecting the ephemeral GC that happens at the beginning of a BGC. if (stats.events.Count > 0) { GCEvent lastGCEvent = stats.events[stats.events.Count - 1]; if ((lastGCEvent.Type == GCType.BackgroundGC) && (!lastGCEvent.isComplete) && (data.Type == GCType.NonConcurrentGC)) { isEphemeralGCAtBGCStart = true; } } Debug.Assert(stats.suspendTimeRelativeMSec != -1); if (isEphemeralGCAtBGCStart) { _event.PauseStartRelativeMSec = data.TimeStampRelativeMSec; } else { _event.PauseStartRelativeMSec = stats.suspendTimeRelativeMSec; if (stats.suspendEndTimeRelativeMSec == -1) { stats.suspendEndTimeRelativeMSec = data.TimeStampRelativeMSec; } _event._SuspendDurationMSec = stats.suspendEndTimeRelativeMSec - stats.suspendTimeRelativeMSec; } _event.GCStartRelativeMSec = data.TimeStampRelativeMSec; stats.events.Add(_event); if (_event.Type == GCType.BackgroundGC) { stats.currentBGC = _event; _event.ProcessCpuAtLastGC = stats.ProcessCpuAtLastGC; } #if (!CAP) if ((_event.Type != GCType.BackgroundGC) && (stats.isServerGCUsed == 1)) { _event.SetUpServerGcHistory(); foreach (var s in RecentCpuSamples) _event.AddServerGcSample(s); foreach (var s in RecentThreadSwitches) _event.AddServerGcThreadSwitch(s); } #endif } }); source.Clr.AddCallbackForEvent("GC/PinObjectAtGCTime", delegate (PinObjectAtGCTimeTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc.GetOrCreate(data.ProcessID); GCEvent _event = stats.GetCurrentGC(); if (_event != null) { if (!_event.PinnedObjects.ContainsKey(data.ObjectID)) { _event.PinnedObjects.Add(data.ObjectID, data.ObjectSize); } else { _event.duplicatedPinningReports++; } } }); // Some builds have this as a public event, and some have it as a private event. // All will move to the private event, so we'll remove this code afterwards. source.Clr.AddCallbackForEvent("GC/PinPlugAtGCTime", delegate (PinPlugAtGCTimeTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc.GetOrCreate(data.ProcessID); GCEvent _event = stats.GetCurrentGC(); if (_event != null) { // ObjectID is supposed to be an IntPtr. But "Address" is defined as UInt64 in // TraceEvent. _event.PinnedPlugs.Add(new GCEvent.PinnedPlug(data.PlugStart, data.PlugEnd)); } }); source.Clr.AddCallbackForEvent("GC/Mark", delegate (GCMarkWithTypeTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc.GetOrCreate(data.ProcessID); stats.AddServerGCThreadFromMark(data.ThreadID, data.HeapNum); GCEvent _event = stats.GetCurrentGC(); if (_event != null) { if (_event.PerHeapMarkTimes == null) { _event.PerHeapMarkTimes = new Dictionary<int, GCEvent.MarkInfo>(); } if (!_event.PerHeapMarkTimes.ContainsKey(data.HeapNum)) { _event.PerHeapMarkTimes.Add(data.HeapNum, new GCEvent.MarkInfo()); } _event.PerHeapMarkTimes[data.HeapNum].MarkTimes[(int)data.Type] = data.TimeStampRelativeMSec; _event.PerHeapMarkTimes[data.HeapNum].MarkPromoted[(int)data.Type] = data.Promoted; } }); source.Clr.AddCallbackForEvent("GC/GlobalHeapHistory", delegate (GCGlobalHeapHistoryTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc.GetOrCreate(data.ProcessID); stats.ProcessGlobalHistory(data); }); source.Clr.AddCallbackForEvent("GC/PerHeapHistory", delegate (GCPerHeapHistoryTraceData3 data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc.GetOrCreate(data.ProcessID); stats.ProcessPerHeapHistory(data); }); #if HAS_PRIVATE_GC_EVENTS // See if the source knows about the CLR Private provider, if it does, then var gcPrivate = new ClrPrivateTraceEventParser(source); gcPrivate.GCPinPlugAtGCTime += delegate (PinPlugAtGCTimeTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc[data]; GCEvent _event = stats.GetCurrentGC(); if (_event != null) { // ObjectID is supposed to be an IntPtr. But "Address" is defined as UInt64 in // TraceEvent. _event.PinnedPlugs.Add(new GCEvent.PinnedPlug(data.PlugStart, data.PlugEnd)); } }; // Sometimes at the end of a trace I see only some mark events are included in the trace and they // are not in order, so need to anticipate that scenario. gcPrivate.GCMarkStackRoots += delegate (GCMarkTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc[data]; stats.AddServerGCThreadFromMark(data.ThreadID, data.HeapNum); GCEvent _event = stats.GetCurrentGC(); if (_event != null) { if (_event.PerHeapMarkTimes == null) { _event.PerHeapMarkTimes = new Dictionary<int, GCEvent.MarkInfo>(); } if (!_event.PerHeapMarkTimes.ContainsKey(data.HeapNum)) { _event.PerHeapMarkTimes.Add(data.HeapNum, new GCEvent.MarkInfo(false)); } _event.PerHeapMarkTimes[data.HeapNum].MarkTimes[(int)MarkRootType.MarkStack] = data.TimeStampRelativeMSec; } }; gcPrivate.GCMarkFinalizeQueueRoots += delegate (GCMarkTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc[data]; GCEvent _event = stats.GetCurrentGC(); if (_event != null) { if ((_event.PerHeapMarkTimes != null) && _event.PerHeapMarkTimes.ContainsKey(data.HeapNum)) { _event.PerHeapMarkTimes[data.HeapNum].MarkTimes[(int)MarkRootType.MarkFQ] = data.TimeStampRelativeMSec; } } }; gcPrivate.GCMarkHandles += delegate (GCMarkTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc[data]; GCEvent _event = stats.GetCurrentGC(); if (_event != null) { if ((_event.PerHeapMarkTimes != null) && _event.PerHeapMarkTimes.ContainsKey(data.HeapNum)) { _event.PerHeapMarkTimes[data.HeapNum].MarkTimes[(int)MarkRootType.MarkHandles] = data.TimeStampRelativeMSec; } } }; gcPrivate.GCMarkCards += delegate (GCMarkTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc[data]; GCEvent _event = stats.GetCurrentGC(); if (_event != null) { if ((_event.PerHeapMarkTimes != null) && _event.PerHeapMarkTimes.ContainsKey(data.HeapNum)) { _event.PerHeapMarkTimes[data.HeapNum].MarkTimes[(int)MarkRootType.MarkOlder] = data.TimeStampRelativeMSec; } } }; gcPrivate.GCGlobalHeapHistory += delegate (GCGlobalHeapHistoryTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc[data]; stats.ProcessGlobalHistory(data); }; gcPrivate.GCPerHeapHistory += delegate (GCPerHeapHistoryTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc[data]; stats.ProcessPerHeapHistory(data); }; gcPrivate.GCBGCStart += delegate (GCNoUserDataTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc[data]; if (stats.currentBGC != null) { if (stats.backgroundGCThreads == null) { stats.backgroundGCThreads = new Dictionary<int, object>(16); } stats.backgroundGCThreads[data.ThreadID] = null; } }; #endif source.Clr.AddCallbackForEvent("GC/Stop", delegate (GCEndTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc.GetOrCreate(data.ProcessID); GCEvent _event = stats.GetCurrentGC(); if (_event != null) { _event.GCDurationMSec = data.TimeStampRelativeMSec - _event.GCStartRelativeMSec; _event.GCGeneration = data.Depth; _event.GCEnd(); } }); source.Clr.AddCallbackForEvent("GC/HeapStats", delegate (GCHeapStatsTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc.GetOrCreate(data.ProcessID); GCEvent _event = stats.GetCurrentGC(); var sizeAfterMB = (data.GenerationSize1 + data.GenerationSize2 + data.GenerationSize3) / 1000000.0; if (_event != null) { _event.HeapStats = (GCHeapStatsTraceData)data.Clone(); if (_event.Type == GCType.BackgroundGC) { _event.ProcessCpuMSec = stats.ProcessCpuMSec - _event.ProcessCpuAtLastGC; _event.DurationSinceLastRestartMSec = data.TimeStampRelativeMSec - stats.lastRestartEndTimeRelativeMSec; } else { _event.ProcessCpuMSec = stats.ProcessCpuMSec - stats.ProcessCpuAtLastGC; _event.DurationSinceLastRestartMSec = _event.PauseStartRelativeMSec - stats.lastRestartEndTimeRelativeMSec; } if (stats.HasAllocTickEvents) { _event.HasAllocTickEvents = true; _event.AllocedSinceLastGCBasedOnAllocTickMB[0] = stats.allocTickCurrentMB[0] - stats.allocTickAtLastGC[0]; _event.AllocedSinceLastGCBasedOnAllocTickMB[1] = stats.allocTickCurrentMB[1] - stats.allocTickAtLastGC[1]; } // This is where a background GC ends. if ((_event.Type == GCType.BackgroundGC) && (stats.currentBGC != null)) { stats.currentBGC.isComplete = true; stats.lastCompletedGC = stats.currentBGC; stats.currentBGC = null; } if (_event.isConcurrentGC) { Debug.Assert(_event.is20Event); _event.isComplete = true; stats.lastCompletedGC = _event; } } stats.ProcessCpuAtLastGC = stats.ProcessCpuMSec; stats.allocTickAtLastGC[0] = stats.allocTickCurrentMB[0]; stats.allocTickAtLastGC[1] = stats.allocTickCurrentMB[1]; stats.lastRestartEndTimeRelativeMSec = data.TimeStampRelativeMSec; }); source.Clr.AddCallbackForEvent("GC/TerminateConcurrentThread", delegate (GCTerminateConcurrentThreadTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc.GetOrCreate(data.ProcessID); if (stats.backgroundGCThreads != null) { stats.backgroundGCThreads = null; } }); #if HAS_PRIVATE_GC_EVENTS gcPrivate.GCBGCAllocWaitStart += delegate (BGCAllocWaitTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc[data]; Debug.Assert(stats.currentBGC != null); if (stats.currentBGC != null) { stats.currentBGC.AddLOHWaitThreadInfo(data.ThreadID, data.TimeStampRelativeMSec, data.Reason, true); } }; gcPrivate.GCBGCAllocWaitStop += delegate (BGCAllocWaitTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess stats = perProc[data]; GCEvent _event = stats.GetLastBGC(); if (_event != null) { _event.AddLOHWaitThreadInfo(data.ThreadID, data.TimeStampRelativeMSec, data.Reason, false); } }; gcPrivate.GCJoin += delegate (GCJoinTraceData data) { if (filterFunc != null && !filterFunc.Invoke(data)) { return; } GCProcess gcProcess = perProc[data]; GCEvent _event = gcProcess.GetCurrentGC(); if (_event != null) { _event.AddGcJoin(data); } }; source.Process(); #endif return perProc; } public int ProcessID { get; set; } public string ProcessName { get; set; } bool isDead; public bool Interesting { get { return Total.GCCount > 0 || RuntimeVersion != null; } } public bool InterestingForAnalysis { get { return ((Total.GCCount > 3) && ((GetGCPauseTimePercentage() > 1.0) || (Total.MaxPauseDurationMSec > 200.0))); } } // A process can have one or more SBAs associated with it. public GCInfo[] Generations = new GCInfo[3] { new GCInfo(), new GCInfo(), new GCInfo() }; public GCInfo Total = new GCInfo(); public float ProcessCpuMSec; // Total CPU time used in process (approximate) public float GCCpuMSec; // CPU time used in the GC (approximate) public int NumberOfHeaps = 1; // Of all the CPU, how much as a percentage is spent in the GC. public float PercentTimeInGC { get { return GCCpuMSec * 100 / ProcessCpuMSec; } } public static string GetImageName(string path) { int startIdx = path.LastIndexOf('\\'); if (0 <= startIdx) startIdx++; else startIdx = 0; int endIdx = path.LastIndexOf('.'); if (endIdx <= startIdx) endIdx = path.Length; string name = path.Substring(startIdx, endIdx - startIdx); return name; } // This is calculated based on the GC events which is fine for the GC analysis purpose. public double ProcessDuration { get { double startRelativeMSec = 0.0; for (int i = 0; i < events.Count; i++) { if (events[i].isComplete) { startRelativeMSec = events[i].PauseStartRelativeMSec; break; } } if (startRelativeMSec == 0.0) return 0; // Get the end time of the last GC. double endRelativeMSec = lastRestartEndTimeRelativeMSec; return (endRelativeMSec - startRelativeMSec); } } public StartupFlags StartupFlags; public string RuntimeVersion; public int Bitness = -1; public Dictionary<int, int> ThreadId2Priority = new Dictionary<int, int>(); public Dictionary<int, int> ServerGcHeap2ThreadId = new Dictionary<int, int>(); public string CommandLine { get; set; } public double PeakWorkingSetMB { get; set; } public double PeakVirtualMB { get; set; } /// <summary> /// Means it detected that the ETW information is in a format it does not understand. /// </summary> public bool GCVersionInfoMismatch { get; private set; } public double GetGCPauseTimePercentage() { return ((ProcessDuration == 0) ? 0.0 : ((Total.TotalPauseTimeMSec * 100) / ProcessDuration)); } internal static void ComputeRollup(IDictionary<int, GCProcess> perProc) { // Compute rollup information. foreach (GCProcess stats in perProc.Values) { for (int i = 0; i < stats.events.Count; i++) { GCEvent _event = stats.events[i]; if (!_event.isComplete) { continue; } _event.Index = i; if (_event.DetailedGenDataAvailable()) //per heap histories is not null stats.m_detailedGCInfo = true; // Update the per-generation information stats.Generations[_event.GCGeneration].GCCount++; bool isInduced = ((_event.Reason == GCReason.Induced) || (_event.Reason == GCReason.InducedNotForced)); if (isInduced) (stats.Generations[_event.GCGeneration].NumInduced)++; long PinnedObjectSizes = _event.GetPinnedObjectSizes(); if (PinnedObjectSizes != 0) { stats.Generations[_event.GCGeneration].PinnedObjectSizes += PinnedObjectSizes; stats.Generations[_event.GCGeneration].NumGCWithPinEvents++; } int PinnedObjectPercentage = _event.GetPinnedObjectPercentage(); if (PinnedObjectPercentage != -1) { stats.Generations[_event.GCGeneration].PinnedObjectPercentage += _event.GetPinnedObjectPercentage(); stats.Generations[_event.GCGeneration].NumGCWithPinPlugEvents++; } stats.Generations[_event.GCGeneration].TotalGCCpuMSec += _event.GetTotalGCTime(); stats.Generations[_event.GCGeneration].TotalSizeAfterMB += _event.HeapSizeAfterMB; stats.Generations[_event.GCGeneration].TotalSizePeakMB += _event.HeapSizePeakMB; stats.Generations[_event.GCGeneration].TotalPromotedMB += _event.PromotedMB; stats.Generations[_event.GCGeneration].TotalPauseTimeMSec += _event.PauseDurationMSec; stats.Generations[_event.GCGeneration].TotalAllocatedMB += _event.AllocedSinceLastGCMB; stats.Generations[_event.GCGeneration].MaxPauseDurationMSec = Math.Max(stats.Generations[_event.GCGeneration].MaxPauseDurationMSec, _event.PauseDurationMSec); stats.Generations[_event.GCGeneration].MaxSizePeakMB = Math.Max(stats.Generations[_event.GCGeneration].MaxSizePeakMB, _event.HeapSizePeakMB); stats.Generations[_event.GCGeneration].MaxAllocRateMBSec = Math.Max(stats.Generations[_event.GCGeneration].MaxAllocRateMBSec, _event.AllocRateMBSec); stats.Generations[_event.GCGeneration].MaxPauseDurationMSec = Math.Max(stats.Generations[_event.GCGeneration].MaxPauseDurationMSec, _event.PauseDurationMSec); stats.Generations[_event.GCGeneration].MaxSuspendDurationMSec = Math.Max(stats.Generations[_event.GCGeneration].MaxSuspendDurationMSec, _event._SuspendDurationMSec); // And the totals stats.Total.GCCount++; if (isInduced) stats.Total.NumInduced++; if (PinnedObjectSizes != 0) { stats.Total.PinnedObjectSizes += PinnedObjectSizes; stats.Total.NumGCWithPinEvents++; } if (PinnedObjectPercentage != -1) { stats.Total.PinnedObjectPercentage += _event.GetPinnedObjectPercentage(); stats.Total.NumGCWithPinPlugEvents++; } stats.Total.TotalGCCpuMSec += _event.GetTotalGCTime(); stats.Total.TotalSizeAfterMB += _event.HeapSizeAfterMB; stats.Total.TotalPromotedMB += _event.PromotedMB; stats.Total.TotalSizePeakMB += _event.HeapSizePeakMB; stats.Total.TotalPauseTimeMSec += _event.PauseDurationMSec; stats.Total.TotalAllocatedMB += _event.AllocedSinceLastGCMB; stats.Total.MaxPauseDurationMSec = Math.Max(stats.Total.MaxPauseDurationMSec, _event.PauseDurationMSec); stats.Total.MaxSizePeakMB = Math.Max(stats.Total.MaxSizePeakMB, _event.HeapSizePeakMB); stats.Total.MaxAllocRateMBSec = Math.Max(stats.Total.MaxAllocRateMBSec, _event.AllocRateMBSec); stats.Total.MaxSuspendDurationMSec = Math.Max(stats.Total.MaxSuspendDurationMSec, _event._SuspendDurationMSec); } } } #region private protected virtual void Init(TraceEvent data) { ProcessID = data.ProcessID; ProcessName = data.ProcessName; isDead = false; } private GCEvent GetCurrentGC() { if (events.Count > 0) { if (!events[events.Count - 1].isComplete) { return events[events.Count - 1]; } else if (currentBGC != null) { return currentBGC; } } return null; } // This is the last GC in progress. We need this for server Background GC. // See comments for lastCompletedGC. private GCEvent GetLastGC() { GCEvent _event = GetCurrentGC(); if ((isServerGCUsed == 1) && (_event == null)) { if (lastCompletedGC != null) { Debug.Assert(lastCompletedGC.Type == GCType.BackgroundGC); _event = lastCompletedGC; } } return _event; } private GCEvent GetLastBGC() { if (currentBGC != null) { return currentBGC; } if ((lastCompletedGC != null) && (lastCompletedGC.Type == GCType.BackgroundGC)) { return lastCompletedGC; } // Otherwise we search till we find the last BGC if we have seen one. for (int i = (events.Count - 1); i >= 0; i--) { if (events[i].Type == GCType.BackgroundGC) { return events[i]; } } return null; } private void AddConcurrentPauseTime(GCEvent _event, double RestartEEMSec) { if (suspendThreadIDBGC > 0) { _event.PauseDurationMSec += RestartEEMSec - suspendTimeRelativeMSec; } else { Debug.Assert(_event.PauseDurationMSec == 0); _event.PauseDurationMSec = RestartEEMSec - _event.PauseStartRelativeMSec; } } private void AddServerGCThreadFromMark(int ThreadID, int HeapNum) { if (isServerGCUsed == 1) { Debug.Assert(heapCount > 1); if (serverGCThreads.Count < heapCount) { // I am seeing that sometimes we are not getting these events from all heaps // for a complete GC so I have to check for that. if (!serverGCThreads.ContainsKey(ThreadID)) { serverGCThreads.Add(ThreadID, HeapNum); } } } } private void ProcessGlobalHistory(GCGlobalHeapHistoryTraceData data) { if (isServerGCUsed == -1) { // We detected whether we are using Server GC now. isServerGCUsed = ((data.NumHeaps > 1) ? 1 : 0); if (heapCount == -1) { heapCount = data.NumHeaps; } if (isServerGCUsed == 1) { serverGCThreads = new Dictionary<int, int>(data.NumHeaps); } } GCEvent _event = GetLastGC(); if (_event != null) { _event.GlobalHeapHistory = (GCGlobalHeapHistoryTraceData)data.Clone(); _event.SetHeapCount(heapCount); } } private void ProcessPerHeapHistory(GCPerHeapHistoryTraceData data) { if (!data.VersionRecognized) { GCVersionInfoMismatch = true; return; } GCEvent _event = GetLastGC(); if (_event != null) { if (_event.PerHeapHistories == null) _event.PerHeapHistories = new List<GCPerHeapHistoryTraceData>(); _event.PerHeapHistories.Add((GCPerHeapHistoryTraceData)data.Clone()); } } public IList<GCEvent> Events { get { return events; } } private List<GCEvent> events = new List<GCEvent>(); // The amount of memory allocated by the user threads. So they are divided up into gen0 and LOH allocations. double[] allocTickCurrentMB = { 0.0, 0.0 }; double[] allocTickAtLastGC = { 0.0, 0.0 }; bool HasAllocTickEvents = false; bool SeenBadAllocTick = false; double lastRestartEndTimeRelativeMSec; // EE can be suspended via different reasons. The only ones we care about are // SuspendForGC(1) - suspending for GC start // SuspendForGCPrep(6) - BGC uses it in the middle of a BGC. // We need to filter out the rest of the suspend/resume events. // Keep track of the last time we started suspending the EE. Will use in 'Start' to set PauseStartRelativeMSec int suspendThreadIDOther = -1; int suspendThreadIDBGC = -1; // This is either the user thread (in workstation case) or a server GC thread that called SuspendEE to do a GC int suspendThreadIDGC = -1; double suspendTimeRelativeMSec = -1; double suspendEndTimeRelativeMSec = -1; // This records the amount of CPU time spent at the end of last GC. float ProcessCpuAtLastGC = 0; // This is the BGC that's in progress as we are parsing. We need to remember this // so we can correctly attribute the suspension time. GCEvent currentBGC = null; Dictionary<int, object> backgroundGCThreads = null; bool IsBGCThread(int threadID) { if (backgroundGCThreads != null) return backgroundGCThreads.ContainsKey(threadID); return false; } // I keep this for the purpose of server Background GC. Unfortunately for server background // GC we are firing the GCEnd/GCHeaps events and Global/Perheap events in the reversed order. // This is so that the Global/Perheap events can still be attributed to the right BGC. GCEvent lastCompletedGC = null; // We don't necessarily have the GCSettings event (only fired at the beginning if we attach) // So we have to detect whether we are running server GC or not. // Till we get our first GlobalHeapHistory event which indicates whether we use server GC // or not this remains -1. public int isServerGCUsed = -1; public int heapCount = -1; // This is the server GC threads. It's built up in the 2nd server GC we see. Dictionary<int, int> serverGCThreads = null; internal bool m_detailedGCInfo; int IsServerGCThread(int threadID) { int heapIndex; if (serverGCThreads != null) { if (serverGCThreads.TryGetValue(threadID, out heapIndex)) { return heapIndex; } } return -1; } #endregion } #if HAS_PRIVATE_GC_EVENTS class BGCAllocWaitInfo { public double WaitStartRelativeMSec; public double WaitStopRelativeMSec; public BGCAllocWaitReason Reason; public bool GetWaitTime(ref double pauseMSec) { if ((WaitStartRelativeMSec != 0) && (WaitStopRelativeMSec != 0)) { pauseMSec = WaitStopRelativeMSec - WaitStartRelativeMSec; return true; } return false; } public bool IsLOHWaitLong(double pauseMSecMin) { double pauseMSec = 0; if (GetWaitTime(ref pauseMSec)) { return (pauseMSec > pauseMSecMin); } return false; } public override string ToString() { if ((Reason == BGCAllocWaitReason.GetLOHSeg) || (Reason == BGCAllocWaitReason.AllocDuringSweep)) { return "Waiting for BGC to thread free lists"; } else { Debug.Assert(Reason == BGCAllocWaitReason.AllocDuringBGC); return "Allocated too much during BGC, waiting for BGC to finish"; } } } #endif } #endif