context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // PlayQueueActions.cs // // Authors: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Mono.Unix; using Gtk; using Hyena; using Banshee.MediaEngine; using Banshee.ServiceStack; using Banshee.Sources; using Banshee.Gui; namespace Banshee.PlayQueue { public class PlayQueueActions : Banshee.Gui.BansheeActionGroup { private PlayQueueSource playqueue; public PlayQueueActions (PlayQueueSource playqueue) : base ("playqueue") { this.playqueue = playqueue; Add (new ActionEntry [] { new ActionEntry ("AddToPlayQueueAction", Stock.Add, Catalog.GetString ("Add to Play Queue"), "q", Catalog.GetString ("Append selected songs to the play queue"), OnAddToPlayQueue), new ActionEntry ("AddToPlayQueueAfterAction", null, Catalog.GetString ("Play After"), null, Catalog.GetString ("Add selected songs after the currently playing track, album, or artist"), null), new ActionEntry ("AddToPlayQueueAfterCurrentTrackAction", null, Catalog.GetString ("Current Track"), null, Catalog.GetString ("Add selected songs to the play queue after the currently playing song"), OnAddToPlayQueueAfterCurrentTrack), new ActionEntry ("AddToPlayQueueAfterCurrentAlbumAction", null, Catalog.GetString ("Current Album"), null, Catalog.GetString ("Add selected songs to the play queue after the currently playing album"), OnAddToPlayQueueAfterCurrentAlbum), new ActionEntry ("AddToPlayQueueAfterCurrentArtistAction", null, Catalog.GetString ("Current Artist"), null, Catalog.GetString ("Add selected songs to the play queue after the currently playing artist"), OnAddToPlayQueueAfterCurrentArtist) }); AddImportant ( new ActionEntry ("RefreshPlayQueueAction", Stock.Refresh, Catalog.GetString ("Refresh"), null, Catalog.GetString ("Refresh random tracks in the play queue"), OnRefreshPlayQueue), new ActionEntry ("ShufflePlayQueue", null, Catalog.GetString ("Shuffle"), null, Catalog.GetString ("Randomize the playback order of items in the play queue"), OnShufflePlayQueue), new ActionEntry ("AddPlayQueueTracksAction", Stock.Add, Catalog.GetString ("Add More"), null, Catalog.GetString ("Add more random tracks to the play queue"), OnAddPlayQueueTracks), new ActionEntry ("ClearPlayQueueAction", Stock.Clear, Catalog.GetString ("Clear"), null, Catalog.GetString ("Remove all tracks from the play queue"), OnClearPlayQueue) ); this["ShufflePlayQueue"].IconName = "media-playlist-shuffle"; Add (new ToggleActionEntry [] { new ToggleActionEntry ("ClearPlayQueueOnQuitAction", null, Catalog.GetString ("Clear on Quit"), null, Catalog.GetString ("Clear the play queue when quitting"), OnClearPlayQueueOnQuit, PlayQueueSource.ClearOnQuitSchema.Get ()) }); AddUiFromFile ("GlobalUI.xml"); playqueue.Updated += OnUpdated; ServiceManager.SourceManager.ActiveSourceChanged += OnSourceUpdated; ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StateChange); ServiceManager.PlaybackController.SourceChanged += OnPlaybackSourceChanged; OnUpdated (null, null); Register (); } public override void Dispose () { playqueue.Updated -= OnUpdated; ServiceManager.SourceManager.ActiveSourceChanged -= OnSourceUpdated; base.Dispose (); } #region Action Handlers private void OnPlayerEvent (PlayerEventArgs args) { this["AddToPlayQueueAfterAction"].Sensitive = ServiceManager.PlayerEngine.IsPlaying (); } private void OnPlaybackSourceChanged (object sender, EventArgs e) { if (ServiceManager.PlaybackController.Source is PlayQueueSource) { this["AddToPlayQueueAfterCurrentAlbumAction"].Sensitive = true; this["AddToPlayQueueAfterCurrentArtistAction"].Sensitive = true; } else { this["AddToPlayQueueAfterCurrentAlbumAction"].Sensitive = false; this["AddToPlayQueueAfterCurrentArtistAction"].Sensitive = false; } } private void OnAddToPlayQueue (object o, EventArgs args) { AddSelectedToPlayQueue (QueueMode.Normal); } private void OnAddToPlayQueueAfterCurrentTrack (object sender, EventArgs e) { AddSelectedToPlayQueue (QueueMode.AfterCurrentTrack); } private void OnAddToPlayQueueAfterCurrentAlbum (object sender, EventArgs e) { AddSelectedToPlayQueue (QueueMode.AfterCurrentAlbum); } private void OnAddToPlayQueueAfterCurrentArtist (object sender, EventArgs e) { AddSelectedToPlayQueue (QueueMode.AfterCurrentArtist); } private void AddSelectedToPlayQueue (QueueMode mode) { var track_actions = ServiceManager.Get<InterfaceActionService> ().TrackActions; playqueue.AddSelectedTracks (ServiceManager.SourceManager.ActiveSource, track_actions.Selection, mode); } private void OnClearPlayQueue (object o, EventArgs args) { playqueue.Clear (); } private void OnRefreshPlayQueue (object o, EventArgs args) { playqueue.Refresh (); } private void OnAddPlayQueueTracks (object o, EventArgs args) { playqueue.AddMoreRandomTracks (); } private void OnShufflePlayQueue (object o, EventArgs args) { playqueue.Shuffle (); } private void OnClearPlayQueueOnQuit (object o, EventArgs args) { ToggleAction action = this["ClearPlayQueueOnQuitAction"] as Gtk.ToggleAction; PlayQueueSource.ClearOnQuitSchema.Set (action.Active); } #endregion private void OnSourceUpdated (SourceEventArgs args) { if (ServiceManager.SourceManager.ActiveSource is PlayQueueSource) { this["AddToPlayQueueAfterAction"].Visible = false; } else { this["AddToPlayQueueAfterAction"].Visible = true; } OnUpdated (null, null); } private void OnUpdated (object o, EventArgs args) { ThreadAssist.ProxyToMain (UpdateActions); } private void UpdateActions () { Source source = ServiceManager.SourceManager.ActiveSource; if (source != null) { DatabaseSource db_source = source as DatabaseSource ?? source.Parent as DatabaseSource; UpdateAction ("RefreshPlayQueueAction", playqueue.Populate); UpdateAction ("AddPlayQueueTracksAction", playqueue.Populate); UpdateAction ("ShufflePlayQueue", !playqueue.Populate, playqueue.Count > 1); UpdateAction ("ClearPlayQueueAction", !playqueue.Populate, playqueue.Count > 0); UpdateAction ("ClearPlayQueueOnQuitAction", !playqueue.Populate); UpdateAction ("AddToPlayQueueAction", db_source != null && db_source != playqueue, true); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NPOI.HSSF.Util; using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace NPOI.SS.UserModel { /** * A deprecated indexing scheme for colours that is still required for some records, and for backwards * compatibility with OLE2 formats. * * <p> * Each element corresponds to a color index (zero-based). When using the default indexed color palette, * the values are not written out, but instead are implied. When the color palette has been modified from default, * then the entire color palette is used. * </p> * * @author Yegor Kozlov */ public class IndexedColors { public static readonly IndexedColors Black; public static readonly IndexedColors White; public static readonly IndexedColors Red; public static readonly IndexedColors BrightGreen; public static readonly IndexedColors Blue; public static readonly IndexedColors Yellow; public static readonly IndexedColors Pink; public static readonly IndexedColors Turquoise; public static readonly IndexedColors DarkRed; public static readonly IndexedColors Green; public static readonly IndexedColors DarkBlue; public static readonly IndexedColors DarkYellow; public static readonly IndexedColors Violet; public static readonly IndexedColors Teal; public static readonly IndexedColors Grey25Percent; public static readonly IndexedColors Grey50Percent; public static readonly IndexedColors CornflowerBlue; public static readonly IndexedColors Maroon; public static readonly IndexedColors LemonChiffon; public static readonly IndexedColors Orchid; public static readonly IndexedColors Coral; public static readonly IndexedColors RoyalBlue; public static readonly IndexedColors LightCornflowerBlue; public static readonly IndexedColors SkyBlue; public static readonly IndexedColors LightTurquoise; public static readonly IndexedColors LightGreen; public static readonly IndexedColors LightYellow; public static readonly IndexedColors PaleBlue; public static readonly IndexedColors Rose; public static readonly IndexedColors Lavender; public static readonly IndexedColors Tan; public static readonly IndexedColors LightBlue; public static readonly IndexedColors Aqua; public static readonly IndexedColors Lime; public static readonly IndexedColors Gold; public static readonly IndexedColors LightOrange; public static readonly IndexedColors Orange; public static readonly IndexedColors BlueGrey; public static readonly IndexedColors Grey40Percent; public static readonly IndexedColors DarkTeal; public static readonly IndexedColors SeaGreen; public static readonly IndexedColors DarkGreen; public static readonly IndexedColors OliveGreen; public static readonly IndexedColors Brown ; public static readonly IndexedColors Plum; public static readonly IndexedColors Indigo; public static readonly IndexedColors Grey80Percent; public static readonly IndexedColors Automatic; private int index; private HSSFColor hssfColor; IndexedColors(int idx, HSSFColor color) { index = idx; this.hssfColor = color; } static Dictionary<string, IndexedColors> mappingName = null; static Dictionary<int, IndexedColors> mappingIndex = null; static IndexedColors() { Black = new IndexedColors(8, new HSSFColor.Black()); White = new IndexedColors(9, new HSSFColor.White()); Red = new IndexedColors(10, new HSSFColor.Red()); BrightGreen = new IndexedColors(11, new HSSFColor.BrightGreen()); Blue = new IndexedColors(12, new HSSFColor.Blue()); Yellow = new IndexedColors(13, new HSSFColor.Yellow()); Pink = new IndexedColors(14, new HSSFColor.Pink()); Turquoise = new IndexedColors(15, new HSSFColor.Turquoise()); DarkRed = new IndexedColors(16, new HSSFColor.DarkRed()); Green = new IndexedColors(17, new HSSFColor.Green()); DarkBlue = new IndexedColors(18, new HSSFColor.DarkBlue()); DarkYellow = new IndexedColors(19, new HSSFColor.DarkYellow()); Violet = new IndexedColors(20, new HSSFColor.Violet()); Teal = new IndexedColors(21, new HSSFColor.Teal()); Grey25Percent = new IndexedColors(22, new HSSFColor.Grey25Percent()); Grey50Percent = new IndexedColors(23, new HSSFColor.Grey50Percent()); CornflowerBlue = new IndexedColors(24, new HSSFColor.CornflowerBlue()); Maroon = new IndexedColors(25, new HSSFColor.Maroon()); LemonChiffon = new IndexedColors(26, new HSSFColor.LemonChiffon()); Orchid = new IndexedColors(28, new HSSFColor.Orchid()); Coral = new IndexedColors(29, new HSSFColor.Coral()); RoyalBlue = new IndexedColors(30, new HSSFColor.RoyalBlue()); LightCornflowerBlue = new IndexedColors(31,new HSSFColor.LightCornflowerBlue()); SkyBlue = new IndexedColors(40, new HSSFColor.SkyBlue()); LightTurquoise = new IndexedColors(41, new HSSFColor.LightTurquoise()); LightGreen = new IndexedColors(42, new HSSFColor.LightGreen()); LightYellow = new IndexedColors(43, new HSSFColor.LightYellow()); PaleBlue = new IndexedColors(44, new HSSFColor.PaleBlue()); Rose = new IndexedColors(45, new HSSFColor.Rose()); Lavender = new IndexedColors(46, new HSSFColor.Lavender()); Tan = new IndexedColors(47, new HSSFColor.Tan()); LightBlue = new IndexedColors(48, new HSSFColor.LightBlue()); Aqua = new IndexedColors(49, new HSSFColor.Aqua()); Lime = new IndexedColors(50, new HSSFColor.Lime()); Gold = new IndexedColors(51, new HSSFColor.Gold()); LightOrange = new IndexedColors(52, new HSSFColor.LightOrange()); Orange = new IndexedColors(53, new HSSFColor.Orange()); BlueGrey = new IndexedColors(54, new HSSFColor.BlueGrey()); Grey40Percent = new IndexedColors(55, new HSSFColor.Grey40Percent()); DarkTeal = new IndexedColors(56, new HSSFColor.DarkTeal()); SeaGreen = new IndexedColors(57, new HSSFColor.SeaGreen()); DarkGreen = new IndexedColors(58, new HSSFColor.DarkGreen()); OliveGreen = new IndexedColors(59, new HSSFColor.OliveGreen()); Brown = new IndexedColors(60, new HSSFColor.Brown()); Plum = new IndexedColors(61, new HSSFColor.Plum()); Indigo = new IndexedColors(62, new HSSFColor.Indigo()); Grey80Percent = new IndexedColors(63, new HSSFColor.Grey80Percent()); Automatic = new IndexedColors(64, new HSSFColor.Automatic()); mappingName = new Dictionary<string, IndexedColors>(); mappingName.Add("black", IndexedColors.Black); mappingName.Add("white", IndexedColors.White); mappingName.Add("red", IndexedColors.Red); mappingName.Add("brightgreen", IndexedColors.BrightGreen); mappingName.Add("blue", IndexedColors.Blue); mappingName.Add("yellow", IndexedColors.Yellow); mappingName.Add("pink", IndexedColors.Pink); mappingName.Add("turquoise", IndexedColors.Turquoise); mappingName.Add("darkred", IndexedColors.DarkRed); mappingName.Add("green", IndexedColors.Green); mappingName.Add("darkblue", IndexedColors.DarkBlue); mappingName.Add("darkyellow", IndexedColors.DarkYellow); mappingName.Add("violet", IndexedColors.Violet); mappingName.Add("teal", IndexedColors.Teal); mappingName.Add("grey25percent", IndexedColors.Grey25Percent); mappingName.Add("grey50percent", IndexedColors.Grey50Percent); mappingName.Add("cornflowerblue", IndexedColors.CornflowerBlue); mappingName.Add("maroon", IndexedColors.Maroon); mappingName.Add("lemonchiffon", IndexedColors.LemonChiffon); mappingName.Add("orchid", IndexedColors.Orchid); mappingName.Add("coral", IndexedColors.Coral); mappingName.Add("royalblue", IndexedColors.RoyalBlue); mappingName.Add("lightcornflowerblue", IndexedColors.LightCornflowerBlue); mappingName.Add("skyblue", IndexedColors.SkyBlue); mappingName.Add("lightturquoise", IndexedColors.LightTurquoise); mappingName.Add("lightgreen", IndexedColors.LightGreen); mappingName.Add("lightyellow", IndexedColors.LightYellow); mappingName.Add("paleblue", IndexedColors.PaleBlue); mappingName.Add("rose", IndexedColors.Rose); mappingName.Add("lavender", IndexedColors.Lavender); mappingName.Add("tan", IndexedColors.Tan); mappingName.Add("lightblue", IndexedColors.LightBlue); mappingName.Add("aqua", IndexedColors.Aqua); mappingName.Add("lime", IndexedColors.Lime); mappingName.Add("gold", IndexedColors.Gold); mappingName.Add("lightorange", IndexedColors.LightOrange); mappingName.Add("orange", IndexedColors.Orange); mappingName.Add("bluegrey", IndexedColors.BlueGrey); mappingName.Add("grey40percent", IndexedColors.Grey40Percent); mappingName.Add("darkteal", IndexedColors.DarkTeal); mappingName.Add("seagreen", IndexedColors.SeaGreen); mappingName.Add("darkgreen", IndexedColors.DarkGreen); mappingName.Add("olivergreen", IndexedColors.OliveGreen); mappingName.Add("brown", IndexedColors.Brown); mappingName.Add("plum", IndexedColors.Plum); mappingName.Add("indigo", IndexedColors.Indigo); mappingName.Add("grey80percent", IndexedColors.Grey80Percent); mappingName.Add("automatic", IndexedColors.Automatic); mappingIndex = new Dictionary<int, IndexedColors>(); mappingIndex.Add(8, IndexedColors.Black); mappingIndex.Add(9, IndexedColors.White); mappingIndex.Add(10, IndexedColors.Red); mappingIndex.Add(11, IndexedColors.BrightGreen); mappingIndex.Add(12, IndexedColors.Blue); mappingIndex.Add(13, IndexedColors.Yellow); mappingIndex.Add(14, IndexedColors.Pink); mappingIndex.Add(15, IndexedColors.Turquoise); mappingIndex.Add(16, IndexedColors.DarkRed); mappingIndex.Add(17, IndexedColors.Green); mappingIndex.Add(18, IndexedColors.DarkBlue); mappingIndex.Add(19, IndexedColors.DarkYellow); mappingIndex.Add(20, IndexedColors.Violet); mappingIndex.Add(21, IndexedColors.Teal); mappingIndex.Add(22, IndexedColors.Grey25Percent); mappingIndex.Add(23, IndexedColors.Grey50Percent); mappingIndex.Add(24, IndexedColors.CornflowerBlue); mappingIndex.Add(25, IndexedColors.Maroon); mappingIndex.Add(26, IndexedColors.LemonChiffon); mappingIndex.Add(28, IndexedColors.Orchid); mappingIndex.Add(29, IndexedColors.Coral); mappingIndex.Add(30, IndexedColors.RoyalBlue); mappingIndex.Add(31, IndexedColors.LightCornflowerBlue); mappingIndex.Add(40, IndexedColors.SkyBlue); mappingIndex.Add(41, IndexedColors.LightTurquoise); mappingIndex.Add(42, IndexedColors.LightGreen); mappingIndex.Add(43, IndexedColors.LightYellow); mappingIndex.Add(44, IndexedColors.PaleBlue); mappingIndex.Add(45, IndexedColors.Rose); mappingIndex.Add(46, IndexedColors.Lavender); mappingIndex.Add(47, IndexedColors.Tan); mappingIndex.Add(48, IndexedColors.LightBlue); mappingIndex.Add(49, IndexedColors.Aqua); mappingIndex.Add(50, IndexedColors.Lime); mappingIndex.Add(51, IndexedColors.Gold); mappingIndex.Add(52, IndexedColors.LightOrange); mappingIndex.Add(53, IndexedColors.Orange); mappingIndex.Add(54, IndexedColors.BlueGrey); mappingIndex.Add(55, IndexedColors.Grey40Percent); mappingIndex.Add(56, IndexedColors.DarkTeal); mappingIndex.Add(57, IndexedColors.SeaGreen); mappingIndex.Add(58, IndexedColors.DarkGreen); mappingIndex.Add(59, IndexedColors.OliveGreen); mappingIndex.Add(60, IndexedColors.Brown); mappingIndex.Add(61, IndexedColors.Plum); mappingIndex.Add(62, IndexedColors.Indigo); mappingIndex.Add(63, IndexedColors.Grey80Percent); mappingIndex.Add(64, IndexedColors.Automatic); } public static IndexedColors ValueOf(string colorName) { if (mappingName.ContainsKey(colorName.ToLower())) return mappingName[colorName.ToLower()]; return null; } public static IndexedColors ValueOf(int index) { if(mappingIndex.ContainsKey(index)) return mappingIndex[index]; throw new ArgumentException("Illegal IndexedColor index: " + index); } /** * * * @param index the index of the color * @return the corresponding IndexedColors enum * @throws IllegalArgumentException if index is not a valid IndexedColors * @since 3.15-beta2 */ public static IndexedColors FromInt(int index) { return ValueOf(index); } public byte[] RGB { get { return hssfColor.RGB; } } public string HexString { get { StringBuilder stringBuilder = new StringBuilder(7); stringBuilder.Append('#'); byte[] rgb = this.hssfColor.RGB; foreach (byte s in rgb) { stringBuilder.Append(s.ToString("x2")); } return stringBuilder.ToString(); } } /** * Returns index of this color * * @return index of this color */ public short Index { get { return (short)index; } } } }
using System; using System.Drawing; namespace ICSharpCode.TextEditor.Document { public class TextWord { public sealed class SpaceTextWord : TextWord { public override TextWordType Type { get { return TextWordType.Space; } } public override bool IsWhiteSpace { get { return true; } } public SpaceTextWord() { this.length = 1; } public SpaceTextWord(HighlightColor color) { this.length = 1; base.SyntaxColor = color; } public override Font GetFont(FontContainer fontContainer) { return null; } } public sealed class TabTextWord : TextWord { public override TextWordType Type { get { return TextWordType.Tab; } } public override bool IsWhiteSpace { get { return true; } } public TabTextWord() { this.length = 1; } public TabTextWord(HighlightColor color) { this.length = 1; base.SyntaxColor = color; } public override Font GetFont(FontContainer fontContainer) { return null; } } private HighlightColor color; private LineSegment line; private IDocument document; private int offset; private int length; private static TextWord spaceWord = new TextWord.SpaceTextWord(); private static TextWord tabWord = new TextWord.TabTextWord(); private bool hasDefaultColor; public static TextWord Space { get { return TextWord.spaceWord; } } public static TextWord Tab { get { return TextWord.tabWord; } } public int Offset { get { return this.offset; } } public int Length { get { return this.length; } } public bool HasDefaultColor { get { return this.hasDefaultColor; } } public virtual TextWordType Type { get { return TextWordType.Word; } } public string Word { get { if (this.document == null) { return string.Empty; } return this.document.GetText(this.line.Offset + this.offset, this.length); } } public Color Color { get { if (this.color == null) { return Color.Black; } return this.color.Color; } } public bool Bold { get { return this.color != null && this.color.Bold; } } public bool Italic { get { return this.color != null && this.color.Italic; } } public HighlightColor SyntaxColor { get { return this.color; } set { this.color = value; } } public virtual bool IsWhiteSpace { get { return false; } } public static TextWord Split(ref TextWord word, int pos) { TextWord result = new TextWord(word.document, word.line, word.offset + pos, word.length - pos, word.color, word.hasDefaultColor); word = new TextWord(word.document, word.line, word.offset, pos, word.color, word.hasDefaultColor); return result; } public virtual Font GetFont(FontContainer fontContainer) { return this.color.GetFont(fontContainer); } protected TextWord() { } public TextWord(IDocument document, LineSegment line, int offset, int length, HighlightColor color, bool hasDefaultColor) { this.document = document; this.line = line; this.offset = offset; this.length = length; this.color = color; this.hasDefaultColor = hasDefaultColor; } public override string ToString() { return string.Concat(new object[] { "[TextWord: Word = ", this.Word, ", Color = ", this.Color, "]" }); } } }
using System; using RLToolkit.Logger; namespace RLToolkit.Widgets { /// <summary> /// Widget that allow the user to Multiple controls in a grid-like interface, with the possibility to +/- in the list and with possibility to use either vertically or horizontally. /// </summary> [System.ComponentModel.ToolboxItem(true)] public partial class GridSelector : Gtk.Bin { #region variables // the control array private Gtk.Widget[] controlArray; // the filler control type private System.Type fillerControlType = typeof(Gtk.Label); // the offset variables private int offset = 0; // if we're initialized yet private bool isInitialized = false; #endregion #region state // The state of the control controls /// <summary> /// The state (using the eState enum) of the control. used to handle vertical or horizontal mode. /// </summary> public eState controlState = eState.None; /// <summary> The various possible state the control can take.</summary> public enum eState { /// <summary>No mode selected, will not display +/- buttons. </summary> None = 0, /// <summary>Vertical mode.</summary> Vertical, /// <summary>Horizontal mode</summary> Horizontal }; #endregion #region Properties // property private int nbCol = 3; private int nbRow = 3; /// <summary> /// Property used for the number of columns in the grid /// </summary> /// <value>The number of columns to use.</value> /// <remarks>Needs to be in between 1 and 20</remarks> public int NbCol { get { return nbCol; } set { nbCol = value; } } /// <summary> /// Property used for the number of rows in the grid /// </summary> /// <value>The number of rows to use.</value> /// <remarks>Needs to be in between 1 and 20</remarks> public int NbRow { get { return nbRow; } set { nbRow = value; } } #endregion #region Constructor/Initialization /// <summary> /// Method that builds the control. /// </summary> /// <remarks>Make sure to call the 'Initialize' method before using the control</remarks> public GridSelector() { this.Build(); } /// <summary> /// Method to fill the control with the controls used for the grid and to define it state /// </summary> /// <param name="s">The state of the control to use using the eState Enum</param> /// <param name="inputControls">The control array of Gtk.Widgets to use.</param> public void Initialize(eState s, Gtk.Widget[] inputControls) { // initialize the state if (s == eState.None) { SetNoControlMode(); } else if (s == eState.Horizontal) { SetHorizontalMode(); } else if (s == eState.Vertical) { SetVerticalMode(); } else { // something went terribly wrong this.Log().Warn("Invalid state requested. Using 'none'"); SetNoControlMode(); } // set the number of column/row if (nbCol <= 0) { this.Log().Warn("Tried to use a number of column invalid. (needs to be over 0)"); nbCol = 1; } if (nbCol > 20) { this.Log().Warn("Tried to use a number of column invalid. (needs to be under 21)"); nbCol = 20; } if (nbRow <= 0) { this.Log().Warn("Tried to use a number of row invalid. (needs to be over 0)"); nbRow = 1; } if (nbRow > 20) { this.Log().Warn("Tried to use a number of row invalid. (needs to be under 21)"); nbRow = 20; } tableContent.NColumns = (uint)nbCol; tableContent.NRows = (uint)nbRow; // initialize the controls SetControlArray(inputControls); // done initializing isInitialized = true; RefreshControlShown(); } #endregion #region Mode/FillerType/Array setter /// <summary> /// Set the filler type of control to use. Default is Gtk.Label. /// </summary> /// <param name="input">the typeof your desired GTK widget control.</param> /// <remarks>Do not use GTK.Widget as filler.</remarks> public void SetFillerControlType(System.Type input) { // updating the filler type fillerControlType = input; // redraw in case we have some shown RefreshControlShown(); } /// <summary> /// Method to update the control array. /// </summary> /// <param name="inputArray">the new control array to use</param> public void SetControlArray(Gtk.Widget[] inputArray) { controlArray = inputArray; RefreshControlShown(); } /// <summary> /// Method to set the Grid in Horizontal mode. /// </summary> public void SetHorizontalMode() { // uses the H controls, start top+left, bottom+left, Top+right controlState = eState.Horizontal; verticalControl.Hide(); horizontalControl.Show(); RefreshControlShown(); } /// <summary> /// Method to set the Grid in Vertical mode. /// </summary> public void SetVerticalMode() { // uses the V controls, start top+left, top+right, Bottom+left controlState = eState.Vertical; horizontalControl.Hide(); verticalControl.Show(); RefreshControlShown(); } /// <summary> /// Method to set the Grid in 'none' mode. No way to change controls in this mode. /// </summary> public void SetNoControlMode() { // No movement controls, only use what's shown controlState = eState.None; horizontalControl.Hide(); verticalControl.Hide(); RefreshControlShown(); } #endregion #region Refresh private void RefreshControlShown() { if (!isInitialized) { // not initialized. don't try anything yet. return; } // fill the tableContent with the right controls foreach (Gtk.Widget c in tableContent.Children) { // clear all controls tableContent.Remove(c); } int numX; int numY; bool hmode = false; // Fetch the info for our state/max switch (controlState) { case eState.Horizontal: hmode = true; numX = (int)tableContent.NColumns; numY = (int)tableContent.NRows; break; case eState.Vertical: hmode = false; numX = (int)tableContent.NRows; numY = (int)tableContent.NColumns; break; case eState.None: hmode = true; numX = (int)tableContent.NColumns; numY = (int)tableContent.NRows; break; default: // we have a problem here this.Log().Warn("Something went wrong. Invalid state."); hmode = true; numX = (int)tableContent.NColumns; numY = (int)tableContent.NRows; break; } // Fill the taqble with our content int nControl = 0; for (int x = 0; x < numX; x++) { for (int y = 0; y < numY; y++) { // figure out which control to use int index = nControl + (offset * numY); Gtk.Widget controlToUse; if (index >= controlArray.Length) { // filler controlToUse = (Gtk.Widget)Activator.CreateInstance(fillerControlType); controlToUse.Sensitive = false; } else { controlToUse = controlArray[index]; } // depending on the control mode, find out where to attach if (hmode) { tableContent.Attach(controlToUse, (uint)x, (uint)x+1, (uint)y, (uint)y+1); } else { tableContent.Attach(controlToUse, (uint)y, (uint)y+1, (uint)x, (uint)x+1); } // increment the count nControl++; } } // make sure we show everything tableContent.ShowAll(); } #endregion #region Validation private void ValidateOffset() { if (offset < 0) { this.Log().Info("Negative Offset found, setting to 0."); offset = 0; } else { int max; switch (controlState) { case eState.Horizontal: max = (int)Math.Floor((float)(controlArray.Length - 1) / (float)tableContent.NRows); break; case eState.Vertical: max = (int)Math.Floor((float)(controlArray.Length - 1) / (float)tableContent.NColumns); break; case eState.None: max = 0; break; default: max = 0; break; } if (offset > max) { this.Log().Info("Offset too high, setting to maximum"); offset = max; } } } #endregion #region Events /// <summary> /// EventHandler for the vertical minus button pressed /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> protected void OnBtnVMinusClicked (object sender, EventArgs e) { offset--; ValidateOffset(); RefreshControlShown(); } /// <summary> /// EventHandler for the vertical plus button pressed /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> protected void OnBtnVPlusClicked (object sender, EventArgs e) { offset++; ValidateOffset(); RefreshControlShown(); } /// <summary> /// EventHandler for the Horizontal minus button pressed /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> protected void OnBtnHMinusClicked (object sender, EventArgs e) { offset--; ValidateOffset(); RefreshControlShown(); } /// <summary> /// EventHandler for the Horizontal plus button pressed /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> protected void OnBtnHPlusClicked (object sender, EventArgs e) { offset++; ValidateOffset(); RefreshControlShown(); } #endregion } }
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This is a Keyboard Subclass that runs on device only. It displays the // full VR Keyboard. using UnityEngine; using UnityEngine.VR; using System; using System.Runtime.InteropServices; /// @cond namespace Gvr.Internal { public class AndroidNativeKeyboardProvider : IKeyboardProvider { private IntPtr renderEventFunction; // Library name. private const string dllName = "gvr_keyboard_shim_unity"; // Enum gvr_trigger_state. private const int TRIGGER_NONE = 0; private const int TRIGGER_PRESSED = 1; [StructLayout (LayoutKind.Sequential)] private struct gvr_clock_time_point { public long monotonic_system_time_nanos; } [StructLayout (LayoutKind.Sequential)] private struct gvr_recti { public int left; public int right; public int bottom; public int top; } [DllImport ("gvr")] private static extern gvr_clock_time_point gvr_get_time_point_now(); [DllImport (dllName)] private static extern GvrKeyboardInputMode gvr_keyboard_get_input_mode(IntPtr keyboard_context); [DllImport (dllName)] private static extern void gvr_keyboard_set_input_mode(IntPtr keyboard_context, GvrKeyboardInputMode mode); #if UNITY_ANDROID [DllImport(dllName)] private static extern IntPtr gvr_keyboard_initialize(AndroidJavaObject app_context, AndroidJavaObject class_loader); #endif [DllImport (dllName)] private static extern IntPtr gvr_keyboard_create(IntPtr closure, GvrKeyboard.KeyboardCallback callback); // Gets a recommended world space matrix. [DllImport (dllName)] private static extern void gvr_keyboard_get_recommended_world_from_keyboard_matrix(float distance_from_eye, IntPtr matrix); // Sets the recommended world space matrix. The matrix may // contain a combination of translation/rotation/scaling information. [DllImport(dllName)] private static extern void gvr_keyboard_set_world_from_keyboard_matrix(IntPtr keyboard_context, IntPtr matrix); // Shows the keyboard [DllImport (dllName)] private static extern void gvr_keyboard_show(IntPtr keyboard_context); // Updates the keyboard with the controller's button state. [DllImport(dllName)] private static extern void gvr_keyboard_update_button_state(IntPtr keyboard_context, int buttonIndex, bool pressed); // Updates the controller ray on the keyboard. [DllImport(dllName)] private static extern bool gvr_keyboard_update_controller_ray(IntPtr keyboard_context, IntPtr vector3Start, IntPtr vector3End, IntPtr vector3Hit); // Returns the EditText with for the keyboard. [DllImport (dllName)] private static extern IntPtr gvr_keyboard_get_text(IntPtr keyboard_context); // Sets the edit_text for the keyboard. // @return 1 if the edit text could be set. 0 if it cannot be set. [DllImport (dllName)] private static extern int gvr_keyboard_set_text(IntPtr keyboard_context, IntPtr edit_text); // Hides the keyboard. [DllImport (dllName)] private static extern void gvr_keyboard_hide(IntPtr keyboard_context); // Destroys the keyboard. Resources related to the keyboard is released. [DllImport (dllName)] private static extern void gvr_keyboard_destroy(IntPtr keyboard_context); // Called once per frame to set the time index. [DllImport(dllName)] private static extern void GvrKeyboardSetFrameData(IntPtr keyboard_context, gvr_clock_time_point t); // Sets VR eye data in preparation for rendering a single eye's view. [DllImport(dllName)] private static extern void GvrKeyboardSetEyeData(int eye_type, Matrix4x4 modelview, Matrix4x4 projection, gvr_recti viewport); [DllImport(dllName)] private static extern IntPtr GetKeyboardRenderEventFunc(); // Private class data. private IntPtr keyboard_context = IntPtr.Zero; // Used in the GVR Unity C++ shim layer. private const int advanceID = 0x5DAC793B; private const int renderLeftID = 0x3CF97A3D; private const int renderRightID = 0x3CF97A3E; private const string KEYBOARD_JAVA_CLASS = "com.google.vr.keyboard.GvrKeyboardUnity"; private const long kPredictionTimeWithoutVsyncNanos = 50000000; private const int kGvrControllerButtonClick = 1; private GvrKeyboardInputMode mode = GvrKeyboardInputMode.DEFAULT; private string editorText = string.Empty; private Matrix4x4 worldMatrix; private bool isValid = false; private bool isReady = false; public string EditorText { get { IntPtr text = gvr_keyboard_get_text(keyboard_context); editorText = Marshal.PtrToStringAnsi(text); return editorText; } set { editorText = value; IntPtr text = Marshal.StringToHGlobalAnsi(editorText); gvr_keyboard_set_text(keyboard_context, text); } } public void SetInputMode(GvrKeyboardInputMode mode) { Debug.Log("Calling set input mode: " + mode); gvr_keyboard_set_input_mode(keyboard_context, mode); this.mode = mode; } public void OnPause() { } public void OnResume() { } public void ReadState(KeyboardState outState) { outState.editorText = editorText; outState.mode = mode; outState.worldMatrix = worldMatrix; outState.isValid = isValid; outState.isReady = isReady; } // Initialization function. public AndroidNativeKeyboardProvider() { #if UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR AndroidJavaObject activity = GvrActivityHelper.GetActivity(); if (activity == null) { Debug.Log("Failed to get activity for keyboard."); return; } AndroidJavaObject context = GvrActivityHelper.GetApplicationContext(activity); if (context == null) { Debug.Log("Failed to get context for keyboard."); return; } AndroidJavaObject plugin = new AndroidJavaObject(KEYBOARD_JAVA_CLASS); if (plugin != null) { plugin.Call("initializeKeyboard", context); isValid = true; } #endif // UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR // Prevent compilation errors on 5.3.3 and lower. #if UNITY_HAS_GOOGLEVR InputTracking.disablePositionalTracking = true; #endif // UNITY_HAS_GOOGLEVR renderEventFunction = GetKeyboardRenderEventFunc(); } ~AndroidNativeKeyboardProvider() { gvr_keyboard_destroy(keyboard_context); } public bool Create(GvrKeyboard.KeyboardCallback keyboardEvent) { keyboard_context = gvr_keyboard_create(IntPtr.Zero, keyboardEvent); isReady = keyboard_context != IntPtr.Zero; return isReady; } public void Show(Matrix4x4 userMatrix, bool useRecommended, float distance, Matrix4x4 model) { if (useRecommended) { worldMatrix = getRecommendedMatrix(distance); } else { // Convert to GVR coordinates. Matrix4x4 flipZ = Matrix4x4.Scale(new Vector3(1, 1, -1)); worldMatrix = flipZ * userMatrix * flipZ; worldMatrix = worldMatrix.transpose; } Matrix4x4 matToSet = worldMatrix * model.transpose; IntPtr mat_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(matToSet)); Marshal.StructureToPtr(matToSet, mat_ptr, true); gvr_keyboard_set_world_from_keyboard_matrix(keyboard_context, mat_ptr); gvr_keyboard_show(keyboard_context); } public void UpdateData() { #if UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR // Update controller state. GvrBasePointer pointer = GvrPointerManager.Pointer; if (pointer != null && GvrController.State == GvrConnectionState.Connected) { bool pressed = GvrController.ClickButton; gvr_keyboard_update_button_state(keyboard_context, kGvrControllerButtonClick, pressed); Vector3 startPoint = pointer.PointerTransform.position; // Need to flip Z for native library startPoint.z *= -1; IntPtr start_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(startPoint)); Marshal.StructureToPtr(startPoint, start_ptr, true); Vector3 endPoint = pointer.LineEndPoint; // Need to flip Z for native library endPoint.z *= -1; IntPtr end_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(endPoint)); Marshal.StructureToPtr(endPoint, end_ptr, true); Vector3 hit = Vector3.one; IntPtr hit_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(Vector3.zero)); Marshal.StructureToPtr(Vector3.zero, hit_ptr, true); gvr_keyboard_update_controller_ray(keyboard_context, start_ptr, end_ptr, hit_ptr); hit = (Vector3)Marshal.PtrToStructure(hit_ptr, typeof(Vector3)); hit.z *= -1; } #endif // UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR // Get time stamp. gvr_clock_time_point time = gvr_get_time_point_now(); time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos; // Update frame data. GvrKeyboardSetFrameData(keyboard_context, time); GL.IssuePluginEvent(renderEventFunction, advanceID); } public void Render(int eye, Matrix4x4 modelview, Matrix4x4 projection, Rect viewport) { gvr_recti rect = new gvr_recti(); rect.left = (int)viewport.x; rect.top = (int)viewport.y + (int)viewport.height; rect.right = (int)viewport.x + (int)viewport.width; rect.bottom = (int)viewport.y; // For the modelview matrix, we need to convert it to a world-to-camera // matrix for GVR keyboard, hence the inverse. We need to convert left // handed to right handed, hence the multiply by flipZ. // Unity projection matrices are already in a form GVR needs. // Unity stores matrices row-major, so both get a final transpose to get // them column-major for GVR. Matrix4x4 flipZ = Matrix4x4.Scale(new Vector3(1, 1, -1)); GvrKeyboardSetEyeData(eye, (flipZ * modelview.inverse).transpose.inverse, projection.transpose, rect); GL.IssuePluginEvent(renderEventFunction, eye == 0 ? renderLeftID : renderRightID); } public void Hide() { gvr_keyboard_hide(keyboard_context); } // Return the recommended keyboard local to world space // matrix given a distance value by the user. This value should // be between 1 and 5 and will get clamped to that range. private Matrix4x4 getRecommendedMatrix(float inputDistance) { float distance = Mathf.Clamp(inputDistance, 1.0f, 5.0f); Matrix4x4 result = new Matrix4x4(); IntPtr mat_ptr = Marshal.AllocHGlobal(Marshal.SizeOf (result)); Marshal.StructureToPtr(result, mat_ptr, true); gvr_keyboard_get_recommended_world_from_keyboard_matrix(distance, mat_ptr); result = (Matrix4x4) Marshal.PtrToStructure(mat_ptr, typeof(Matrix4x4)); return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Collections; using System.Globalization; using System.ComponentModel; using System.Diagnostics; namespace System.DirectoryServices.ActiveDirectory { public class ActiveDirectorySiteLinkBridge : IDisposable { internal readonly DirectoryContext context = null; private readonly string _name = null; private readonly ActiveDirectoryTransportType _transport = ActiveDirectoryTransportType.Rpc; private bool _disposed = false; private bool _existing = false; internal DirectoryEntry cachedEntry = null; private readonly ActiveDirectorySiteLinkCollection _links = new ActiveDirectorySiteLinkCollection(); private bool _linksRetrieved = false; public ActiveDirectorySiteLinkBridge(DirectoryContext context, string bridgeName) : this(context, bridgeName, ActiveDirectoryTransportType.Rpc) { } public ActiveDirectorySiteLinkBridge(DirectoryContext context, string bridgeName, ActiveDirectoryTransportType transport) { ValidateArgument(context, bridgeName, transport); // work with copy of the context context = new DirectoryContext(context); this.context = context; _name = bridgeName; _transport = transport; // bind to the rootdse to get the configurationnamingcontext DirectoryEntry de; try { de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); string parentDN = null; if (transport == ActiveDirectoryTransportType.Rpc) parentDN = "CN=IP,CN=Inter-Site Transports,CN=Sites," + config; else parentDN = "CN=SMTP,CN=Inter-Site Transports,CN=Sites," + config; de = DirectoryEntryManager.GetDirectoryEntry(context, parentDN); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name)); } try { string rdn = "cn=" + _name; rdn = Utils.GetEscapedPath(rdn); cachedEntry = de.Children.Add(rdn, "siteLinkBridge"); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { // if it is ADAM and transport type is SMTP, throw NotSupportedException. DirectoryEntry tmpDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); if (Utils.CheckCapability(tmpDE, Capability.ActiveDirectoryApplicationMode) && transport == ActiveDirectoryTransportType.Smtp) { throw new NotSupportedException(SR.NotSupportTransportSMTP); } } throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { de.Dispose(); } } internal ActiveDirectorySiteLinkBridge(DirectoryContext context, string bridgeName, ActiveDirectoryTransportType transport, bool existing) { this.context = context; _name = bridgeName; _transport = transport; _existing = existing; } public static ActiveDirectorySiteLinkBridge FindByName(DirectoryContext context, string bridgeName) { return FindByName(context, bridgeName, ActiveDirectoryTransportType.Rpc); } public static ActiveDirectorySiteLinkBridge FindByName(DirectoryContext context, string bridgeName, ActiveDirectoryTransportType transport) { ValidateArgument(context, bridgeName, transport); // work with copy of the context context = new DirectoryContext(context); // bind to the rootdse to get the configurationnamingcontext DirectoryEntry de; try { de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); string containerDN = "CN=Inter-Site Transports,CN=Sites," + config; if (transport == ActiveDirectoryTransportType.Rpc) containerDN = "CN=IP," + containerDN; else containerDN = "CN=SMTP," + containerDN; de = DirectoryEntryManager.GetDirectoryEntry(context, containerDN); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name)); } try { ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=siteLinkBridge)(objectCategory=SiteLinkBridge)(name=" + Utils.GetEscapedFilterValue(bridgeName) + "))", new string[] { "distinguishedName" }, SearchScope.OneLevel, false, /* don't need paged search */ false /* don't need to cache result */); SearchResult srchResult = adSearcher.FindOne(); if (srchResult == null) { // no such site link bridge object Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySiteLinkBridge), bridgeName); throw e; } else { DirectoryEntry connectionEntry = srchResult.GetDirectoryEntry(); // it is an existing site link bridge object ActiveDirectorySiteLinkBridge bridge = new ActiveDirectorySiteLinkBridge(context, bridgeName, transport, true); bridge.cachedEntry = connectionEntry; return bridge; } } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { // if it is ADAM and transport type is SMTP, throw NotSupportedException. DirectoryEntry tmpDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); if (Utils.CheckCapability(tmpDE, Capability.ActiveDirectoryApplicationMode) && transport == ActiveDirectoryTransportType.Smtp) { throw new NotSupportedException(SR.NotSupportTransportSMTP); } else { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySiteLinkBridge), bridgeName); } } throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { de.Dispose(); } } public string Name { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); return _name; } } public ActiveDirectorySiteLinkCollection SiteLinks { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (_existing) { // if asked the first time, we need to properly construct the subnets collection if (!_linksRetrieved) { _links.initialized = false; _links.Clear(); GetLinks(); _linksRetrieved = true; } } _links.initialized = true; _links.de = cachedEntry; _links.context = context; return _links; } } public ActiveDirectoryTransportType TransportType { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); return _transport; } } public void Save() { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { cachedEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (_existing) { // indicates that nex time user asks for SiteLinks property, we might need to fetch it from server _linksRetrieved = false; } else { _existing = true; } } public void Delete() { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (!_existing) { throw new InvalidOperationException(SR.CannotDelete); } else { try { cachedEntry.Parent.Children.Remove(cachedEntry); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public override string ToString() { if (_disposed) throw new ObjectDisposedException(GetType().Name); return _name; } public DirectoryEntry GetDirectoryEntry() { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (!_existing) { throw new InvalidOperationException(SR.CannotGetObject); } else { return DirectoryEntryManager.GetDirectoryEntryInternal(context, cachedEntry.Path); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // free other state (managed objects) if (cachedEntry != null) cachedEntry.Dispose(); } // free your own state (unmanaged objects) _disposed = true; } private static void ValidateArgument(DirectoryContext context, string bridgeName, ActiveDirectoryTransportType transport) { // basic validation first if (context == null) throw new ArgumentNullException("context"); // if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, "context"); } // more validation for the context, if the target is not null, then it should be either forest name or server name if (context.Name != null) { if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet())) throw new ArgumentException(SR.NotADOrADAM, "context"); } if (bridgeName == null) throw new ArgumentNullException("bridgeName"); if (bridgeName.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "bridgeName"); if (transport < ActiveDirectoryTransportType.Rpc || transport > ActiveDirectoryTransportType.Smtp) throw new InvalidEnumArgumentException("value", (int)transport, typeof(ActiveDirectoryTransportType)); } private void GetLinks() { ArrayList propertyList = new ArrayList(); NativeComInterfaces.IAdsPathname pathCracker = null; pathCracker = (NativeComInterfaces.IAdsPathname)new NativeComInterfaces.Pathname(); // need to turn off the escaping for name pathCracker.EscapedMode = NativeComInterfaces.ADS_ESCAPEDMODE_OFF_EX; string propertyName = "siteLinkList"; propertyList.Add(propertyName); Hashtable values = Utils.GetValuesWithRangeRetrieval(cachedEntry, "(objectClass=*)", propertyList, SearchScope.Base); ArrayList siteLinkLists = (ArrayList)values[propertyName.ToLower(CultureInfo.InvariantCulture)]; // somehow no site link list if (siteLinkLists == null) return; // construct the site link object for (int i = 0; i < siteLinkLists.Count; i++) { string dn = (string)siteLinkLists[i]; // escaping manipulation pathCracker.Set(dn, NativeComInterfaces.ADS_SETTYPE_DN); string rdn = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF); Debug.Assert(rdn != null && Utils.Compare(rdn, 0, 3, "CN=", 0, 3) == 0); rdn = rdn.Substring(3); DirectoryEntry entry = DirectoryEntryManager.GetDirectoryEntry(context, dn); ActiveDirectorySiteLink link = new ActiveDirectorySiteLink(context, rdn, _transport, true, entry); _links.Add(link); } } } }
using System; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Runtime; namespace Orleans.Internal { public static class OrleansTaskExtentions { internal static readonly Task<object> CanceledTask = TaskFromCanceled<object>(); internal static readonly Task<object> CompletedTask = Task.FromResult(default(object)); /// <summary> /// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task"/>. /// </summary> /// <param name="task">The task.</param> public static Task<object> ToUntypedTask(this Task task) { switch (task.Status) { case TaskStatus.RanToCompletion: return CompletedTask; case TaskStatus.Faulted: return TaskFromFaulted(task); case TaskStatus.Canceled: return CanceledTask; default: return ConvertAsync(task); } async Task<object> ConvertAsync(Task asyncTask) { await asyncTask; return null; } } /// <summary> /// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{T}"/>. /// </summary> /// <typeparam name="T">The underlying type of <paramref name="task"/>.</typeparam> /// <param name="task">The task.</param> public static Task<object> ToUntypedTask<T>(this Task<T> task) { if (typeof(T) == typeof(object)) return task as Task<object>; switch (task.Status) { case TaskStatus.RanToCompletion: return Task.FromResult((object)GetResult(task)); case TaskStatus.Faulted: return TaskFromFaulted(task); case TaskStatus.Canceled: return CanceledTask; default: return ConvertAsync(task); } async Task<object> ConvertAsync(Task<T> asyncTask) { return await asyncTask.ConfigureAwait(false); } } /// <summary> /// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{T}"/>. /// </summary> /// <typeparam name="T">The underlying type of <paramref name="task"/>.</typeparam> /// <param name="task">The task.</param> internal static Task<T> ToTypedTask<T>(this Task<object> task) { if (typeof(T) == typeof(object)) return task as Task<T>; switch (task.Status) { case TaskStatus.RanToCompletion: return Task.FromResult((T)GetResult(task)); case TaskStatus.Faulted: return TaskFromFaulted<T>(task); case TaskStatus.Canceled: return TaskFromCanceled<T>(); default: return ConvertAsync(task); } async Task<T> ConvertAsync(Task<object> asyncTask) { var result = await asyncTask.ConfigureAwait(false); if (result is null) { if (!NullabilityHelper<T>.IsNullableType) { ThrowInvalidTaskResultType(typeof(T)); } return default; } return (T)result; } } private static class NullabilityHelper<T> { /// <summary> /// True if <typeparamref name="T" /> is an instance of a nullable type (a reference type or <see cref="Nullable{T}"/>), otherwise false. /// </summary> public static readonly bool IsNullableType = !typeof(T).IsValueType || typeof(T).IsConstructedGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowInvalidTaskResultType(Type type) { var message = $"Expected result of type {type} but encountered a null value. This may be caused by a grain call filter swallowing an exception."; throw new InvalidOperationException(message); } /// <summary> /// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{Object}"/>. /// </summary> /// <param name="task">The task.</param> public static Task<object> ToUntypedTask(this Task<object> task) { return task; } private static Task<object> TaskFromFaulted(Task task) { var completion = new TaskCompletionSource<object>(); completion.SetException(task.Exception.InnerExceptions); return completion.Task; } private static Task<T> TaskFromFaulted<T>(Task task) { var completion = new TaskCompletionSource<T>(); completion.SetException(task.Exception.InnerExceptions); return completion.Task; } private static Task<T> TaskFromCanceled<T>() { var completion = new TaskCompletionSource<T>(); completion.SetCanceled(); return completion.Task; } public static async Task LogException(this Task task, ILogger logger, ErrorCode errorCode, string message) { try { await task; } catch (Exception exc) { var ignored = task.Exception; // Observe exception logger.Error(errorCode, message, exc); throw; } } // Executes an async function such as Exception is never thrown but rather always returned as a broken task. public static async Task SafeExecute(Func<Task> action) { await action(); } public static async Task ExecuteAndIgnoreException(Func<Task> action) { try { await action(); } catch (Exception) { // dont re-throw, just eat it. } } internal static String ToString(this Task t) { return t == null ? "null" : string.Format("[Id={0}, Status={1}]", t.Id, Enum.GetName(typeof(TaskStatus), t.Status)); } internal static String ToString<T>(this Task<T> t) { return t == null ? "null" : string.Format("[Id={0}, Status={1}]", t.Id, Enum.GetName(typeof(TaskStatus), t.Status)); } public static void WaitWithThrow(this Task task, TimeSpan timeout) { if (!task.Wait(timeout)) { throw new TimeoutException($"Task.WaitWithThrow has timed out after {timeout}."); } } internal static T WaitForResultWithThrow<T>(this Task<T> task, TimeSpan timeout) { if (!task.Wait(timeout)) { throw new TimeoutException($"Task<T>.WaitForResultWithThrow has timed out after {timeout}."); } return task.Result; } /// <summary> /// This will apply a timeout delay to the task, allowing us to exit early /// </summary> /// <param name="taskToComplete">The task we will timeout after timeSpan</param> /// <param name="timeout">Amount of time to wait before timing out</param> /// <param name="exceptionMessage">Text to put into the timeout exception message</param> /// <exception cref="TimeoutException">If we time out we will get this exception</exception> /// <returns>The completed task</returns> public static async Task WithTimeout(this Task taskToComplete, TimeSpan timeout, string exceptionMessage = null) { if (taskToComplete.IsCompleted) { await taskToComplete; return; } var timeoutCancellationTokenSource = new CancellationTokenSource(); var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); // We got done before the timeout, or were able to complete before this code ran, return the result if (taskToComplete == completedTask) { timeoutCancellationTokenSource.Cancel(); // Await this so as to propagate the exception correctly await taskToComplete; return; } // We did not complete before the timeout, we fire and forget to ensure we observe any exceptions that may occur taskToComplete.Ignore(); var errorMessage = exceptionMessage ?? $"WithTimeout has timed out after {timeout}"; throw new TimeoutException(errorMessage); } /// <summary> /// This will apply a timeout delay to the task, allowing us to exit early /// </summary> /// <param name="taskToComplete">The task we will timeout after timeSpan</param> /// <param name="timeSpan">Amount of time to wait before timing out</param> /// <param name="exceptionMessage">Text to put into the timeout exception message</param> /// <exception cref="TimeoutException">If we time out we will get this exception</exception> /// <exception cref="TimeoutException">If we time out we will get this exception</exception> /// <returns>The value of the completed task</returns> public static async Task<T> WithTimeout<T>(this Task<T> taskToComplete, TimeSpan timeSpan, string exceptionMessage = null) { if (taskToComplete.IsCompleted) { return await taskToComplete; } var timeoutCancellationTokenSource = new CancellationTokenSource(); var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeSpan, timeoutCancellationTokenSource.Token)); // We got done before the timeout, or were able to complete before this code ran, return the result if (taskToComplete == completedTask) { timeoutCancellationTokenSource.Cancel(); // Await this so as to propagate the exception correctly return await taskToComplete; } // We did not complete before the timeout, we fire and forget to ensure we observe any exceptions that may occur taskToComplete.Ignore(); var errorMessage = exceptionMessage ?? $"WithTimeout has timed out after {timeSpan}"; throw new TimeoutException(errorMessage); } /// <summary> /// For making an uncancellable task cancellable, by ignoring its result. /// </summary> /// <param name="taskToComplete">The task to wait for unless cancelled</param> /// <param name="cancellationToken">A cancellation token for cancelling the wait</param> /// <param name="message">Message to set in the exception</param> /// <returns></returns> internal static async Task WithCancellation( this Task taskToComplete, CancellationToken cancellationToken, string message) { try { await taskToComplete.WithCancellation(cancellationToken); } catch (TaskCanceledException ex) { throw new TaskCanceledException(message, ex); } } /// <summary> /// For making an uncancellable task cancellable, by ignoring its result. /// </summary> /// <param name="taskToComplete">The task to wait for unless cancelled</param> /// <param name="cancellationToken">A cancellation token for cancelling the wait</param> /// <returns></returns> internal static Task WithCancellation(this Task taskToComplete, CancellationToken cancellationToken) { if (taskToComplete.IsCompleted || !cancellationToken.CanBeCanceled) { return taskToComplete; } else if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<object>(cancellationToken); } else { return MakeCancellable(taskToComplete, cancellationToken); } } private static async Task MakeCancellable(Task task, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<object>(); using (cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken), useSynchronizationContext: false)) { var firstToComplete = await Task.WhenAny(task, tcs.Task).ConfigureAwait(false); if (firstToComplete != task) { task.Ignore(); } await firstToComplete.ConfigureAwait(false); } } /// <summary> /// For making an uncancellable task cancellable, by ignoring its result. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="taskToComplete">The task to wait for unless cancelled</param> /// <param name="cancellationToken">A cancellation token for cancelling the wait</param> /// <param name="message">Message to set in the exception</param> /// <returns></returns> internal static async Task<T> WithCancellation<T>( this Task<T> taskToComplete, CancellationToken cancellationToken, string message) { try { return await taskToComplete.WithCancellation(cancellationToken); } catch (TaskCanceledException ex) { throw new TaskCanceledException(message, ex); } } /// <summary> /// For making an uncancellable task cancellable, by ignoring its result. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="taskToComplete">The task to wait for unless cancelled</param> /// <param name="cancellationToken">A cancellation token for cancelling the wait</param> /// <returns></returns> internal static Task<T> WithCancellation<T>(this Task<T> taskToComplete, CancellationToken cancellationToken) { if (taskToComplete.IsCompleted || !cancellationToken.CanBeCanceled) { return taskToComplete; } else if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<T>(cancellationToken); } else { return MakeCancellable(taskToComplete, cancellationToken); } } private static async Task<T> MakeCancellable<T>(Task<T> task, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<T>(); using (cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken), useSynchronizationContext: false)) { var firstToComplete = await Task.WhenAny(task, tcs.Task).ConfigureAwait(false); if (firstToComplete != task) { task.Ignore(); } return await firstToComplete.ConfigureAwait(false); } } internal static Task WrapInTask(Action action) { try { action(); return Task.CompletedTask; } catch (Exception exc) { return Task.FromException<object>(exc); } } internal static Task<T> ConvertTaskViaTcs<T>(Task<T> task) { if (task == null) return Task.FromResult(default(T)); var resolver = new TaskCompletionSource<T>(); if (task.Status == TaskStatus.RanToCompletion) { resolver.TrySetResult(task.Result); } else if (task.IsFaulted) { resolver.TrySetException(task.Exception.InnerExceptions); } else if (task.IsCanceled) { resolver.TrySetException(new TaskCanceledException(task)); } else { if (task.Status == TaskStatus.Created) task.Start(); task.ContinueWith(t => { if (t.IsFaulted) { resolver.TrySetException(t.Exception.InnerExceptions); } else if (t.IsCanceled) { resolver.TrySetException(new TaskCanceledException(t)); } else { resolver.TrySetResult(t.GetResult()); } }); } return resolver.Task; } //The rationale for GetAwaiter().GetResult() instead of .Result //is presented at https://github.com/aspnet/Security/issues/59. internal static T GetResult<T>(this Task<T> task) { return task.GetAwaiter().GetResult(); } internal static void GetResult(this Task task) { task.GetAwaiter().GetResult(); } internal static Task WhenCancelled(this CancellationToken token) { if (token.IsCancellationRequested) { return Task.CompletedTask; } var waitForCancellation = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); token.Register(obj => { var tcs = (TaskCompletionSource<object>)obj; tcs.TrySetResult(null); }, waitForCancellation); return waitForCancellation.Task; } } } namespace Orleans { /// <summary> /// A special void 'Done' Task that is already in the RunToCompletion state. /// Equivalent to Task.FromResult(1). /// </summary> public static class TaskDone { /// <summary> /// A special 'Done' Task that is already in the RunToCompletion state /// </summary> [Obsolete("Use Task.CompletedTask")] public static Task Done => Task.CompletedTask; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using ComponentAce.Compression.Libs.zlib; using IdSharp.Common.Utils; namespace IdSharp.Tagging.ID3v2 { internal static class ID3v2Utils { public static int ReadInt32SyncSafe(Stream stream) { byte[] byteArray = stream.Read(4); int returnValue = ((byteArray[0] << 21) + (byteArray[1] << 14) + (byteArray[2] << 7) + byteArray[3]); return returnValue; } private static void CopyStream(Stream input, Stream output, int size) { byte[] buffer = new byte[size]; input.Read(buffer, 0, size); output.Write(buffer, 0, size); output.Flush(); } public static Stream DecompressFrame(Stream stream, int compressedSize) { Stream outStream = new MemoryStream(); ZOutputStream outZStream = new ZOutputStream(outStream); CopyStream(stream, outZStream, compressedSize); outStream.Position = 0; return outStream; } public static Stream ReadUnsynchronizedStream(Stream stream, int length) { Stream newStream = new MemoryStream(ReadUnsynchronized(stream, length), 0, length); newStream.Position = 0; return newStream; } public static byte[] ReadUnsynchronized(byte[] stream) { using (MemoryStream byteList = new MemoryStream(stream.Length)) { for (int i = 0, j = 0; i < stream.Length; i++) { byte myByte = stream[j++]; byteList.WriteByte(myByte); if (myByte == 0xFF) { myByte = stream[j++]; // skip 0x00 if (myByte != 0) { byteList.WriteByte(myByte); i++; } } } return byteList.ToArray(); } } public static byte[] ReadUnsynchronized(Stream stream, int size) { using (MemoryStream byteList = new MemoryStream(size)) { for (int i = 0; i < size; i++) { byte myByte = stream.Read1(); byteList.WriteByte(myByte); if (myByte == 0xFF) { myByte = stream.Read1(); // skip 0x00 if (myByte != 0) { byteList.WriteByte(myByte); i++; } } } return byteList.ToArray(); } } public static int ReadInt32Unsynchronized(Stream stream) { byte[] byteArray = ReadUnsynchronized(stream, 4); int returnValue = (byteArray[0] << 24) + (byteArray[1] << 16) + (byteArray[2] << 8) + byteArray[3]; return returnValue; } public static int ReadInt24Unsynchronized(Stream stream) { byte[] byteArray = ReadUnsynchronized(stream, 3); int returnValue = (byteArray[0] << 16) + (byteArray[1] << 8) + byteArray[2]; return returnValue; } public static byte[] GetStringBytes(ID3v2TagVersion tagVersion, EncodingType encodingType, string value, bool isTerminated) { List<byte> byteList = new List<byte>(); switch (tagVersion) { case ID3v2TagVersion.ID3v22: switch (encodingType) { case EncodingType.Unicode: if (!string.IsNullOrEmpty(value)) { byteList.Add(0xFF); byteList.Add(0xFE); byteList.AddRange(Encoding.Unicode.GetBytes(value)); // WITH BOM } if (isTerminated) byteList.AddRange(new byte[] { 0, 0 }); break; default: byteList.AddRange(ByteUtils.ISO88591GetBytes(value)); if (isTerminated) byteList.Add(0); break; } break; case ID3v2TagVersion.ID3v23: switch (encodingType) { case EncodingType.Unicode: if (!string.IsNullOrEmpty(value)) { byteList.Add(0xFF); byteList.Add(0xFE); byteList.AddRange(Encoding.Unicode.GetBytes(value)); // WITH BOM } if (isTerminated) byteList.AddRange(new byte[] { 0, 0 }); break; default: byteList.AddRange(ByteUtils.ISO88591GetBytes(value)); if (isTerminated) byteList.Add(0); break; } break; case ID3v2TagVersion.ID3v24: switch (encodingType) { case EncodingType.UTF8: if (!string.IsNullOrEmpty(value)) { byteList.AddRange(Encoding.UTF8.GetBytes(value)); } if (isTerminated) byteList.Add(0); break; case EncodingType.UTF16BE: if (!string.IsNullOrEmpty(value)) { byteList.AddRange(Encoding.BigEndianUnicode.GetBytes(value)); // no BOM } if (isTerminated) byteList.AddRange(new byte[] { 0, 0 }); break; case EncodingType.Unicode: if (!string.IsNullOrEmpty(value)) { byteList.Add(0xFF); byteList.Add(0xFE); byteList.AddRange(Encoding.Unicode.GetBytes(value)); // WITH BOM } if (isTerminated) byteList.AddRange(new byte[] { 0, 0 }); break; default: byteList.AddRange(ByteUtils.ISO88591GetBytes(value)); if (isTerminated) byteList.Add(0); break; } break; default: throw new ArgumentException("Unknown tag version"); } return byteList.ToArray(); } public static byte[] ConvertToUnsynchronized(byte[] data) { using (MemoryStream newStream = new MemoryStream((int)(data.Length * 1.05))) { for (int i = 0; i < data.Length; i++) { newStream.WriteByte(data[i]); if (data[i] == 0xFF) { if (i != data.Length - 1) { if (data[i + 1] == 0x00 || ((data[i + 1] & 0xE0) == 0xE0)) // 0xE0 = 1110 0000 { newStream.WriteByte(0); } } } } return newStream.ToArray(); } } public static string ReadString(EncodingType textEncoding, byte[] bytes, int length) { using (MemoryStream memoryStream = new MemoryStream(bytes)) { return ReadString(textEncoding, memoryStream, length); } } public static string ReadString(EncodingType textEncoding, Stream stream, int length) { string returnValue = string.Empty; byte[] byteArray = stream.Read(length); if (textEncoding == EncodingType.ISO88591) { returnValue = ByteUtils.ISO88591GetString(byteArray); } else if (textEncoding == EncodingType.Unicode) { if (length > 2) { if (byteArray.Length >= 2) { // If BOM is part of the string, decode as the appropriate Unicode type. // If no BOM is present use Little Endian Unicode. if (byteArray[0] == 0xFF && byteArray[1] == 0xFE) returnValue = Encoding.Unicode.GetString(byteArray, 2, byteArray.Length - 2); else if (byteArray[0] == 0xFE && byteArray[1] == 0xFF) returnValue = Encoding.BigEndianUnicode.GetString(byteArray, 2, byteArray.Length - 2); else returnValue = Encoding.Unicode.GetString(byteArray, 0, byteArray.Length); } else { returnValue = Encoding.Unicode.GetString(byteArray, 0, byteArray.Length); } } } else if (textEncoding == EncodingType.UTF16BE) { if (byteArray.Length >= 2) { // If BOM is part of the string, remove before decoding. if (byteArray[0] == 0xFE && byteArray[1] == 0xFF) returnValue = Encoding.BigEndianUnicode.GetString(byteArray, 2, byteArray.Length - 2); else returnValue = Encoding.BigEndianUnicode.GetString(byteArray, 0, byteArray.Length); } else { returnValue = Encoding.BigEndianUnicode.GetString(byteArray, 0, byteArray.Length); } } else if (textEncoding == EncodingType.UTF8) { returnValue = Encoding.UTF8.GetString(byteArray, 0, length); } else { // Most likely bad data string msg = string.Format("Text Encoding '{0}' unknown at position {1}", textEncoding, stream.Position); Trace.WriteLine(msg); } return returnValue.TrimEnd('\0'); } public static string ReadString(EncodingType textEncoding, byte[] bytes) { if (bytes == null) throw new ArgumentNullException("bytes"); using (MemoryStream memoryStream = new MemoryStream(bytes)) { return ReadString(textEncoding, memoryStream); } } public static string ReadString(EncodingType textEncoding, Stream stream) { if (stream == null) throw new ArgumentNullException("stream"); string returnValue; List<byte> byteList = new List<byte>(); if (textEncoding == EncodingType.ISO88591) { byte readByte = stream.Read1(); while (readByte != 0) { byteList.Add(readByte); readByte = stream.Read1(); } returnValue = ByteUtils.ISO88591GetString(byteList.ToArray()); } else if (textEncoding == EncodingType.Unicode) { byte byte1; byte byte2; do { byte1 = stream.Read1(); byteList.Add(byte1); byte2 = stream.Read1(); byteList.Add(byte2); } while (byte1 != 0 || byte2 != 0); byte[] byteArray = byteList.ToArray(); if (byteArray.Length >= 2) { // If BOM is part of the string, decode as the appropriate Unicode type. // If no BOM is present use Little Endian Unicode. if (byteArray[0] == 0xFF && byteArray[1] == 0xFE) returnValue = Encoding.Unicode.GetString(byteArray, 2, byteArray.Length - 2); else if (byteArray[0] == 0xFE && byteArray[1] == 0xFF) returnValue = Encoding.BigEndianUnicode.GetString(byteArray, 2, byteArray.Length - 2); else returnValue = Encoding.Unicode.GetString(byteArray, 0, byteArray.Length); } else { returnValue = Encoding.Unicode.GetString(byteArray, 0, byteArray.Length); } } else if (textEncoding == EncodingType.UTF16BE) { byte byte1; byte byte2; do { byte1 = stream.Read1(); byteList.Add(byte1); byte2 = stream.Read1(); byteList.Add(byte2); } while (byte1 != 0 || byte2 != 0); byte[] byteArray = byteList.ToArray(); if (byteArray.Length >= 2) { // If BOM is part of the string, remove before decoding. if (byteArray[0] == 0xFE && byteArray[1] == 0xFF) returnValue = Encoding.BigEndianUnicode.GetString(byteArray, 2, byteArray.Length - 2); else returnValue = Encoding.BigEndianUnicode.GetString(byteArray, 0, byteArray.Length); } else { returnValue = Encoding.BigEndianUnicode.GetString(byteArray, 0, byteArray.Length); } } else if (textEncoding == EncodingType.UTF8) { byte readByte = stream.Read1(); while (readByte != 0) { byteList.Add(readByte); readByte = stream.Read1(); } returnValue = Encoding.UTF8.GetString(byteList.ToArray()); } else { // Most likely bad data string msg = string.Format("Text Encoding '{0}' unknown at position {1}", textEncoding, stream.Position); Trace.WriteLine(msg); return ""; } returnValue = returnValue.TrimEnd('\0'); return returnValue; } public static string ReadString(EncodingType textEncoding, Stream stream, ref int bytesLeft) { if (bytesLeft <= 0) { //String msg = String.Format("ReadString (unknown length) called with {0} bytes left at position {1}", bytesLeft, stream.Position); //Trace.WriteLine(msg); return string.Empty; } string returnValue; List<byte> byteList = new List<byte>(); if (textEncoding == EncodingType.ISO88591) { byte readByte = stream.Read1(); --bytesLeft; if (bytesLeft == 0) { //String msg = String.Format("End of frame reached while reading unknown length string at position {0}", stream.Position); //Trace.WriteLine(msg); return ""; } while (readByte != 0) { byteList.Add(readByte); readByte = stream.Read1(); --bytesLeft; if (bytesLeft == 0) { //String msg = String.Format("End of frame reached while reading unknown length string at position {0}", stream.Position); //Trace.WriteLine(msg); if (readByte != 0) byteList.Add(readByte); return ByteUtils.ISO88591GetString(byteList.ToArray()); } } returnValue = ByteUtils.ISO88591GetString(byteList.ToArray()); } else if (textEncoding == EncodingType.Unicode) { byte byte1; byte byte2; do { byte1 = stream.Read1(); byteList.Add(byte1); --bytesLeft; if (bytesLeft == 0) { //String msg = String.Format("End of frame reached while reading unknown length string at position {0}", stream.Position); //Trace.WriteLine(msg); return ""; } byte2 = stream.Read1(); byteList.Add(byte2); --bytesLeft; if (bytesLeft == 0) { //String msg = String.Format("End of frame reached while reading unknown length string at position {0}", stream.Position); //Trace.WriteLine(msg); break; //return ""; } } while (byte1 != 0 || byte2 != 0); byte[] byteArray = byteList.ToArray(); if (byteArray.Length >= 2) { // If BOM is part of the string, decode as the appropriate Unicode type. // If no BOM is present use Little Endian Unicode. if (byteArray[0] == 0xFF && byteArray[1] == 0xFE) returnValue = Encoding.Unicode.GetString(byteArray, 2, byteArray.Length - 2); else if (byteArray[0] == 0xFE && byteArray[1] == 0xFF) returnValue = Encoding.BigEndianUnicode.GetString(byteArray, 2, byteArray.Length - 2); else returnValue = Encoding.Unicode.GetString(byteArray, 0, byteArray.Length); } else { returnValue = Encoding.Unicode.GetString(byteArray, 0, byteArray.Length); } } else if (textEncoding == EncodingType.UTF16BE) { byte byte1; byte byte2; do { byte1 = stream.Read1(); byteList.Add(byte1); --bytesLeft; if (bytesLeft == 0) { //String msg = String.Format("End of frame reached while reading unknown length string at position {0}", stream.Position); //Trace.WriteLine(msg); return ""; } byte2 = stream.Read1(); byteList.Add(byte2); --bytesLeft; if (bytesLeft == 0) { //String msg = String.Format("End of frame reached while reading unknown length string at position {0}", stream.Position); //Trace.WriteLine(msg); break; //return ""; } } while (byte1 != 0 || byte2 != 0); byte[] byteArray = byteList.ToArray(); if (byteArray.Length >= 2) { // If BOM is part of the string, remove before decoding. if (byteArray[0] == 0xFE && byteArray[1] == 0xFF) returnValue = Encoding.BigEndianUnicode.GetString(byteArray, 2, byteArray.Length - 2); else returnValue = Encoding.BigEndianUnicode.GetString(byteArray, 0, byteArray.Length); } else { returnValue = Encoding.BigEndianUnicode.GetString(byteArray, 0, byteArray.Length); } } else if (textEncoding == EncodingType.UTF8) { byte readByte = stream.Read1(); --bytesLeft; if (bytesLeft == 0) { //String msg = String.Format("End of frame reached while reading unknown length string at position {0}", stream.Position); //Trace.WriteLine(msg); return ""; } while (readByte != 0) { byteList.Add(readByte); readByte = stream.Read1(); --bytesLeft; if (bytesLeft == 0) { //String msg = String.Format("End of frame reached while reading unknown length string at position {0}", stream.Position); //Trace.WriteLine(msg); return ""; } } returnValue = Encoding.UTF8.GetString(byteList.ToArray()); } else { // Most likely bad data string msg = string.Format("Text Encoding '{0}' unknown at position {1}", textEncoding, stream.Position); Trace.WriteLine(msg); return ""; } returnValue = returnValue.TrimEnd('\0'); return returnValue; } } }
// ReSharper disable InconsistentNaming using System; using System.Runtime.Serialization; using System.Threading; using NUnit.Framework; using RabbitMQ.Client; namespace EasyNetQ.Tests.Integration { [TestFixture] public class RequestResponseTests { private IBus bus; [SetUp] public void SetUp() { bus = RabbitHutch.CreateBus("host=localhost"); bus.Respond<TestRequestMessage, TestResponseMessage>(req => new TestResponseMessage { Text = req.Text }); } [TearDown] public void TearDown() { bus.Dispose(); } // First start the EasyNetQ.Tests.SimpleService console app. [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Large_number_of_request_calls_should_not_create_a_large_number_of_open_channels() { const int numberOfCalls = 100; var countdownEvent = new CountdownEvent(numberOfCalls); for (int i = 0; i < numberOfCalls; i++) { bus.RequestAsync<TestRequestMessage, TestResponseMessage>( new TestRequestMessage {Text = string.Format("Hello from client number: {0}! ", i)}) .ContinueWith( response => { Console.WriteLine("Got response: " + response.Result.Text); countdownEvent.Signal(); } ); } countdownEvent.Wait(1000); Console.WriteLine("Test end"); } // First start the EasyNetQ.Tests.SimpleService console app. // Run this test. You should see the SimpleService report that it's // responding and the response should appear here. [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_be_able_to_do_simple_request_response() { var request = new TestRequestMessage {Text = "Hello from the client! "}; Console.WriteLine("Making request"); var response = bus.Request<TestRequestMessage, TestResponseMessage>(request); Console.WriteLine("Got response: '{0}'", response.Text); } // First start the EasyNetQ.Tests.SimpleService console app. // Run this test. You should see the SimpleService report that it's // responding to 1000 messages and you should see the messages return here. [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_be_able_to_do_simple_request_response_lots() { const int numberOfCalls = 5000; var countdownEvent = new CountdownEvent(numberOfCalls); var count = 0; for (int i = 0; i < numberOfCalls; i++) { var request = new TestRequestMessage { Text = "Hello from the client! " + i.ToString() }; bus.RequestAsync<TestRequestMessage, TestResponseMessage>(request).ContinueWith(response => { Console.WriteLine("Got response: '{0}'", response.Result.Text); count++; countdownEvent.Signal(); }); } countdownEvent.Wait(15000); count.ShouldEqual(numberOfCalls); } // First start the EasyNetQ.Tests.SimpleService console app. // Run this test. You should see the SimpleService report that it's // responding and the response should appear here. [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_be_able_to_make_a_request_that_runs_async_on_the_server() { var autoResetEvent = new AutoResetEvent(false); var request = new TestAsyncRequestMessage {Text = "Hello async from the client!"}; Console.Out.WriteLine("Making request"); bus.RequestAsync<TestAsyncRequestMessage, TestAsyncResponseMessage>(request).ContinueWith(response => { Console.Out.WriteLine("response = {0}", response.Result.Text); autoResetEvent.Set(); }); autoResetEvent.WaitOne(2000); } // First start the EasyNetQ.Tests.SimpleService console app. // Run this test. You should see 1000 response messages on the SimpleService // and then 1000 messages appear back here. [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_be_able_to_make_many_async_requests() { const int numberOfCalls = 500; var countdownEvent = new CountdownEvent(numberOfCalls); var count = 0; for (int i = 0; i < 1000; i++) { var request = new TestAsyncRequestMessage { Text = "Hello async from the client! " + i }; bus.RequestAsync<TestAsyncRequestMessage, TestAsyncResponseMessage>(request).ContinueWith(response => { Console.Out.WriteLine("response = {0}", response.Result.Text); Interlocked.Increment(ref count); countdownEvent.Signal(); }); } countdownEvent.Wait(10000); count.ShouldEqual(numberOfCalls); } /// <summary> /// First start the EasyNetQ.Tests.SimpleService console app. /// Run this test. You should see an error message written to the error queue /// and an error logged /// </summary> [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Service_should_handle_sychronous_message_of_the_wrong_type() { const string routingKey = "EasyNetQ_Tests_TestRequestMessage:EasyNetQ_Tests_Messages"; const string type = "not_the_type_you_are_expecting"; MakeRpcRequest(type, routingKey); } /// <summary> /// First start the EasyNetQ.Tests.SimpleService console app. /// Run this test. You should see an error message written to the error queue /// and an error logged /// </summary> [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Service_should_handle_asychronous_message_of_the_wrong_type() { const string routingKey = "EasyNetQ_Tests_TestAsyncRequestMessage:EasyNetQ_Tests_Messages"; const string type = "not_the_type_you_are_expecting"; MakeRpcRequest(type, routingKey); } private static void MakeRpcRequest(string type, string routingKey) { var connectionFactory = new ConnectionFactory { HostName = "localhost" }; using (var connection = connectionFactory.CreateConnection()) using (var model = connection.CreateModel()) { var properties = model.CreateBasicProperties(); properties.Type = type; model.BasicPublish( "easy_net_q_rpc", // exchange routingKey, // routing key false, // manditory false, // immediate properties, new byte[0]); } } // First start the EasyNetQ.Tests.SimpleService console app. // Run this test. You should see the SimpleService report that it's // Thrown and a new error message in the error queue. [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_be_able_to_do_simple_request_response_that_throws_on_server() { var request = new TestRequestMessage { Text = "Hello from the client! ", CausesExceptionInServer = true }; Console.WriteLine("Making request"); bus.RequestAsync<TestRequestMessage, TestResponseMessage>(request).ContinueWith(response => Console.WriteLine("Got response: '{0}'", response.Result.Text)); Thread.Sleep(500); } // First start the EasyNetQ.Tests.SimpleService console app. // Run this test. You should see the SimpleService report that it's // Thrown, a new error message in the error queue and an EasyNetQResponderException // exception should be thrown by the consumer as a response. [Test, Explicit("Needs a Rabbit instance on localhost to work")] [ExpectedException(ExpectedException = typeof(EasyNetQResponderException), ExpectedMessage = "This should be the original exception message!")] public void Should_throw_an_exception_at_consumer_on_simple_request_response_that_throws_on_server() { var request = new TestRequestMessage { Text = "Hello from the client! ", CausesExceptionInServer = true, ExceptionInServerMessage = "This should be the original exception message!" }; Console.WriteLine("Making request"); try { bus.RequestAsync<TestRequestMessage, TestResponseMessage>(request).Wait(1000); } catch (AggregateException e) { throw e.InnerException; } } // First start the EasyNetQ.Tests.SimpleService console app. // Run this test. You should see the SimpleService report that it's // responding and the response should appear here with an exception report. // you should also see a new error message in the error queue. [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_be_able_to_do_simple_request_response_that_throws_on_response_consumer() { var autoResetEvent = new AutoResetEvent(false); var request = new TestRequestMessage { Text = "Hello from the client! " }; Console.WriteLine("Making request"); bus.RequestAsync<TestRequestMessage, TestResponseMessage>(request).ContinueWith(response => { Console.WriteLine("Got response: '{0}'", response.Result.Text); autoResetEvent.Set(); throw new SomeRandomException("Something very bad just happened!"); }); autoResetEvent.WaitOne(1000); } // First start the EasyNetQ.Tests.SimpleService console app. // Run this test. You should see the SimpleService report that it's // responding and the response should appear here. [Test, Explicit("Needs a Rabbit instance on localhost to work")] public void Should_be_able_to_do_simple_request_response_that_takes_a_long_time() { var autoResetEvent = new AutoResetEvent(false); var request = new TestRequestMessage { Text = "Hello from the client! ", CausesServerToTakeALongTimeToRespond = true }; Console.WriteLine("Making request"); bus.RequestAsync<TestRequestMessage, TestResponseMessage>(request).ContinueWith(response => { Console.WriteLine("Got response: '{0}'", response.Result.Text); autoResetEvent.Set(); }); autoResetEvent.WaitOne(10000); } } [Serializable] public class SomeRandomException : Exception { // // For guidelines regarding the creation of new exception types, see // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp // and // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp // public SomeRandomException() {} public SomeRandomException(string message) : base(message) {} public SomeRandomException(string message, Exception inner) : base(message, inner) {} protected SomeRandomException( SerializationInfo info, StreamingContext context) : base(info, context) {} } } // ReSharper restore InconsistentNaming
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Rest.Generator.CSharp.Templates { #line 1 "ExtensionMethodTemplate.cshtml" using System.Text #line default #line hidden ; #line 2 "ExtensionMethodTemplate.cshtml" using Microsoft.Rest.Generator.CSharp #line default #line hidden ; #line 3 "ExtensionMethodTemplate.cshtml" using Microsoft.Rest.Generator.CSharp.Templates #line default #line hidden ; #line 4 "ExtensionMethodTemplate.cshtml" using Microsoft.Rest.Generator.CSharp.TemplateModels #line default #line hidden ; #line 5 "ExtensionMethodTemplate.cshtml" using Microsoft.Rest.Generator.Utilities #line default #line hidden ; using System.Threading.Tasks; public class ExtensionMethodTemplate : Microsoft.Rest.Generator.Template<Microsoft.Rest.Generator.CSharp.MethodTemplateModel> { #line hidden public ExtensionMethodTemplate() { } #pragma warning disable 1998 public override async Task ExecuteAsync() { #line 8 "ExtensionMethodTemplate.cshtml" #line default #line hidden WriteLiteral("/// <summary>\r\n"); #line 10 "ExtensionMethodTemplate.cshtml" Write(WrapComment("/// ", Model.Documentation.EscapeXmlComment())); #line default #line hidden WriteLiteral("\r\n/// </summary>\r\n/// <param name=\'operations\'>\r\n/// The operations group for thi" + "s extension method\r\n/// </param>\r\n"); #line 15 "ExtensionMethodTemplate.cshtml" foreach (var parameter in Model.LocalParameters) { #line default #line hidden WriteLiteral("/// <param name=\'"); #line 17 "ExtensionMethodTemplate.cshtml" Write(parameter.Name); #line default #line hidden WriteLiteral("\'>\r\n"); #line 18 "ExtensionMethodTemplate.cshtml" Write(WrapComment("/// ", parameter.Documentation.EscapeXmlComment())); #line default #line hidden WriteLiteral("\r\n/// </param>\r\n"); #line 20 "ExtensionMethodTemplate.cshtml" } #line default #line hidden WriteLiteral("public static "); #line 21 "ExtensionMethodTemplate.cshtml" Write(Model.ReturnTypeString); #line default #line hidden WriteLiteral(" "); #line 21 "ExtensionMethodTemplate.cshtml" Write(Model.Name); #line default #line hidden WriteLiteral("("); #line 21 "ExtensionMethodTemplate.cshtml" Write(Model.GetExtensionParameters(Model.SyncMethodParameterDeclaration)); #line default #line hidden WriteLiteral(")\r\n{\r\n"); #line 23 "ExtensionMethodTemplate.cshtml" if (Model.ReturnType != null) { #line default #line hidden WriteLiteral(" return Task.Factory.StartNew(s => ((I"); #line 25 "ExtensionMethodTemplate.cshtml" Write(Model.MethodGroupName); #line default #line hidden WriteLiteral(")s)."); #line 25 "ExtensionMethodTemplate.cshtml" Write(Model.Name); #line default #line hidden WriteLiteral("Async("); #line 25 "ExtensionMethodTemplate.cshtml" Write(Model.SyncMethodInvocationArgs); #line default #line hidden WriteLiteral("), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.De" + "fault).Unwrap().GetAwaiter().GetResult();\r\n"); #line 26 "ExtensionMethodTemplate.cshtml" } else { #line default #line hidden WriteLiteral(" Task.Factory.StartNew(s => ((I"); #line 29 "ExtensionMethodTemplate.cshtml" Write(Model.MethodGroupName); #line default #line hidden WriteLiteral(")s)."); #line 29 "ExtensionMethodTemplate.cshtml" Write(Model.Name); #line default #line hidden WriteLiteral("Async("); #line 29 "ExtensionMethodTemplate.cshtml" Write(Model.SyncMethodInvocationArgs); #line default #line hidden WriteLiteral("), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.De" + "fault).Unwrap().GetAwaiter().GetResult();\r\n"); #line 30 "ExtensionMethodTemplate.cshtml" } #line default #line hidden WriteLiteral("}\r\n"); #line 32 "ExtensionMethodTemplate.cshtml" #line default #line hidden #line 32 "ExtensionMethodTemplate.cshtml" Write(EmptyLine); #line default #line hidden #line 32 "ExtensionMethodTemplate.cshtml" #line default #line hidden WriteLiteral("/// <summary>\r\n"); #line 34 "ExtensionMethodTemplate.cshtml" Write(WrapComment("/// ", Model.Documentation.EscapeXmlComment())); #line default #line hidden WriteLiteral("\r\n/// </summary>\r\n/// <param name=\'operations\'>\r\n/// The operations group for thi" + "s extension method\r\n/// </param>\r\n"); #line 39 "ExtensionMethodTemplate.cshtml" foreach (var parameter in Model.LocalParameters) { #line default #line hidden WriteLiteral("/// <param name=\'"); #line 41 "ExtensionMethodTemplate.cshtml" Write(parameter.Name); #line default #line hidden WriteLiteral("\'>\r\n"); #line 42 "ExtensionMethodTemplate.cshtml" Write(WrapComment("/// ", parameter.Documentation.EscapeXmlComment())); #line default #line hidden WriteLiteral("\r\n/// </param>\r\n"); #line 44 "ExtensionMethodTemplate.cshtml" } #line default #line hidden WriteLiteral("/// <param name=\'cancellationToken\'>\r\n/// Cancellation token.\r\n/// </param>\r\npubl" + "ic static async "); #line 48 "ExtensionMethodTemplate.cshtml" Write(Model.TaskExtensionReturnTypeString); #line default #line hidden WriteLiteral(" "); #line 48 "ExtensionMethodTemplate.cshtml" Write(Model.Name); #line default #line hidden WriteLiteral("Async( "); #line 48 "ExtensionMethodTemplate.cshtml" Write(Model.GetExtensionParameters(Model.GetAsyncMethodParameterDeclaration())); #line default #line hidden WriteLiteral(")\r\n{\r\n"); #line 50 "ExtensionMethodTemplate.cshtml" if (Model.ReturnType != null) { #line default #line hidden WriteLiteral(" "); #line 52 "ExtensionMethodTemplate.cshtml" Write(Model.OperationResponseReturnTypeString); #line default #line hidden WriteLiteral(" result = await operations."); #line 52 "ExtensionMethodTemplate.cshtml" Write(Model.Name); #line default #line hidden WriteLiteral("WithHttpMessagesAsync("); #line 52 "ExtensionMethodTemplate.cshtml" Write(Model.GetAsyncMethodInvocationArgs("null")); #line default #line hidden WriteLiteral(").ConfigureAwait(false);\r\n return result.Body;\r\n"); #line 54 "ExtensionMethodTemplate.cshtml" } else { #line default #line hidden WriteLiteral(" await operations."); #line 57 "ExtensionMethodTemplate.cshtml" Write(Model.Name); #line default #line hidden WriteLiteral("WithHttpMessagesAsync("); #line 57 "ExtensionMethodTemplate.cshtml" Write(Model.GetAsyncMethodInvocationArgs("null")); #line default #line hidden WriteLiteral(").ConfigureAwait(false);\r\n"); #line 58 "ExtensionMethodTemplate.cshtml" } #line default #line hidden WriteLiteral("}\r\n\r\n"); #line 61 "ExtensionMethodTemplate.cshtml" #line default #line hidden } #pragma warning restore 1998 } }
using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.IO; namespace T5Suite2 { class msiupdater { private Version m_currentversion; private string m_customer = "Global"; private string m_server = "http://develop.trionictuning.com/T5Suite2/"; private string m_username = ""; private string m_password = ""; private Version m_NewVersion; private string m_apppath = ""; private bool m_fromFileLocation = false; private bool m_blockauto_updates = false; public bool Blockauto_updates { get { return m_blockauto_updates; } set { m_blockauto_updates = value; } } public string Apppath { get { return m_apppath; } set { m_apppath = value; } } public Version NewVersion { get { return m_NewVersion; } set { m_NewVersion = value; } } public delegate void DataPump(MSIUpdaterEventArgs e); public event msiupdater.DataPump onDataPump; public delegate void UpdateProgressChanged(MSIUpdateProgressEventArgs e); public event msiupdater.UpdateProgressChanged onUpdateProgressChanged; public class MSIUpdateProgressEventArgs : System.EventArgs { private Int32 _NoFiles; private Int32 _NoFilesDone; private Int32 _PercentageDone; private Int32 _NoBytes; private Int32 _NoBytesDone; public Int32 NoBytesDone { get { return _NoBytesDone; } } public Int32 NoBytes { get { return _NoBytes; } } public Int32 NoFiles { get { return _NoFiles; } } public Int32 NoFilesDone { get { return _NoFilesDone; } } public Int32 PercentageDone { get { return _PercentageDone; } } public MSIUpdateProgressEventArgs(Int32 NoFiles, Int32 NoFilesDone, Int32 PercentageDone, Int32 NoBytes, Int32 NoBytesDone) { this._NoFiles = NoFiles; this._NoFilesDone = NoFilesDone; this._PercentageDone = PercentageDone; this._NoBytes = NoBytes; this._NoBytesDone = NoBytesDone; } } public class MSIUpdaterEventArgs : System.EventArgs { private string _Data; private bool _UpdateAvailable; private bool _Version2High; private Version _Version; private string _xmlFile; public string XMLFile { get { return _xmlFile; } } public string Data { get { return _Data; } } public bool UpdateAvailable { get { return _UpdateAvailable; } } public bool Version2High { get { return _Version2High; } } public Version Version { get { return _Version; } } public MSIUpdaterEventArgs(string Data, bool Update, bool mVersion2High, Version NewVersion, string xmlfile) { this._Data = Data; this._UpdateAvailable = Update; this._Version2High = mVersion2High; this._Version = NewVersion; this._xmlFile = xmlfile; } } public msiupdater(Version CurrentVersion) { m_currentversion = CurrentVersion; m_NewVersion = new Version("1.0.0.0"); } public void CheckForUpdates(string customer, string server, string username, string password, bool FromFile) { m_server = server; m_customer = customer; m_username = username; m_password = password; m_fromFileLocation = FromFile; if (!m_blockauto_updates) { System.Threading.Thread t = new System.Threading.Thread(updatecheck); t.Start(); } } public void ExecuteUpdate(Version ver) { //http://reverse-that-trionic.googlecode.com/svn/trunk/T5Suite/ string command = "http://develop.trionictuning.com/T5Suite2/" + ver.ToString() + "/T5SuiteII.msi"; try { System.Diagnostics.Process.Start(command); } catch (Exception E) { PumpString("Exception when checking new update(s): " + E.Message, false, false, new Version(), ""); } } private void PumpString(string text, bool updateavailable, bool version2high, Version newver, string xmlfile) { onDataPump(new MSIUpdaterEventArgs(text, updateavailable, version2high, newver, xmlfile)); } private void NotifyProgress(Int32 NoFiles, Int32 NoFilesDone, Int32 PercentageDone, Int32 NoBytes, Int32 NoBytesDone) { onUpdateProgressChanged(new MSIUpdateProgressEventArgs(NoFiles, NoFilesDone, PercentageDone, NoBytes, NoBytesDone)); } public string GetPageHTML(string pageUrl, int timeoutSeconds) { System.Net.WebResponse response = null; try { // Setup our Web request System.Net.WebRequest request = System.Net.WebRequest.Create(pageUrl); try { //request.Proxy = System.Net.WebProxy.GetDefaultProxy(); request.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; } catch (Exception proxyE) { PumpString("Error setting proxy server: " + proxyE.Message, false, false, new Version(), ""); } /* if (UseDefaultProxy) { request.Proxy = System.Net.WebProxy.GetDefaultProxy(); if (UseDefaultCredentials) { request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials; } if (UseDefaultNetworkCredentials) { request.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; } }*/ request.Timeout = timeoutSeconds * 1000; // Retrieve data from request response = request.GetResponse(); System.IO.Stream streamReceive = response.GetResponseStream(); System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("utf-8"); System.IO.StreamReader streamRead = new System.IO.StreamReader(streamReceive, encoding); // return the retrieved HTML return streamRead.ReadToEnd(); } catch (Exception ex) { // Error occured grabbing data, return empty string. PumpString("An error occurred while retrieving the HTML content. " + ex.Message, false, false, new Version(), ""); /*using (StreamWriter logfile = new StreamWriter("update.log", true, System.Text.Encoding.ASCII, 2048)) { logfile.WriteLine("An error occurred while retrieving the HTML content. " + ex.Message); logfile.Close(); }*/ return ""; } finally { // Check if exists, then close the response. if (response != null) { response.Close(); } } } private void ExtractNameValue(string input, out string Name, out string Value) { Name = ""; Value = ""; // input : <Element name="I2l" value="00" /> int id1,id2,id3,id4; id1=input.IndexOf("\"",0,input.Length); if(id1>0) // eerste " gevonden { id2=input.IndexOf("\"",id1+1,input.Length - id1 - 1); if(id2 > 0) // tweede " gevonden { id3=input.IndexOf("\"",id2+1,input.Length - id2 - 1); if(id3>0) { id4=input.IndexOf("\"",id3+1,input.Length - id3 - 1); if(id4>0) { Name = input.Substring(id1+1,id2-id1-1); Value = input.Substring(id3+1,id4-id3-1); // alles gevonden } } } } } private string FileToString(string infile) { StreamReader stream = System.IO.File.OpenText(infile); string returnvalues; returnvalues = stream.ReadToEnd(); stream.Close(); return returnvalues; } private void updatecheck() { string URLString=""; string XMLResult=""; //string VehicleString; bool m_updateavailable = false; bool m_version_toohigh = false; Version maxversion = new Version("1.0.0.0"); File.Delete(Apppath + "\\input.xml"); File.Delete(Apppath + "\\Notes.xml"); try { if (m_customer.Length > 0) { URLString = "http://develop.trionictuning.com/T5Suite2/version.xml"; Console.WriteLine("First try"); XMLResult = GetPageHTML(URLString, 10); if (XMLResult == "") { Console.WriteLine("Second try"); XMLResult = GetPageHTML(URLString, 10); } using (StreamWriter xmlfile = new StreamWriter(Apppath + "\\input.xml", false, System.Text.Encoding.ASCII, 2048)) { xmlfile.Write(XMLResult); xmlfile.Close(); } URLString = "http://develop.trionictuning.com/T5Suite2/Notes.xml"; XMLResult = GetPageHTML(URLString, 10); using (StreamWriter xmlfile = new StreamWriter(Apppath + "\\Notes.xml", false, System.Text.Encoding.ASCII, 2048)) { xmlfile.Write(XMLResult); xmlfile.Close(); } } /*using (StreamWriter logfile = new StreamWriter(Apppath + "\\update.log", true, System.Text.Encoding.ASCII, 2048)) { logfile.WriteLine("Current version: " + m_currentversion); logfile.WriteLine("Customer: " + "Global"); logfile.WriteLine("Server: " + m_server); logfile.WriteLine("URLString: " + URLString); logfile.WriteLine("XMLResult: " + XMLResult); logfile.Close(); }*/ XmlDocument doc; try { doc = new XmlDocument(); doc.LoadXml(FileToString(Apppath + "\\input.xml")); // Add any other properties that would be useful to store //foreach ( System.Xml.XmlNodeList Nodes; Nodes = doc.GetElementsByTagName("t5suite2"); foreach (System.Xml.XmlNode Item in Nodes) { System.Xml.XmlAttributeCollection XMLColl; XMLColl = Item.Attributes; foreach (System.Xml.XmlAttribute myAttr in XMLColl) { if (myAttr.Name == "version") { Version v = new Version(myAttr.Value); if (v > m_currentversion) { if (v > maxversion) maxversion = v; m_updateavailable = true; PumpString("Available version: " + myAttr.Value, false, false, new Version(), Apppath + "\\Notes.xml"); } else if (v.Major < m_currentversion.Major || (v.Major == m_currentversion.Major && v.Minor < m_currentversion.Minor) || (v.Major == m_currentversion.Major && v.Minor == m_currentversion.Minor && v.Build < m_currentversion.Build)) { // mmm .. gebruiker draait een versie die hoger is dan dat is vrijgegeven... if (v > maxversion) maxversion = v; m_updateavailable = false; m_version_toohigh = true; } } } } } catch (Exception E) { PumpString(E.Message, false, false, new Version(), ""); } if (m_updateavailable) { //Console.WriteLine("An update is available: " + maxversion.ToString()); PumpString("A newer version is available: " + maxversion.ToString(), m_updateavailable, m_version_toohigh, maxversion, Apppath + "\\Notes.xml"); m_NewVersion = maxversion; } else if (m_version_toohigh) { PumpString("Versionnumber is too high: " + maxversion.ToString(), m_updateavailable, m_version_toohigh, maxversion, Apppath + "\\Notes.xml"); m_NewVersion = maxversion; } else { PumpString("No new version(s) found...", false, false, new Version(), Apppath + "\\Notes.xml"); } } catch (Exception tuE) { PumpString(tuE.Message, false, false, new Version(), ""); } } public string GetReleaseNotes() { string URLString = "http://develop.trionictuning.com/T5Suite2/Notes.xml"; string XMLResult = GetPageHTML(URLString, 10); using (StreamWriter xmlfile = new StreamWriter(Apppath + "\\Notes.xml", false, System.Text.Encoding.ASCII, 2048)) { xmlfile.Write(XMLResult); xmlfile.Close(); } return Apppath + "\\Notes.xml"; } } }
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry and contributors // 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 FakeItEasy; using FluentAssertions; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Dynamic; using System.IO; using System.Reflection; using System.Text.RegularExpressions; using Xunit; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.ObjectFactories; namespace YamlDotNet.Test.Serialization { public class SerializationTests : SerializationTestHelper { [Fact] public void DeserializeEmptyDocument() { var emptyText = string.Empty; var array = Deserializer.Deserialize<int[]>(UsingReaderFor(emptyText)); array.Should().BeNull(); } [Fact] public void DeserializeScalar() { var stream = Yaml.StreamFrom("02-scalar-in-imp-doc.yaml"); var result = Deserializer.Deserialize(stream); result.Should().Be("a scalar"); } [Fact] public void DeserializeScalarZero() { var result = Deserializer.Deserialize<int>(UsingReaderFor("0")); result.Should().Be(0); } [Fact] public void DeserializeScalarDecimal() { var result = Deserializer.Deserialize<int>(UsingReaderFor("+1_234_567")); result.Should().Be(1234567); } [Fact] public void DeserializeScalarBinaryNumber() { var result = Deserializer.Deserialize<int>(UsingReaderFor("-0b1_0010_1001_0010")); result.Should().Be(-4754); } [Fact] public void DeserializeScalarOctalNumber() { var result = Deserializer.Deserialize<int>(UsingReaderFor("+071_352")); result.Should().Be(29418); } [Fact] public void DeserializeScalarHexNumber() { var result = Deserializer.Deserialize<int>(UsingReaderFor("-0x_0F_B9")); result.Should().Be(-0xFB9); } [Fact] public void DeserializeScalarLongBase60Number() { var result = Deserializer.Deserialize<long>(UsingReaderFor("99_:_58:47:3:6_2:10")); result.Should().Be(77744246530L); } [Fact] public void RoundtripEnums() { var flags = EnumExample.One | EnumExample.Two; var result = DoRoundtripFromObjectTo<EnumExample>(flags); result.Should().Be(flags); } [Fact] public void SerializeCircularReference() { var obj = new CircularReference(); obj.Child1 = new CircularReference { Child1 = obj, Child2 = obj }; Action action = () => RoundtripSerializer.Serialize(new StringWriter(), obj, typeof(CircularReference)); action.ShouldNotThrow(); } [Fact] public void DeserializeCustomTags() { var stream = Yaml.StreamFrom("tags.yaml"); Deserializer.RegisterTagMapping("tag:yaml.org,2002:point", typeof(Point)); var result = Deserializer.Deserialize(stream); result.Should().BeOfType<Point>().And .Subject.As<Point>() .ShouldBeEquivalentTo(new { X = 10, Y = 20 }, o => o.ExcludingMissingMembers()); } [Fact] public void DeserializeExplicitType() { var text = Yaml.StreamFrom("explicit-type.template").TemplatedOn<Simple>(); var result = Deserializer.Deserialize<Simple>(UsingReaderFor(text)); result.aaa.Should().Be("bbb"); } [Fact] public void DeserializeConvertible() { var text = Yaml.StreamFrom("convertible.template").TemplatedOn<Convertible>(); var result = Deserializer.Deserialize<Simple>(UsingReaderFor(text)); result.aaa.Should().Be("[hello, world]"); } [Fact] public void DeserializationOfObjectsHandlesForwardReferences() { var text = Lines( "Nothing: *forward", "MyString: &forward ForwardReference"); var result = Deserializer.Deserialize<Example>(UsingReaderFor(text)); result.ShouldBeEquivalentTo( new { Nothing = "ForwardReference", MyString = "ForwardReference" }, o => o.ExcludingMissingMembers()); } [Fact] public void DeserializationFailsForUndefinedForwardReferences() { var text = Lines( "Nothing: *forward", "MyString: ForwardReference"); Action action = () => Deserializer.Deserialize<Example>(UsingReaderFor(text)); action.ShouldThrow<AnchorNotFoundException>(); } [Fact] public void RoundtripObject() { var obj = new Example(); var result = DoRoundtripFromObjectTo<Example>(obj, RoundtripSerializer); result.ShouldBeEquivalentTo(obj); } [Fact] public void RoundtripObjectWithDefaults() { var obj = new Example(); var result = DoRoundtripFromObjectTo<Example>(obj, RoundtripEmitDefaultsSerializer); result.ShouldBeEquivalentTo(obj); } [Fact] public void RoundtripAnonymousType() { var data = new { Key = 3 }; var result = DoRoundtripFromObjectTo<Dictionary<string, string>>(data); result.Should().Equal(new Dictionary<string, string> { { "Key", "3" } }); } [Fact] public void RoundtripWithYamlTypeConverter() { var obj = new MissingDefaultCtor("Yo"); RoundtripSerializer.RegisterTypeConverter(new MissingDefaultCtorConverter()); Deserializer.RegisterTypeConverter(new MissingDefaultCtorConverter()); var result = DoRoundtripFromObjectTo<MissingDefaultCtor>(obj, RoundtripSerializer, Deserializer); result.Value.Should().Be("Yo"); } [Fact] public void RoundtripAlias() { var writer = new StringWriter(); var input = new NameConvention { AliasTest = "Fourth" }; Serializer.Serialize(writer, input, input.GetType()); var text = writer.ToString(); // Todo: use RegEx once FluentAssertions 2.2 is released text.TrimEnd('\r', '\n').Should().Be("fourthTest: Fourth"); var output = Deserializer.Deserialize<NameConvention>(UsingReaderFor(text)); output.AliasTest.Should().Be(input.AliasTest); } [Fact] // Todo: is the assert on the string necessary? public void RoundtripDerivedClass() { var obj = new InheritanceExample { SomeScalar = "Hello", RegularBase = new Derived { BaseProperty = "foo", DerivedProperty = "bar" }, }; var result = DoRoundtripFromObjectTo<InheritanceExample>(obj, RoundtripSerializer); result.SomeScalar.Should().Be("Hello"); result.RegularBase.Should().BeOfType<Derived>().And .Subject.As<Derived>().ShouldBeEquivalentTo(new { ChildProp = "bar" }, o => o.ExcludingMissingMembers()); } [Fact] public void RoundtripDerivedClassWithSerializeAs() { var obj = new InheritanceExample { SomeScalar = "Hello", BaseWithSerializeAs = new Derived { BaseProperty = "foo", DerivedProperty = "bar" }, }; var result = DoRoundtripFromObjectTo<InheritanceExample>(obj, RoundtripSerializer); result.BaseWithSerializeAs.Should().BeOfType<Base>().And .Subject.As<Base>().ShouldBeEquivalentTo(new { ParentProp = "foo" }, o => o.ExcludingMissingMembers()); } [Fact] public void RoundtripInterfaceProperties() { AssumingDeserializerWith(new LambdaObjectFactory(t => { if (t == typeof(InterfaceExample)) { return new InterfaceExample(); } else if (t == typeof(IDerived)) { return new Derived(); } return null; })); var obj = new InterfaceExample { Derived = new Derived { BaseProperty = "foo", DerivedProperty = "bar" } }; var result = DoRoundtripFromObjectTo<InterfaceExample>(obj); result.Derived.Should().BeOfType<Derived>().And .Subject.As<IDerived>().ShouldBeEquivalentTo(new { BaseProperty = "foo", DerivedProperty = "bar" }, o => o.ExcludingMissingMembers()); } [Fact] public void DeserializeGuid() { var stream = Yaml.StreamFrom("guid.yaml"); var result = Deserializer.Deserialize<Guid>(stream); result.Should().Be(new Guid("9462790d5c44468985425e2dd38ebd98")); } [Fact] public void DeserializationOfOrderedProperties() { TextReader stream = Yaml.StreamFrom("ordered-properties.yaml"); var orderExample = Deserializer.Deserialize<OrderExample>(stream); orderExample.Order1.Should().Be("Order1 value"); orderExample.Order2.Should().Be("Order2 value"); } [Fact] public void DeserializeEnumerable() { var obj = new[] { new Simple { aaa = "bbb" } }; var result = DoRoundtripFromObjectTo<IEnumerable<Simple>>(obj); result.Should().ContainSingle(item => "bbb".Equals(item.aaa)); } [Fact] public void DeserializeArray() { var stream = Yaml.StreamFrom("list.yaml"); var result = Deserializer.Deserialize<String[]>(stream); result.Should().Equal(new[] { "one", "two", "three" }); } [Fact] public void DeserializeList() { var stream = Yaml.StreamFrom("list.yaml"); var result = Deserializer.Deserialize(stream); result.Should().BeAssignableTo<IList>().And .Subject.As<IList>().Should().Equal(new[] { "one", "two", "three" }); } [Fact] public void DeserializeExplicitList() { var stream = Yaml.StreamFrom("list-explicit.yaml"); var result = Deserializer.Deserialize(stream); result.Should().BeAssignableTo<IList<int>>().And .Subject.As<IList<int>>().Should().Equal(3, 4, 5); } [Fact] public void DeserializationOfGenericListsHandlesForwardReferences() { var text = Lines( "- *forward", "- &forward ForwardReference"); var result = Deserializer.Deserialize<string[]>(UsingReaderFor(text)); result.Should().Equal(new[] { "ForwardReference", "ForwardReference" }); } [Fact] public void DeserializationOfNonGenericListsHandlesForwardReferences() { var text = Lines( "- *forward", "- &forward ForwardReference"); var result = Deserializer.Deserialize<ArrayList>(UsingReaderFor(text)); result.Should().Equal(new[] { "ForwardReference", "ForwardReference" }); } [Fact] public void RoundtripList() { var obj = new List<int> { 2, 4, 6 }; var result = DoRoundtripOn<List<int>>(obj, RoundtripSerializer); result.Should().Equal(obj); } [Fact] public void RoundtripArrayWithTypeConversion() { var obj = new object[] { 1, 2, "3" }; var result = DoRoundtripFromObjectTo<int[]>(obj); result.Should().Equal(1, 2, 3); } [Fact] public void RoundtripArrayOfIdenticalObjects() { var z = new Simple { aaa = "bbb" }; var obj = new[] { z, z, z }; var result = DoRoundtripOn<Simple[]>(obj); result.Should().HaveCount(3).And.OnlyContain(x => z.aaa.Equals(x.aaa)); result[0].Should().BeSameAs(result[1]).And.BeSameAs(result[2]); } [Fact] public void DeserializeDictionary() { var stream = Yaml.StreamFrom("dictionary.yaml"); var result = Deserializer.Deserialize(stream); result.Should().BeAssignableTo<IDictionary<object, object>>().And.Subject .As<IDictionary<object, object>>().Should().Equal(new Dictionary<object, object> { { "key1", "value1" }, { "key2", "value2" } }); } [Fact] public void DeserializeExplicitDictionary() { var stream = Yaml.StreamFrom("dictionary-explicit.yaml"); var result = Deserializer.Deserialize(stream); result.Should().BeAssignableTo<IDictionary<string, int>>().And.Subject .As<IDictionary<string, int>>().Should().Equal(new Dictionary<string, int> { { "key1", 1 }, { "key2", 2 } }); } [Fact] public void RoundtripDictionary() { var obj = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" }, { "key3", "value3" }, }; var result = DoRoundtripFromObjectTo<Dictionary<string, string>>(obj); result.Should().Equal(obj); } [Fact] public void DeserializationOfGenericDictionariesHandlesForwardReferences() { var text = Lines( "key1: *forward", "*forwardKey: ForwardKeyValue", "*forward: *forward", "key2: &forward ForwardReference", "key3: &forwardKey key4"); var result = Deserializer.Deserialize<Dictionary<string, string>>(UsingReaderFor(text)); result.Should().Equal(new Dictionary<string, string> { { "ForwardReference", "ForwardReference" }, { "key1", "ForwardReference" }, { "key2", "ForwardReference" }, { "key4", "ForwardKeyValue" }, { "key3", "key4" } }); } [Fact] public void DeserializationOfNonGenericDictionariesHandlesForwardReferences() { var text = Lines( "key1: *forward", "*forwardKey: ForwardKeyValue", "*forward: *forward", "key2: &forward ForwardReference", "key3: &forwardKey key4"); var result = Deserializer.Deserialize<Hashtable>(UsingReaderFor(text)); result.Should().BeEquivalentTo( Entry("ForwardReference", "ForwardReference"), Entry("key1", "ForwardReference"), Entry("key2", "ForwardReference"), Entry("key4", "ForwardKeyValue"), Entry("key3", "key4")); } [Fact] public void DeserializeListOfDictionaries() { var stream = Yaml.StreamFrom("list-of-dictionaries.yaml"); var result = Deserializer.Deserialize<List<Dictionary<string, string>>>(stream); result.ShouldBeEquivalentTo(new[] { new Dictionary<string, string> { { "connection", "conn1" }, { "path", "path1" } }, new Dictionary<string, string> { { "connection", "conn2" }, { "path", "path2" } }}, opt => opt.WithStrictOrderingFor(root => root)); } [Fact] public void DeserializeTwoDocuments() { var reader = EventReaderFor(Lines( "---", "aaa: 111", "---", "aaa: 222", "...")); reader.Expect<StreamStart>(); var one = Deserializer.Deserialize<Simple>(reader); var two = Deserializer.Deserialize<Simple>(reader); one.ShouldBeEquivalentTo(new { aaa = "111" }); two.ShouldBeEquivalentTo(new { aaa = "222" }); } [Fact] public void DeserializeThreeDocuments() { var reader = EventReaderFor(Lines( "---", "aaa: 111", "---", "aaa: 222", "---", "aaa: 333", "...")); reader.Expect<StreamStart>(); var one = Deserializer.Deserialize<Simple>(reader); var two = Deserializer.Deserialize<Simple>(reader); var three = Deserializer.Deserialize<Simple>(reader); reader.Accept<StreamEnd>().Should().BeTrue("reader should have reached StreamEnd"); one.ShouldBeEquivalentTo(new { aaa = "111" }); two.ShouldBeEquivalentTo(new { aaa = "222" }); three.ShouldBeEquivalentTo(new { aaa = "333" }); } [Fact] public void SerializeGuid() { var guid = new Guid("{9462790D-5C44-4689-8542-5E2DD38EBD98}"); var writer = new StringWriter(); Serializer.Serialize(writer, guid); var serialized = writer.ToString(); Dump.WriteLine(writer.ToString()); Regex.IsMatch(serialized, "^" + guid.ToString("D")).Should().BeTrue("serialized content should contain the guid, but instead contained: " + serialized); } [Fact] public void SerializationOfNullInListsAreAlwaysEmittedWithoutUsingEmitDefaults() { var writer = new StringWriter(); var obj = new[] { "foo", null, "bar" }; Serializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); Regex.Matches(serialized, "-").Count.Should().Be(3, "there should have been 3 elements"); } [Fact] public void SerializationOfNullInListsAreAlwaysEmittedWhenUsingEmitDefaults() { var writer = new StringWriter(); var obj = new[] { "foo", null, "bar" }; EmitDefaultsSerializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); Regex.Matches(serialized, "-").Count.Should().Be(3, "there should have been 3 elements"); } [Fact] public void SerializationIncludesKeyWhenEmittingDefaults() { var writer = new StringWriter(); var obj = new Example { MyString = null }; EmitDefaultsSerializer.Serialize(writer, obj, typeof(Example)); Dump.WriteLine(writer); writer.ToString().Should().Contain("MyString"); } [Fact] [Trait("Motive", "Bug fix")] public void SerializationIncludesKeyFromAnonymousTypeWhenEmittingDefaults() { var writer = new StringWriter(); var obj = new { MyString = (string)null }; EmitDefaultsSerializer.Serialize(writer, obj, obj.GetType()); Dump.WriteLine(writer); writer.ToString().Should().Contain("MyString"); } [Fact] public void SerializationDoesNotIncludeKeyWhenDisregardingDefaults() { var writer = new StringWriter(); var obj = new Example { MyString = null }; Serializer.Serialize(writer, obj, typeof(Example)); Dump.WriteLine(writer); writer.ToString().Should().NotContain("MyString"); } [Fact] public void SerializationOfDefaultsWorkInJson() { var writer = new StringWriter(); var obj = new Example { MyString = null }; EmitDefaultsJsonCompatibleSerializer.Serialize(writer, obj, typeof(Example)); Dump.WriteLine(writer); writer.ToString().Should().Contain("MyString"); } [Fact] // Todo: this is actualy roundtrip public void DeserializationOfDefaultsWorkInJson() { var writer = new StringWriter(); var obj = new Example { MyString = null }; RoundtripEmitDefaultsJsonCompatibleSerializer.Serialize(writer, obj, typeof(Example)); Dump.WriteLine(writer); var result = Deserializer.Deserialize<Example>(UsingReaderFor(writer)); result.MyString.Should().BeNull(); } [Fact] public void SerializationOfOrderedProperties() { var obj = new OrderExample(); var writer = new StringWriter(); Serializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); serialized.Should() .Be("Order1: Order1 value\r\nOrder2: Order2 value\r\n", "the properties should be in the right order"); } [Fact] public void SerializationRespectsYamlIgnoreAttribute() { var writer = new StringWriter(); var obj = new IgnoreExample(); Serializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); serialized.Should().NotContain("IgnoreMe"); } [Fact] public void SerializationRespectsScalarStyle() { var writer = new StringWriter(); var obj = new ScalarStyleExample(); Serializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); serialized.Should() .Be("LiteralString: |-\r\n Test\r\nDoubleQuotedString: \"Test\"\r\n", "the properties should be specifically styled"); } [Fact] public void SerializationSkipsPropertyWhenUsingDefaultValueAttribute() { var writer = new StringWriter(); var obj = new DefaultsExample { Value = DefaultsExample.DefaultValue }; Serializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); serialized.Should().NotContain("Value"); } [Fact] public void SerializationEmitsPropertyWhenUsingEmitDefaultsAndDefaultValueAttribute() { var writer = new StringWriter(); var obj = new DefaultsExample { Value = DefaultsExample.DefaultValue }; EmitDefaultsSerializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); serialized.Should().Contain("Value"); } [Fact] public void SerializationEmitsPropertyWhenValueDifferFromDefaultValueAttribute() { var writer = new StringWriter(); var obj = new DefaultsExample { Value = "non-default" }; Serializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); serialized.Should().Contain("Value"); } [Fact] public void SerializingAGenericDictionaryShouldNotThrowTargetException() { var obj = new CustomGenericDictionary { { "hello", "world" }, }; Action action = () => Serializer.Serialize(new StringWriter(), obj); action.ShouldNotThrow<TargetException>(); } [Fact] public void SerializaionUtilizeNamingConventions() { var convention = A.Fake<INamingConvention>(); A.CallTo(() => convention.Apply(A<string>._)).ReturnsLazily((string x) => x); var obj = new NameConvention { FirstTest = "1", SecondTest = "2" }; var serializer = new Serializer(namingConvention: convention); serializer.Serialize(new StringWriter(), obj); A.CallTo(() => convention.Apply("FirstTest")).MustHaveHappened(); A.CallTo(() => convention.Apply("SecondTest")).MustHaveHappened(); } [Fact] public void DeserializationUtilizeNamingConventions() { var convention = A.Fake<INamingConvention>(); A.CallTo(() => convention.Apply(A<string>._)).ReturnsLazily((string x) => x); var text = Lines( "FirstTest: 1", "SecondTest: 2"); var deserializer = new Deserializer(namingConvention: convention); deserializer.Deserialize<NameConvention>(UsingReaderFor(text)); A.CallTo(() => convention.Apply("FirstTest")).MustHaveHappened(); A.CallTo(() => convention.Apply("SecondTest")).MustHaveHappened(); } [Fact] public void TypeConverterIsUsedOnListItems() { var text = Lines( "- !<!{type}>", " Left: hello", " Right: world") .TemplatedOn<Convertible>(); var list = Deserializer.Deserialize<List<string>>(UsingReaderFor(text)); list .Should().NotBeNull() .And.ContainSingle(c => c.Equals("[hello, world]")); } [Fact] public void BackreferencesAreMergedWithMappings() { var stream = Yaml.StreamFrom("backreference.yaml"); var parser = new MergingParser(new Parser(stream)); var result = Deserializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(new EventReader(parser)); var alias = result["alias"]; alias.Should() .Contain("key1", "value1", "key1 should be inherited from the backreferenced mapping") .And.Contain("key2", "Overriding key2", "key2 should be overriden by the actual mapping") .And.Contain("key3", "value3", "key3 is defined in the actual mapping"); } [Fact] public void MergingDoesNotProduceDuplicateAnchors() { var parser = new MergingParser(Yaml.ParserForText(@" anchor: &default key1: &myValue value1 key2: value2 alias: <<: *default key2: Overriding key2 key3: value3 useMyValue: key: *myValue ")); var result = Deserializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(new EventReader(parser)); var alias = result["alias"]; alias.Should() .Contain("key1", "value1", "key1 should be inherited from the backreferenced mapping") .And.Contain("key2", "Overriding key2", "key2 should be overriden by the actual mapping") .And.Contain("key3", "value3", "key3 is defined in the actual mapping"); result["useMyValue"].Should() .Contain("key", "value1", "key should be copied"); } [Fact] public void ExampleFromSpecificationIsHandledCorrectly() { var parser = new MergingParser(Yaml.ParserForText(@" obj: - &CENTER { x: 1, y: 2 } - &LEFT { x: 0, y: 2 } - &BIG { r: 10 } - &SMALL { r: 1 } # All the following maps are equal: results: - # Explicit keys x: 1 y: 2 r: 10 label: center/big - # Merge one map << : *CENTER r: 10 label: center/big - # Merge multiple maps << : [ *CENTER, *BIG ] label: center/big - # Override #<< : [ *BIG, *LEFT, *SMALL ] # This does not work because, in the current implementation, # later keys override former keys. This could be fixed, but that # is not trivial because the deserializer allows aliases to refer to # an anchor that is defined later in the document, and the way it is # implemented, the value is assigned later when the anchored value is # deserialized. << : [ *SMALL, *LEFT, *BIG ] x: 1 label: center/big ")); var result = Deserializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(new EventReader(parser)); int index = 0; foreach (var mapping in result["results"]) { mapping.Should() .Contain("x", "1", "'x' should be '1' in result #{0}", index) .And.Contain("y", "2", "'y' should be '2' in result #{0}", index) .And.Contain("r", "10", "'r' should be '10' in result #{0}", index) .And.Contain("label", "center/big", "'label' should be 'center/big' in result #{0}", index); ++index; } } [Fact] public void IgnoreExtraPropertiesIfWanted() { var text = Lines("aaa: hello", "bbb: world"); var des = new Deserializer(ignoreUnmatched: true); var actual = des.Deserialize<Simple>(UsingReaderFor(text)); actual.aaa.Should().Be("hello"); } [Fact] public void DontIgnoreExtraPropertiesIfWanted() { var text = Lines("aaa: hello", "bbb: world"); var des = new Deserializer(ignoreUnmatched: false); var actual = Record.Exception(() => des.Deserialize<Simple>(UsingReaderFor(text))); Assert.IsType<YamlException>(actual); } [Fact] public void IgnoreExtraPropertiesIfWantedBefore() { var text = Lines("bbb: [200,100]", "aaa: hello"); var des = new Deserializer(ignoreUnmatched: true); var actual = des.Deserialize<Simple>(UsingReaderFor(text)); actual.aaa.Should().Be("hello"); } [Fact] public void IgnoreExtraPropertiesIfWantedNamingScheme() { var text = Lines( "scratch: 'scratcher'", "deleteScratch: false", "notScratch: 9443", "notScratch: 192.168.1.30", "mappedScratch:", "- '/work/'" ); var des = new Deserializer(namingConvention: new CamelCaseNamingConvention(), ignoreUnmatched: true); var actual = des.Deserialize<SimpleScratch>(UsingReaderFor(text)); actual.Scratch.Should().Be("scratcher"); actual.DeleteScratch.Should().Be(false); actual.MappedScratch.Should().ContainInOrder(new[] { "/work/" }); } [Fact] public void InvalidTypeConversionsProduceProperExceptions() { var text = Lines("- 1", "- two", "- 3"); var sut = new Deserializer(); var exception = Assert.Throws<YamlException>(() => sut.Deserialize<List<int>>(UsingReaderFor(text))); Assert.Equal(2, exception.Start.Line); Assert.Equal(3, exception.Start.Column); } [Fact] public void SerializeDynamicPropertyAndApplyNamingConvention() { dynamic obj = new ExpandoObject(); obj.property_one = new ExpandoObject(); ((IDictionary<string, object>)obj.property_one).Add("new_key_here", "new_value"); var mockNamingConvention = A.Fake<INamingConvention>(); A.CallTo(() => mockNamingConvention.Apply(A<string>.Ignored)).Returns("xxx"); var serializer = new Serializer(namingConvention: mockNamingConvention); var writer = new StringWriter(); serializer.Serialize(writer, obj); writer.ToString().Should().Contain("xxx: new_value"); } [Fact] public void SerializeGenericDictionaryPropertyAndDoNotApplyNamingConvention() { var obj = new Dictionary<string, object>(); obj["property_one"] = new GenericTestDictionary<string, object>(); ((IDictionary<string, object>)obj["property_one"]).Add("new_key_here", "new_value"); var mockNamingConvention = A.Fake<INamingConvention>(); A.CallTo(() => mockNamingConvention.Apply(A<string>.Ignored)).Returns("xxx"); var serializer = new Serializer(namingConvention: mockNamingConvention); var writer = new StringWriter(); serializer.Serialize(writer, obj); writer.ToString().Should().Contain("new_key_here: new_value"); } [Fact] public void SpecialFloatsAreDeserializedCorrectly() { var deserializer = new Deserializer(); var doubles = deserializer.Deserialize<List<double>>(Yaml.ReaderForText(@" - .nan - .inf - -.inf - 2.3e4 - 1 ")); Assert.Equal(new double[] { double.NaN, double.PositiveInfinity, double.NegativeInfinity, 23000, 1.0 }, doubles); } [Fact] public void SpecialDoublesAreSerializedAndDeserializedCorrectly() { var expected = new double[] { double.MaxValue, double.MinValue }; var serializer = new Serializer(); var buffer = new StringWriter(); serializer.Serialize(buffer, expected); var text = buffer.ToString(); var deserializer = new Deserializer(); var value = deserializer.Deserialize<double[]>(new StringReader(text)); Assert.Equal(expected, value); } [Fact] public void SpecialFloatsAreSerializedAndDeserializedCorrectly() { var expected = new float[] { float.MaxValue, float.MinValue }; var serializer = new Serializer(); var buffer = new StringWriter(); serializer.Serialize(buffer, expected); var text = buffer.ToString(); var deserializer = new Deserializer(); var value = deserializer.Deserialize<float[]>(new StringReader(text)); Assert.Equal(expected, value); } [Fact] public void NegativeIntegersCanBeDeserialized() { var deserializer = new Deserializer(); var value = deserializer.Deserialize<int>(Yaml.ReaderForText(@" '-123' ")); Assert.Equal(-123, value); } [Fact] public void GenericDictionaryThatDoesNotImplementIDictionaryCanBeDeserialized() { var sut = new Deserializer(); var deserialized = sut.Deserialize<GenericTestDictionary<string, string>>(Yaml.ReaderForText(@" a: 1 b: 2 ")); Assert.Equal("1", deserialized["a"]); Assert.Equal("2", deserialized["b"]); } [Fact] public void GenericListThatDoesNotImplementIListCanBeDeserialized() { var sut = new Deserializer(); var deserialized = sut.Deserialize<GenericTestList<string>>(Yaml.ReaderForText(@" - a - b ")); Assert.Contains("a", deserialized); Assert.Contains("b", deserialized); } [Fact] public void GuidsShouldBeQuotedWhenSerializedAsJson() { var sut = new Serializer(SerializationOptions.JsonCompatible | SerializationOptions.EmitDefaults); var yamlAsJson = new StringWriter(); sut.Serialize(yamlAsJson, new { id = Guid.Empty }); Assert.Contains("\"00000000-0000-0000-0000-000000000000\"", yamlAsJson.ToString()); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using DotSpatial.Data; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// RasterSymbolizer. /// </summary> [Serializable] public class RasterSymbolizer : LegendItem, IRasterSymbolizer { #region Fields private bool _colorSchemeHasChanged; private bool _colorSchemeHasUpdated; private bool _drapeVectorLayers; private float _elevationFactor; private float _extrusion; private float[][] _hillshade; private IFeatureSymbolizerOld _imageOutline; private bool _isElevation; private bool _isSmoothed; private bool _isVisible = true; private bool _meshHasChanged; private Color _noDataColor; private IRasterLayer _parentLayer; private IRaster _raster; private IColorScheme _scheme; private IShadedRelief _shadedRelief; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="RasterSymbolizer"/> class. /// </summary> /// <param name="layer">The parent item.</param> public RasterSymbolizer(IRasterLayer layer) { SetParentItem(layer); _parentLayer = layer; _raster = layer.DataSet; Configure(); } /// <summary> /// Initializes a new instance of the <see cref="RasterSymbolizer"/> class. /// </summary> public RasterSymbolizer() { Configure(); } #endregion #region Events /// <summary> /// Occurs if any of the properties that would contribute to bitmap construction have changed /// </summary> public event EventHandler ColorSchemeChanged; /// <summary> /// This event occurs after a new bitmap has been created to act as a texture. /// </summary> public event EventHandler ColorSchemeUpdated; /// <summary> /// Occurs when the symbology has been changed /// </summary> public event EventHandler SymbologyChanged; #endregion #region Properties /// <summary> /// Gets or sets a value indicating whether the color has changed. /// </summary> public bool ColorSchemeHasChanged { get { return _colorSchemeHasChanged; } set { _colorSchemeHasChanged = value; } } /// <summary> /// Gets or sets a value indicating whether the texture needs to be reloaded from a file. /// </summary> public bool ColorSchemeHasUpdated { get { return _colorSchemeHasUpdated; } set { _colorSchemeHasUpdated = value; if (_colorSchemeHasUpdated) { ColorSchemeHasChanged = true; } } } /// <summary> /// Gets or sets a value indicating whether the vector layers are drawn onto the texture, whenever a texture is created. /// </summary> public bool DrapeVectorLayers { get { return _drapeVectorLayers; } set { _drapeVectorLayers = value; OnColorSchemeChanged(); } } /// <summary> /// Gets or sets the editor settings class to help setup up the symbology controls appropriately. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Serialize("EditorSettings")] public RasterEditorSettings EditorSettings { get { return _scheme.EditorSettings; } set { _scheme.EditorSettings = value; } } /// <summary> /// Gets or sets the elevation factor. This is kept separate from extrusion to reduce confusion. /// This is a conversion factor that will convert the units of elevation into the same units that /// the latitude and longitude are stored in. To convert feet to decimal degrees is around a factor /// of .00000274. This is used only in the 3D-context and does not affect ShadedRelief. /// </summary> [Category("Behavior")] [Description("Gets or sets the factor required to change elevation into the same horizontal and vertical units.")] [Serialize("Elevation Factor")] public virtual float ElevationFactor { get { return _elevationFactor; } set { _elevationFactor = value; _meshHasChanged = true; } } /// <summary> /// Gets or sets a float value expression that modifies the "height" of the apparent shaded relief. A value /// of 1 should show the mountains at their true elevations, presuming the ElevationFactor is /// correct. A value of 0 would be totally flat, while 2 would be twice the value. This controls /// the 3D effects and has nothing to do with the creation of shaded releif on the texture. /// </summary> [Category("Behavior")] [Description("Gets or sets the exageration of the natural elevation values.")] [Serialize("Extrusion")] public virtual float Extrusion { get { return _extrusion; } set { _extrusion = value; _meshHasChanged = true; } } /// <summary> /// Gets or sets the calculated hillshade map. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public float[][] HillShade { get { if (_shadedRelief.IsUsed == false) return null; if (ShadedRelief.HasChanged || _hillshade == null) { _hillshade = Raster.CreateHillShade(ShadedRelief); } return _hillshade; } set { _hillshade = value; } } /// <summary> /// Gets or sets the symbol characteristics for the border of this raster. /// </summary> [Category("Symbology")] [TypeConverter(typeof(FeatureSymbolizerOld))] [Description("Gets or sets the characteristics that control the features of the border around this raster.")] [Serialize("ImageOutline")] public virtual IFeatureSymbolizerOld ImageOutline { get { return _imageOutline; } set { _imageOutline = value; OnSymbologyChange(); } } /// <summary> /// Gets or sets a value indicating whether to treat the values as if they are elevation /// in the 3-D context. If this is true, then it will automatically use this grid for /// calculating elevation values. This does not affect ShadedRelief texture creation. /// </summary> [Category("Behavior")] [Description("Gets or sets whether this raster is an elevation raster and should use itself as the source for elevations.")] [Serialize("IsElevation")] public virtual bool IsElevation { get { return _isElevation; } set { _isElevation = value; _meshHasChanged = true; } } /// <summary> /// Gets or sets a value indicating whether or not this raster should be anti-alliased. /// </summary> [Serialize("IsSmoothed")] public virtual bool IsSmoothed { get { return _isSmoothed; } set { _isSmoothed = value; } } /// <summary> /// Gets or sets a value indicating whether or not this raster should render itself. /// </summary> [Category("Behavior")] [Description("Gets or sets whether this raster should render itself")] [Serialize("IsVisible")] public virtual bool IsVisible { get { return _isVisible; } set { _isVisible = value; } } /// <summary> /// Gets or sets a value indicating whether the elevation values have changed. /// </summary> public bool MeshHasChanged { get { return _meshHasChanged; } set { _meshHasChanged = value; } } /// <summary> /// Gets or sets the color to use if the value of the cell corresponds to a No-Data value. /// </summary> [Category("Symbology")] [Description("Gets or sets the color to use if the value of the cell corresponds to a No-Data value.")] [Serialize("NoDataColor")] public Color NoDataColor { get { return _noDataColor; } set { _noDataColor = value; OnColorSchemeChanged(); } } /// <summary> /// Gets or sets a float value from 0 to 1, where 1 is fully opaque while 0 is fully transparent. /// </summary> public float Opacity { get { return _scheme?.Opacity ?? 1; } set { if (_scheme == null) return; _scheme.Opacity = value; } } /// <summary> /// Gets or sets the parent layer. This is not always used, but can be useful for symbolic editing /// that may require a bitmap to be drawn with draped vector layers. /// </summary> [ShallowCopy] public IRasterLayer ParentLayer { get { return _parentLayer; } set { _parentLayer = value; } } /// <summary> /// Gets or sets the raster that should provide elevation values, but only if "IsElevation" is false. /// </summary> [ReadOnly(true)] [DisplayName(@"Elevation Raster")] [Description("The raster object to use as an Elevation Grid")] [ShallowCopy] public virtual IRaster Raster { get { return _raster; } set { _raster = value; } } /// <summary> /// Gets or sets the raster coloring scheme. /// </summary> [Serialize("Scheme")] public IColorScheme Scheme { get { return _scheme; } set { _scheme?.SetParentItem(null); _scheme = value; _scheme?.SetParentItem(_parentLayer); } } /// <summary> /// Gets or sets the characteristics of the shaded relief. This is specifically used /// to control HillShade characteristics of the BitMap texture creation. /// </summary> [Category("Symbology")] [Description("Gets or sets the set of characteristics that control the HillShade characteristics for the visual texture.")] [Serialize("ShadedRelief")] public virtual IShadedRelief ShadedRelief { get { return _shadedRelief; } set { _shadedRelief = value; // still not sure what kind of update to use here, if any } } #endregion #region Methods /// <summary> /// Creates a bmp from the in-memory portion of the raster. This will be stored as a /// fileName with the same name as the current raster, but ends in bmp. /// </summary> /// <returns>The created bmp.</returns> public Bitmap CreateBitmap() { string fileName = Path.ChangeExtension(_raster.Filename, ".bmp"); Bitmap bmp = new Bitmap(_raster.NumRows, _raster.NumColumns, PixelFormat.Format32bppArgb); bmp.Save(fileName); // this is needed so that lockbits doesn't cause exceptions _raster.DrawToBitmap(this, bmp); bmp.Save(fileName); return bmp; } /// <summary> /// Causes the raster to calculate a hillshade based on this symbolizer. /// </summary> public void CreateHillShade() { _hillshade = Raster.CreateHillShade(_shadedRelief); } /// <summary> /// Causes the raster to calculate a hillshade using the specified progress handler. /// </summary> /// <param name="progressHandler">The progress handler to use.</param> public void CreateHillShade(IProgressHandler progressHandler) { _hillshade = Raster.CreateHillShade(_shadedRelief, progressHandler); } /// <summary> /// Gets the color information for a specific value. This does not include any hillshade information. /// </summary> /// <param name="value">Specifies the value to obtain a color for.</param> /// <returns>A Color.</returns> public virtual Color GetColor(double value) { if (value == Raster.NoDataValue) return NoDataColor; foreach (var cb in _scheme.Categories) { if (cb.Contains(value)) { return cb.CalculateColor(value); } } return Color.Transparent; } /// <summary> /// Creates a bitmap based on the specified RasterSymbolizer. /// </summary> /// <param name="bitmap"> the bitmap to paint to.</param> /// <param name="progressHandler">The progress handler.</param> public void PaintShadingToBitmap(Bitmap bitmap, IProgressHandler progressHandler) { BitmapData bmpData; if (_hillshade == null) { return; } // Create a new Bitmap and use LockBits combined with Marshal.Copy to get an array of bytes to work with. Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); try { bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); } catch (ArgumentException ex) { if (ex.ParamName == "format") { throw new BitmapFormatException(); } throw; } int numBytes = bmpData.Stride * bmpData.Height; byte[] rgbData = new byte[numBytes]; Marshal.Copy(bmpData.Scan0, rgbData, 0, numBytes); float[][] hillshade = _hillshade; ProgressMeter pm = new ProgressMeter(progressHandler, SymbologyMessageStrings.DesktopRasterExt_PaintingHillshade, bitmap.Height); if (bitmap.Width * bitmap.Height < 100000) pm.StepPercent = 50; if (bitmap.Width * bitmap.Height < 500000) pm.StepPercent = 10; if (bitmap.Width * bitmap.Height < 1000000) pm.StepPercent = 5; for (int row = 0; row < bitmap.Height; row++) { for (int col = 0; col < bitmap.Width; col++) { int offset = (row * bmpData.Stride) + (col * 4); byte b = rgbData[offset]; byte g = rgbData[offset + 1]; byte r = rgbData[offset + 2]; // rgbData[offset + 3] = a; don't worry about alpha int red = Convert.ToInt32(r * hillshade[row][col]); int green = Convert.ToInt32(g * hillshade[row][col]); int blue = Convert.ToInt32(b * hillshade[row][col]); if (red > 255) red = 255; if (green > 255) green = 255; if (blue > 255) blue = 255; if (red < 0) red = 0; if (green < 0) green = 0; if (blue < 0) blue = 0; b = (byte)blue; r = (byte)red; g = (byte)green; rgbData[offset] = b; rgbData[offset + 1] = g; rgbData[offset + 2] = r; } pm.CurrentValue = row; } pm.Reset(); // Copy the values back into the bitmap Marshal.Copy(rgbData, 0, bmpData.Scan0, numBytes); bitmap.UnlockBits(bmpData); } /// <summary> /// Sends a symbology updated event, which should cause the layer to be refreshed. /// </summary> public void Refresh() { OnColorSchemeChanged(); _meshHasChanged = true; } /// <summary> /// Indicates that the bitmap has been updated and that the colorscheme is currently /// synchronized with the characteristics of this symbolizer. This also fires the /// ColorSchemeChanged event. /// </summary> public void Validate() { _colorSchemeHasUpdated = false; OnColorSchemeChanged(); } /// <summary> /// Fires the on color scheme changed event. /// </summary> protected virtual void OnColorSchemeChanged() { _colorSchemeHasChanged = true; ColorSchemeChanged?.Invoke(this, EventArgs.Empty); } /// <summary> /// Fires the SymbologyUpdated event, which should happen after symbology choices are finalized, /// a new texture has been created and we are ready for an update. /// </summary> protected virtual void OnColorSchemeUpdated() { ColorSchemeHasChanged = false; _colorSchemeHasUpdated = true; ColorSchemeUpdated?.Invoke(this, EventArgs.Empty); } /// <summary> /// Fires the SymbologyChanged event. /// </summary> protected virtual void OnSymbologyChange() { SymbologyChanged?.Invoke(this, EventArgs.Empty); } /// <summary> /// Adds a category with the given values to the Scheme. /// </summary> /// <param name="startValue">First value, that belongs to this category.</param> /// <param name="endValue">Last value, that belongs to this category.</param> /// <param name="color">Color of this category.</param> private void AddCategory(double startValue, double endValue, Color color) { ICategory newCat = new ColorCategory(startValue, endValue, color, color); newCat.Range.MaxIsInclusive = true; newCat.Range.MinIsInclusive = true; newCat.LegendText = startValue.ToString(CultureInfo.CurrentCulture); Scheme.AddCategory(newCat); } private void Configure() { _shadedRelief = new ShadedRelief(); _noDataColor = Color.Transparent; Scheme = new ColorScheme(); if (_raster != null) { var colors = _raster.CategoryColors(); if (colors != null && colors.Length > 0) { // Use colors that are built into the raster, e.g. GeoTIFF with palette _isElevation = false; // use all colors instead of unique colors because unique colors are not always set/correct int lastColor = colors[0].ToArgb(); // changed by jany_ 2015-06-02 int firstNr = 0; // group succeeding values with the same color to the same category for (int i = 1; i < colors.Length; i++) { int hash = colors[i].ToArgb(); if (hash != lastColor) { // the current color differs from the one before so we add a category for the color before AddCategory(firstNr, i - 1, colors[firstNr]); firstNr = i; lastColor = hash; } if (i == colors.Length - 1) // this is the last color, so we add the last category AddCategory(firstNr, i, colors[firstNr]); } } else { // Assume grid is elevation _elevationFactor = 1 / 3640000f; _isElevation = true; _extrusion = 1; _scheme.ApplyScheme(ColorSchemeType.FallLeaves, _raster); } } } #endregion } }
using System; using Raksha.Crypto.Utilities; namespace Raksha.Crypto.Digests { /** * Draft FIPS 180-2 implementation of SHA-256. <b>Note:</b> As this is * based on a draft this implementation is subject to change. * * <pre> * block word digest * SHA-1 512 32 160 * SHA-256 512 32 256 * SHA-384 1024 64 384 * SHA-512 1024 64 512 * </pre> */ public class Sha256Digest : GeneralDigest { private const int DigestLength = 32; private uint H1, H2, H3, H4, H5, H6, H7, H8; private uint[] X = new uint[64]; private int xOff; public Sha256Digest() { initHs(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha256Digest(Sha256Digest t) : base(t) { H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; H8 = t.H8; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "SHA-256"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff] = Pack.BE_To_UInt32(input, inOff); if (++xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (uint)((ulong)bitLength >> 32); X[15] = (uint)((ulong)bitLength); } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt32_To_BE((uint)H1, output, outOff); Pack.UInt32_To_BE((uint)H2, output, outOff + 4); Pack.UInt32_To_BE((uint)H3, output, outOff + 8); Pack.UInt32_To_BE((uint)H4, output, outOff + 12); Pack.UInt32_To_BE((uint)H5, output, outOff + 16); Pack.UInt32_To_BE((uint)H6, output, outOff + 20); Pack.UInt32_To_BE((uint)H7, output, outOff + 24); Pack.UInt32_To_BE((uint)H8, output, outOff + 28); Reset(); return DigestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); initHs(); xOff = 0; Array.Clear(X, 0, X.Length); } private void initHs() { /* SHA-256 initial hash value * The first 32 bits of the fractional parts of the square roots * of the first eight prime numbers */ H1 = 0x6a09e667; H2 = 0xbb67ae85; H3 = 0x3c6ef372; H4 = 0xa54ff53a; H5 = 0x510e527f; H6 = 0x9b05688c; H7 = 0x1f83d9ab; H8 = 0x5be0cd19; } internal override void ProcessBlock() { // // expand 16 word block into 64 word blocks. // for (int ti = 16; ti <= 63; ti++) { X[ti] = Theta1(X[ti - 2]) + X[ti - 7] + Theta0(X[ti - 15]) + X[ti - 16]; } // // set up working variables. // uint a = H1; uint b = H2; uint c = H3; uint d = H4; uint e = H5; uint f = H6; uint g = H7; uint h = H8; int t = 0; for(int i = 0; i < 8; ++i) { // t = 8 * i h += Sum1Ch(e, f, g) + K[t] + X[t]; d += h; h += Sum0Maj(a, b, c); ++t; // t = 8 * i + 1 g += Sum1Ch(d, e, f) + K[t] + X[t]; c += g; g += Sum0Maj(h, a, b); ++t; // t = 8 * i + 2 f += Sum1Ch(c, d, e) + K[t] + X[t]; b += f; f += Sum0Maj(g, h, a); ++t; // t = 8 * i + 3 e += Sum1Ch(b, c, d) + K[t] + X[t]; a += e; e += Sum0Maj(f, g, h); ++t; // t = 8 * i + 4 d += Sum1Ch(a, b, c) + K[t] + X[t]; h += d; d += Sum0Maj(e, f, g); ++t; // t = 8 * i + 5 c += Sum1Ch(h, a, b) + K[t] + X[t]; g += c; c += Sum0Maj(d, e, f); ++t; // t = 8 * i + 6 b += Sum1Ch(g, h, a) + K[t] + X[t]; f += b; b += Sum0Maj(c, d, e); ++t; // t = 8 * i + 7 a += Sum1Ch(f, g, h) + K[t] + X[t]; e += a; a += Sum0Maj(b, c, d); ++t; } H1 += a; H2 += b; H3 += c; H4 += d; H5 += e; H6 += f; H7 += g; H8 += h; // // reset the offset and clean out the word buffer. // xOff = 0; Array.Clear(X, 0, 16); } private static uint Sum1Ch( uint x, uint y, uint z) { // return Sum1(x) + Ch(x, y, z); return (((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))) + ((x & y) ^ ((~x) & z)); } private static uint Sum0Maj( uint x, uint y, uint z) { // return Sum0(x) + Maj(x, y, z); return (((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))) + ((x & y) ^ (x & z) ^ (y & z)); } // /* SHA-256 functions */ // private static uint Ch( // uint x, // uint y, // uint z) // { // return ((x & y) ^ ((~x) & z)); // } // // private static uint Maj( // uint x, // uint y, // uint z) // { // return ((x & y) ^ (x & z) ^ (y & z)); // } // // private static uint Sum0( // uint x) // { // return ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)); // } // // private static uint Sum1( // uint x) // { // return ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)); // } private static uint Theta0( uint x) { return ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3); } private static uint Theta1( uint x) { return ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10); } /* SHA-256 Constants * (represent the first 32 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ private static readonly uint[] K = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; } }
using System; using System.Collections.Generic; using System.Linq; using MonoMac.Foundation; using MonoMac.AppKit; namespace NSTableViewBinding { public partial class TestWindowController : MonoMac.AppKit.NSWindowController { internal static NSString FIRST_NAME = new NSString("firstname"); internal static NSString LAST_NAME = new NSString("lastname"); internal static NSString PHONE = new NSString("phone"); EditController myEditController = null; internal static List<NSString> Keys = new List<NSString> { FIRST_NAME, LAST_NAME, PHONE}; internal const int FIRST_NAME_IDX = 0; internal const int LAST_NAME_IDX = 1; internal const int PHONE_IDX = 2; #region Constructors // Called when created from unmanaged code public TestWindowController (IntPtr handle) : base(handle) { } // Called when created directly from a XIB file [Export("initWithCoder:")] public TestWindowController (NSCoder coder) : base(coder) { } // Call to load from the XIB/NIB file public TestWindowController () : base("TestWindow") { } #endregion //strongly typed window accessor public new TestWindow Window { get { return (TestWindow)base.Window; } } #region Overrides public override void AwakeFromNib () { base.AwakeFromNib (); //----------------------------------------------------------------------------- // Compiler directive USE_BINDINGS_BY_CODE set in the projects Options // 1) From the MonoDevelop Menu select Project -> NSTableViewBinding Options // This will bring up the project options panel. // 2) Under the category Build -> Compiler look for the field labeled Define Symbols half way // down the panel page. // 3) Add the symbol USE_BINDINGS_BY_CODE //----------------------------------------------------------------------------- // Your NSTableView's content needs to use Cocoa Bindings, // use Interface Builder to setup the bindings like so: // // Each column in the NSTableView needs to use Cocoa Bindings, // use Interface Builder to setup the bindings like so: // // columnIdentifier: "firstname" // "value" = arrangedObjects.firstname [NSTableArray (NSArrayController)] // Bind To: "TableArray" object (NSArrayController) // Controller Key = "arrangedObjects" // Model Key Path = "firstname" ("firstname" is a key in "TableArray") // // columnIdentifier: "lastname" // "value" = arrangedObjects.lastname [NSTableArray (NSArrayController)] // Bind To: "TableArray" object (NSArrayController) // Controller Key = "arrangedObjects" // Model Key Path = "lastname" ("lastname" is a key in "TableArray") // // columnIdentifier: "phone" // "value" = arrangedObjects.phone [NSTableArray (NSArrayController)] // Bind To: "TableArray" object (NSArrayController) // Controller Key = "arrangedObjects" // Model Key Path = "phone" ("phone" is a key in "TableArray") // // or do bindings by code: #if USE_BINDINGS_BY_CODE NSTableColumn firstNameColumn = myTableView.FindTableColumn(FIRST_NAME); firstNameColumn.Bind("value",myContentArray,"arrangedObjects.firstname",null); NSTableColumn lastNameColumn = myTableView.FindTableColumn(LAST_NAME); lastNameColumn.Bind("value",myContentArray,"arrangedObjects.lastname",null); NSTableColumn phoneColumn = myTableView.FindTableColumn(PHONE); phoneColumn.Bind("value",myContentArray,"arrangedObjects.phone",null); #endif // for NSTableView "double-click row" to work you need to use Cocoa Bindings, // use Interface Builder to setup the bindings like so: // // NSTableView: // "doubleClickArgument": // Bind To: "TableArray" object (NSArrayController) // Controller Key = "selectedObjects" // Selector Name = "inspect:" (don't forget the ":") // // "doubleClickTarget": // Bind To: (File's Owner) MyWindowController // Model Key Path = "self" // Selector Name = "inspect:" (don't forget the ":") // // ... also make sure none of the NSTableColumns are "editable". // // or do bindings by code: #if USE_BINDINGS_BY_CODE List<NSObject> doubleClickObjects = new List<NSObject> {new NSString("inspect:"), NSNumber.FromBoolean(true), NSNumber.FromBoolean(true)}; List<NSString> doubleClickKeys = new List<NSString> {new NSString("NSSelectorName"), new NSString("NSConditionallySetsHidden"), new NSString("NSRaisesForNotApplicableKeys")}; NSDictionary doubleClickOptionsDict = NSDictionary.FromObjectsAndKeys(doubleClickObjects.ToArray(),doubleClickKeys.ToArray()); myTableView.Bind("doubleClickArgument",myContentArray,"selectedObjects",doubleClickOptionsDict); myTableView.Bind("doubleClickTarget",this,"self",doubleClickOptionsDict); #endif // the enabled states of the two buttons "Add", "Remove" are bound to "canRemove" // use Interface Builder to setup the bindings like so: // // NSButton ("Add") // "enabled": // Bind To: "TableArray" object (NSArrayController) // Controller Key = "canAdd" // // NSButton ("Remove") // "enabled": // Bind To: "TableArray" object (NSArrayController) // Controller Key = "canRemove" // // or do bindings by code: #if USE_BINDINGS_BY_CODE List<NSObject> enableOptionsObjects = new List<NSObject> {NSNumber.FromBoolean(true)}; List<NSString> enableOptionsKeys = new List<NSString> {new NSString("NSRaisesForNotApplicableKeys")}; NSDictionary enableOptionsDict = NSDictionary.FromObjectsAndKeys(enableOptionsObjects.ToArray(),enableOptionsKeys.ToArray()); addButton.Bind("enabled",myContentArray,"canAdd",enableOptionsDict); removeButton.Bind("enabled",myContentArray,"canRemove",enableOptionsDict); #endif // the NSForm's text fields is bound to the current selection in the NSTableView's content array controller, // use Interface Builder to setup the bindings like so: // // NSFormCell: // "value": // Bind To: "TableArray" object (NSArrayController) // Controller Key = "selection" // Model Key Path = "firstname" // // or do bindings by code: #if USE_BINDINGS_BY_CODE List<NSObject> valueOptionsObjects = new List<NSObject> {NSNumber.FromBoolean(true), NSNumber.FromBoolean(true), NSNumber.FromBoolean(true)}; List<NSString> valueOptionsKeys = new List<NSString> {new NSString("NSAllowsEditingMultipleValuesSelection"), new NSString("NSConditionallySetsEditable"), new NSString("NSRaisesForNotApplicableKeys")}; NSDictionary valueOptionsDict = NSDictionary.FromObjectsAndKeys(enableOptionsObjects.ToArray(),enableOptionsKeys.ToArray()); myFormFields.CellAtIndex(FIRST_NAME_IDX).Bind("value",myContentArray,"selection.firstname",valueOptionsDict); myFormFields.CellAtIndex(LAST_NAME_IDX).Bind("value",myContentArray,"selection.lastname",valueOptionsDict); myFormFields.CellAtIndex(PHONE_IDX).Bind("value",myContentArray,"selection.phone",valueOptionsDict); #endif // start listening for selection changes in our NSTableView's array controller myContentArray.AddObserver(this,new NSString("selectionIndexes"),NSKeyValueObservingOptions.New,IntPtr.Zero); // finally, add the first record in the table as a default value. // // note: to allow the external NSForm fields to alter the table view selection through the "value" bindings, // added objects to the content array needs to be an "NSMutableDictionary" - // List<NSString> objects = new List<NSString> {new NSString("John"), new NSString("Doe"), new NSString("(333) 333-3333)")}; var dict = NSMutableDictionary.FromObjectsAndKeys(objects.ToArray(), Keys.ToArray()); myContentArray.AddObject(dict); } #endregion // // Inspect our selected objects (user double-clicked them). // // Note: this method will not get called until you make all columns in the table // as "non-editable". So long as they are editable, double clicking a row will // cause the current cell to be editied. // partial void inspect (NSArray sender) { NSArray selectedObjects = sender; Console.WriteLine("inspect"); int index; uint numItems = selectedObjects.Count; for (index = 0; index < numItems; index++) { NSDictionary objectDict = new NSDictionary(selectedObjects.ValueAt(0)); if (objectDict != null) { Console.WriteLine(string.Format("inspector item: [ {0} {1}, {2} ]", (NSString)objectDict[FIRST_NAME].ToString(), (NSString)objectDict[LAST_NAME].ToString(), (NSString)objectDict[PHONE].ToString())); } // setup the edit sheet controller if one hasn't been setup already if (myEditController == null) myEditController = new EditController(); // remember which selection index we are changing int savedSelectionIndex = myContentArray.SelectionIndex; NSDictionary editItem = new NSDictionary(selectedObjects.ValueAt(0)); // get the current selected object and start the edit sheet NSMutableDictionary newValues = myEditController.edit(editItem, this); if (!myEditController.Cancelled) { // remove the current selection and replace it with the newly edited one var currentObjects = myContentArray.SelectedObjects; myContentArray.Remove(currentObjects); // make sure to add the new entry at the same selection location as before myContentArray.Insert(newValues,savedSelectionIndex); } } } /// <summary> /// This method demonstrates how to observe selection changes in our NSTableView's array controller /// </summary> /// <param name="keyPath"> /// A <see cref="NSString"/> /// </param> /// <param name="ofObject"> /// A <see cref="NSArrayController"/> /// </param> /// <param name="change"> /// A <see cref="NSDictionary"/> /// </param> /// <param name="context"> /// A <see cref="IntPtr"/> /// </param> [Export("observeValueForKeyPath:ofObject:change:context:")] private void observeValueForKeyPath(NSString keyPath, NSArrayController ofObject, NSDictionary change, IntPtr context) { Console.Write(String.Format("Table selection changed: keyPath = {0} : ", keyPath.ToString())); for(uint idx = 0; idx < ofObject.SelectionIndexes.Count; idx++) { Console.Write(ofObject.SelectionIndexes.IndexGreaterThanOrEqual(idx) + " "); } Console.WriteLine(); } /// <summary> /// Ask the edit form to display itself to enter new record values /// </summary> /// <param name="sender"> /// A <see cref="NSButton"/> /// </param> partial void add (NSButton sender) { // setup the edit sheet controller if one hasn't been setup already if (myEditController == null) myEditController = new EditController(); // ask our edit sheet for information on the record we want to add NSMutableDictionary newValues = myEditController.edit(null, this); if (!myEditController.Cancelled) { // add the new entry myContentArray.AddObject(newValues); } } /// <summary> /// Remove an entry. /// </summary> /// <param name="sender"> /// A <see cref="NSButton"/> /// </param> partial void remove (NSButton sender) { myContentArray.RemoveAt(myContentArray.SelectionIndex); } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing.Printing; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; //credit to author Mark Pitman //reference: http://www.codeproject.com/KB/printing/printtreeview.aspx namespace Pitman.Printing { public class PrintHelper { private PrintDocument _printDoc; private Point _lastPrintPosition; private Image _controlImage = null; private int _nodeHeight = 0; private PrintDirection _currentDir; private int _scrollBarHeight = 0; private int _scrollBarWidth = 0; private int _pageNumber = 0; private DateTime _date; private string _title = string.Empty; private enum PrintDirection { Horizontal, Vertical } public PrintHelper() { _lastPrintPosition = new Point(0, 0); this._printDoc = new PrintDocument(); this._printDoc.BeginPrint += new System.Drawing.Printing.PrintEventHandler(this.printDoc_BeginPrint); this._printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDoc_PrintPage); this._printDoc.EndPrint += new PrintEventHandler(_printDoc_EndPrint); } void _printDoc_EndPrint(object sender, PrintEventArgs e) { _controlImage.Dispose(); } /// <summary> /// Shows a PrintPreview dialog displaying the Tree control passed in. /// </summary> /// <param name="tree">TreeView to print preview</param> public void PrintPreviewTree(TreeView tree, string title) { this._title = title; PrepareTreeImage((TreeView)tree); PrintPreviewDialog pp = new PrintPreviewDialog(); pp.Document = this._printDoc; pp.Show(); } /// <summary> /// Prints a tree /// </summary> /// <param name="tree">TreeView to print</param> public void PrintTree(TreeView tree, string title) { this._title = title; PrepareTreeImage((TreeView)tree); PrintDialog pd = new PrintDialog(); pd.Document = this._printDoc; if (pd.ShowDialog() == DialogResult.OK) { this._printDoc.Print(); } } /// <summary> /// Gets an image that shows the entire tree, not just what is visible on the form /// </summary> /// <param name="tree"></param> private void PrepareTreeImage(TreeView tree) { _scrollBarWidth = tree.Width - tree.ClientSize.Width; _scrollBarHeight = tree.Height - tree.ClientSize.Height; tree.Nodes[0].EnsureVisible(); int height = tree.Nodes[0].Bounds.Height; this._nodeHeight = height; int width = tree.Nodes[0].Bounds.Right; TreeNode node = tree.Nodes[0].NextVisibleNode; while (node != null) { height += node.Bounds.Height; if (node.Bounds.Right > width) { width = node.Bounds.Right; } node = node.NextVisibleNode; } //keep track of the original tree settings int tempHeight = tree.Height; int tempWidth = tree.Width; BorderStyle tempBorder = tree.BorderStyle; bool tempScrollable = tree.Scrollable; TreeNode selectedNode = tree.SelectedNode; //setup the tree to take the snapshot tree.SelectedNode = null; DockStyle tempDock = tree.Dock; tree.Height = height + _scrollBarHeight; tree.Width = width + _scrollBarWidth; tree.BorderStyle = BorderStyle.None; tree.Dock = DockStyle.None; //get the image of the tree // .Net 2.0 supports drawing controls onto bitmaps natively now // However, the full tree didn't get drawn when I tried it, so I am // sticking with the P/Invoke calls //_controlImage = new Bitmap(height, width); //Bitmap bmp = _controlImage as Bitmap; //tree.DrawToBitmap(bmp, tree.Bounds); this._controlImage = GetImage(tree.Handle, tree.Width, tree.Height); //reset the tree to its original settings tree.BorderStyle = tempBorder; tree.Width = tempWidth; tree.Height = tempHeight; tree.Dock = tempDock; tree.Scrollable = tempScrollable; tree.SelectedNode = selectedNode; //give the window time to update Application.DoEvents(); } // Returns an image of the specified width and height, of a control represented by handle. private Image GetImage(IntPtr handle, int width, int height) { IntPtr screenDC = GetDC(IntPtr.Zero); IntPtr hbm = CreateCompatibleBitmap(screenDC, width, height); Image image = Bitmap.FromHbitmap(hbm); Graphics g = Graphics.FromImage(image); IntPtr hdc = g.GetHdc(); SendMessage(handle, 0x0318 /*WM_PRINTCLIENT*/, hdc, (0x00000010 | 0x00000004 | 0x00000002)); g.ReleaseHdc(hdc); ReleaseDC(IntPtr.Zero, screenDC); return image; } private void printDoc_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e) { _lastPrintPosition = new Point(0, 0); this._currentDir = PrintDirection.Horizontal; this._pageNumber = 0; this._date = DateTime.Now; } private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { this._pageNumber++; Graphics g = e.Graphics; Rectangle sourceRect = new Rectangle(_lastPrintPosition, e.MarginBounds.Size); Rectangle destRect = e.MarginBounds; if ((sourceRect.Height % this._nodeHeight) > 0) { sourceRect.Height -= (sourceRect.Height % this._nodeHeight); } g.DrawImage(this._controlImage, destRect, sourceRect, GraphicsUnit.Pixel); //check to see if we need more pages if ((this._controlImage.Height - this._scrollBarHeight) > sourceRect.Bottom || (this._controlImage.Width - this._scrollBarWidth) > sourceRect.Right) { //need more pages e.HasMorePages = true; } if (this._currentDir == PrintDirection.Horizontal) { if (sourceRect.Right < (this._controlImage.Width - this._scrollBarWidth)) { //still need to print horizontally _lastPrintPosition.X += (sourceRect.Width + 1); } else { _lastPrintPosition.X = 0; _lastPrintPosition.Y += (sourceRect.Height + 1); this._currentDir = PrintDirection.Vertical; } } else if (this._currentDir == PrintDirection.Vertical && sourceRect.Right < (this._controlImage.Width - this._scrollBarWidth)) { this._currentDir = PrintDirection.Horizontal; _lastPrintPosition.X += (sourceRect.Width + 1); } else { _lastPrintPosition.Y += (sourceRect.Height + 1); } //print footer Brush brush = new SolidBrush(Color.Black); string footer = this._pageNumber.ToString(System.Globalization.NumberFormatInfo.CurrentInfo); Font f = new Font(FontFamily.GenericSansSerif, 10f); SizeF footerSize = g.MeasureString(footer, f); PointF pageBottomCenter = new PointF(e.PageBounds.Width / 2, e.MarginBounds.Bottom + ((e.PageBounds.Bottom - e.MarginBounds.Bottom) / 2)); PointF footerLocation = new PointF(pageBottomCenter.X - (footerSize.Width / 2), pageBottomCenter.Y - (footerSize.Height / 2)); g.DrawString(footer, f, brush, footerLocation); //print header if (this._pageNumber == 1 && this._title.Length > 0) { Font headerFont = new Font(FontFamily.GenericSansSerif, 24f, FontStyle.Bold, GraphicsUnit.Point); SizeF headerSize = g.MeasureString(this._title, headerFont); PointF headerLocation = new PointF(e.MarginBounds.Left, ((e.MarginBounds.Top - e.PageBounds.Top) / 2) - (headerSize.Height / 2)); g.DrawString(this._title, headerFont, brush, headerLocation); } } //External function declarations [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, int lParam); [DllImport("user32.dll")] private static extern IntPtr GetDC(IntPtr hWnd); [DllImport("user32.dll")] private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int width, int height); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace HoloToolkit.Sharing.SyncModel { /// <summary> /// The SyncArray class provides the functionality of an array in the data model. /// The array holds entire objects, not primitives, since each object is indexed by unique name. /// Note that this array is unordered. /// </summary> /// <typeparam name="T">Type of SyncObject in the array.</typeparam> public class SyncArray<T> : SyncObject, IEnumerable<T> where T : SyncObject, new() { /// <summary> /// Called when a new object has been added to the array. /// </summary> public event Action<T> ObjectAdded; /// <summary> /// Called when an existing object has been removed from the array /// </summary> public event Action<T> ObjectRemoved; /// <summary> /// // Maps the unique id to object /// </summary> private readonly Dictionary<string, T> dataArray; /// <summary> /// Type of objects in the array. /// This is cached so that we don't have to call typeof(T) more than once. /// </summary> protected readonly Type arrayType; public SyncArray(string field) : base(field) { dataArray = new Dictionary<string, T>(); arrayType = typeof(T); } public SyncArray() : this(string.Empty) { } /// <summary> /// Creates the object in the array, based on its underlying object element that came from the sync system. /// </summary> /// <param name="objectElement">Object element on which the data model object is based.</param> /// <returns>The created data model object of the appropriate type.</returns> protected virtual T CreateObject(ObjectElement objectElement) { Type objectType = SyncSettings.Instance.GetDataModelType(objectElement.GetObjectType()).AsType(); if (!objectType.IsSubclassOf(arrayType) && objectType != arrayType) { throw new InvalidCastException(string.Format("Object of incorrect type added to SyncArray: Expected {0}, got {1} ", objectType, objectElement.GetObjectType().GetString())); } object createdObject = Activator.CreateInstance(objectType); T spawnedDataModel = (T)createdObject; spawnedDataModel.Element = objectElement; spawnedDataModel.FieldName = objectElement.GetName(); // TODO: this should not query SharingStage, but instead query the underlying session layer spawnedDataModel.Owner = SharingStage.Instance.SessionUsersTracker.GetUserById(objectElement.GetOwnerID()); return spawnedDataModel; } /// <summary> /// Adds a new entry into the array. /// </summary> /// <param name="newSyncObject">New object to add.</param> /// <param name="owner">Owner the object. Set to null if the object has no owner.</param> /// <returns>Object that was added, with its networking elements setup.</returns> public T AddObject(T newSyncObject, User owner = null) { // Create our object element for our target string id = System.Guid.NewGuid().ToString(); string dataModelName = SyncSettings.Instance.GetDataModelName(newSyncObject.GetType()); ObjectElement existingElement = Element.CreateObjectElement(new XString(id), dataModelName, owner); // Create a new object and assign the element newSyncObject.Element = existingElement; newSyncObject.FieldName = id; newSyncObject.Owner = owner; // Register the child with the object AddChild(newSyncObject); // Update internal map dataArray[id] = newSyncObject; // Initialize it so it can be used immediately. newSyncObject.InitializeLocal(Element); // Notify listeners that an object was added. if (ObjectAdded != null) { ObjectAdded(newSyncObject); } return newSyncObject; } /// <summary> /// Removes an entry from the array /// </summary> /// <param name="existingObject">Object to remove.</param> /// <returns>True if removal succeeded, false if not.</returns> public bool RemoveObject(T existingObject) { bool success = false; if (existingObject != null) { string uniqueName = existingObject.Element.GetName(); if (dataArray.Remove(uniqueName)) { RemoveChild(existingObject); if (ObjectRemoved != null) { ObjectRemoved(existingObject); } success = true; } } return success; } // Returns a full list of the objects public T[] GetDataArray() { var childrenList = new List<T>(dataArray.Count); foreach (KeyValuePair<string, T> pair in dataArray) { childrenList.Add(pair.Value); } return childrenList.ToArray(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return dataArray.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return dataArray.Values.GetEnumerator(); } public void Clear() { // TODO: We need a way of resetting in a consistent way across all object types and hierarchies. T[] array = GetDataArray(); for (int i = 0; i < array.Length; i++) { RemoveObject(array[i]); } } protected override void OnElementAdded(Element element) { if (element.GetElementType() == ElementType.ObjectType) { // Add the new object and listen for when the initialization has fully completed since it can take time. T newObject = AddObject(ObjectElement.Cast(element)); newObject.InitializationComplete += OnInitializationComplete; } else { Debug.LogError("Error: Adding unknown element to SyncArray<T>"); } base.OnElementAdded(element); } protected override void OnElementDeleted(Element element) { base.OnElementDeleted(element); string uniqueName = element.GetName(); if (dataArray.ContainsKey(uniqueName)) { T obj = dataArray[uniqueName]; RemoveObject(obj); } } private void OnInitializationComplete(SyncObject obj) { // Notify listeners know that an object was added if (ObjectAdded != null) { ObjectAdded(obj as T); } } /// <summary> /// Adds a new entry into the array. /// </summary> /// <param name="existingElement">Element from which the object should be created.</param> /// <returns></returns> private T AddObject(ObjectElement existingElement) { string id = existingElement.GetName(); // Create a new object and assign the element T newObject = CreateObject(existingElement); // Register the child with the object AddChild(newObject); // Update internal map dataArray[id] = newObject; return newObject; } } }
//----------------------------------------------------------------------- // <copyright file="BindableBase.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>This class implements INotifyPropertyChanged</summary> //----------------------------------------------------------------------- using System; using System.ComponentModel; namespace Csla.Core { /// <summary> /// This class implements INotifyPropertyChanged /// and INotifyPropertyChanging in a /// serialization-safe manner. /// </summary> [Serializable()] public abstract class BindableBase : MobileObject, INotifyPropertyChanged, INotifyPropertyChanging { /// <summary> /// Creates an instance of the object. /// </summary> protected BindableBase() { } [NonSerialized()] private PropertyChangedEventHandler _nonSerializableChangedHandlers; private PropertyChangedEventHandler _serializableChangedHandlers; /// <summary> /// Implements a serialization-safe PropertyChanged event. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public event PropertyChangedEventHandler PropertyChanged { add { if (ShouldHandlerSerialize(value)) _serializableChangedHandlers = (PropertyChangedEventHandler) System.Delegate.Combine(_serializableChangedHandlers, value); else _nonSerializableChangedHandlers = (PropertyChangedEventHandler) System.Delegate.Combine(_nonSerializableChangedHandlers, value); } remove { if (ShouldHandlerSerialize(value)) _serializableChangedHandlers = (PropertyChangedEventHandler) System.Delegate.Remove(_serializableChangedHandlers, value); else _nonSerializableChangedHandlers = (PropertyChangedEventHandler) System.Delegate.Remove(_nonSerializableChangedHandlers, value); } } /// <summary> /// Override this method to change the default logic for determining /// if the event handler should be serialized /// </summary> /// <param name="value">the event handler to review</param> /// <returns></returns> protected virtual bool ShouldHandlerSerialize(PropertyChangedEventHandler value) { return value.Method.IsPublic && value.Method.DeclaringType != null && (value.Method.DeclaringType.IsSerializable || value.Method.IsStatic); } /// <summary> /// Call this method to raise the PropertyChanged event /// for a specific property. /// </summary> /// <param name="propertyName">Name of the property that /// has changed.</param> /// <remarks> /// This method may be called by properties in the business /// class to indicate the change in a specific property. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnPropertyChanged(string propertyName) { if (_nonSerializableChangedHandlers != null) _nonSerializableChangedHandlers.Invoke(this, new PropertyChangedEventArgs(propertyName)); if (_serializableChangedHandlers != null) _serializableChangedHandlers.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// Call this method to raise the PropertyChanged event /// for a MetaData (IsXYZ) property /// </summary> /// <param name="propertyName">Name of the property that /// has changed.</param> /// <remarks> /// This method may be called by properties in the business /// class to indicate the change in a specific property. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnMetaPropertyChanged(string propertyName) { if (_nonSerializableChangedHandlers != null) _nonSerializableChangedHandlers.Invoke(this, new MetaPropertyChangedEventArgs(propertyName)); if (_serializableChangedHandlers != null) _serializableChangedHandlers.Invoke(this, new MetaPropertyChangedEventArgs(propertyName)); } /// <summary> /// Call this method to raise the PropertyChanged event /// for a specific property. /// </summary> /// <param name="propertyInfo">PropertyInfo of the property that /// has changed.</param> /// <remarks> /// This method may be called by properties in the business /// class to indicate the change in a specific property. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnPropertyChanged(IPropertyInfo propertyInfo) { OnPropertyChanged(propertyInfo.Name); } /// <summary> /// Call this method to raise the PropertyChanged event /// for all object properties. /// </summary> /// <remarks> /// This method is for backward compatibility with /// CSLA .NET 1.x. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnIsDirtyChanged() { OnUnknownPropertyChanged(); } /// <summary> /// Call this method to raise the PropertyChanged event /// for all object properties. /// </summary> /// <remarks> /// This method is automatically called by MarkDirty. It /// actually raises PropertyChanged for an empty string, /// which tells data binding to refresh all properties. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnUnknownPropertyChanged() { OnPropertyChanged(string.Empty); } [NonSerialized()] private PropertyChangingEventHandler _nonSerializableChangingHandlers; private PropertyChangingEventHandler _serializableChangingHandlers; /// <summary> /// Implements a serialization-safe PropertyChanging event. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public event PropertyChangingEventHandler PropertyChanging { add { if (ShouldHandlerSerialize(value)) _serializableChangingHandlers = (PropertyChangingEventHandler) System.Delegate.Combine(_serializableChangingHandlers, value); else _nonSerializableChangingHandlers = (PropertyChangingEventHandler) System.Delegate.Combine(_nonSerializableChangingHandlers, value); } remove { if (ShouldHandlerSerialize(value)) _serializableChangingHandlers = (PropertyChangingEventHandler) System.Delegate.Remove(_serializableChangingHandlers, value); else _nonSerializableChangingHandlers = (PropertyChangingEventHandler) System.Delegate.Remove(_nonSerializableChangingHandlers, value); } } /// <summary> /// Call this method to raise the PropertyChanging event /// for all object properties. /// </summary> /// <remarks> /// This method is for backward compatibility with /// CSLA .NET 1.x. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnIsDirtyChanging() { OnUnknownPropertyChanging(); } /// <summary> /// Call this method to raise the PropertyChanging event /// for all object properties. /// </summary> /// <remarks> /// This method is automatically called by MarkDirty. It /// actually raises PropertyChanging for an empty string, /// which tells data binding to refresh all properties. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnUnknownPropertyChanging() { OnPropertyChanging(string.Empty); } /// <summary> /// Call this method to raise the PropertyChanging event /// for a specific property. /// </summary> /// <param name="propertyName">Name of the property that /// has Changing.</param> /// <remarks> /// This method may be called by properties in the business /// class to indicate the change in a specific property. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnPropertyChanging(string propertyName) { if (_nonSerializableChangingHandlers != null) _nonSerializableChangingHandlers.Invoke(this, new PropertyChangingEventArgs(propertyName)); if (_serializableChangingHandlers != null) _serializableChangingHandlers.Invoke(this, new PropertyChangingEventArgs(propertyName)); } /// <summary> /// Call this method to raise the PropertyChanging event /// for a specific property. /// </summary> /// <param name="propertyInfo">PropertyInfo of the property that /// has Changing.</param> /// <remarks> /// This method may be called by properties in the business /// class to indicate the change in a specific property. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnPropertyChanging(IPropertyInfo propertyInfo) { OnPropertyChanging(propertyInfo.Name); } /// <summary> /// Override this method to change the default logic for determining /// if the event handler should be serialized /// </summary> /// <param name="value">the event handler to review</param> /// <returns></returns> protected virtual bool ShouldHandlerSerialize(PropertyChangingEventHandler value) { return value.Method.IsPublic && value.Method.DeclaringType != null && (value.Method.DeclaringType.IsSerializable || value.Method.IsStatic); } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Org.Apache.Cordova { // Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']" [global::Android.Runtime.Register ("org/apache/cordova/PluginResult", DoNotGenerateAcw=true)] public partial class PluginResult : global::Java.Lang.Object { // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/field[@name='MESSAGE_TYPE_ARRAYBUFFER']" [Register ("MESSAGE_TYPE_ARRAYBUFFER")] public const int MessageTypeArraybuffer = (int) 6; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/field[@name='MESSAGE_TYPE_BINARYSTRING']" [Register ("MESSAGE_TYPE_BINARYSTRING")] public const int MessageTypeBinarystring = (int) 7; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/field[@name='MESSAGE_TYPE_BOOLEAN']" [Register ("MESSAGE_TYPE_BOOLEAN")] public const int MessageTypeBoolean = (int) 4; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/field[@name='MESSAGE_TYPE_JSON']" [Register ("MESSAGE_TYPE_JSON")] public const int MessageTypeJson = (int) 2; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/field[@name='MESSAGE_TYPE_MULTIPART']" [Register ("MESSAGE_TYPE_MULTIPART")] public const int MessageTypeMultipart = (int) 8; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/field[@name='MESSAGE_TYPE_NULL']" [Register ("MESSAGE_TYPE_NULL")] public const int MessageTypeNull = (int) 5; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/field[@name='MESSAGE_TYPE_NUMBER']" [Register ("MESSAGE_TYPE_NUMBER")] public const int MessageTypeNumber = (int) 3; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/field[@name='MESSAGE_TYPE_STRING']" [Register ("MESSAGE_TYPE_STRING")] public const int MessageTypeString = (int) 1; static IntPtr StatusMessages_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/field[@name='StatusMessages']" [Register ("StatusMessages")] public static IList<string> StatusMessages { get { if (StatusMessages_jfieldId == IntPtr.Zero) StatusMessages_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "StatusMessages", "[Ljava/lang/String;"); return JavaArray<string>.FromJniHandle (JNIEnv.GetStaticObjectField (class_ref, StatusMessages_jfieldId), JniHandleOwnership.TransferLocalRef); } set { if (StatusMessages_jfieldId == IntPtr.Zero) StatusMessages_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "StatusMessages", "[Ljava/lang/String;"); IntPtr native_value = JavaArray<string>.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, StatusMessages_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } // Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult.Status']" [global::Android.Runtime.Register ("org/apache/cordova/PluginResult$Status", DoNotGenerateAcw=true)] public sealed partial class Status : global::Java.Lang.Enum { static IntPtr CLASS_NOT_FOUND_EXCEPTION_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult.Status']/field[@name='CLASS_NOT_FOUND_EXCEPTION']" [Register ("CLASS_NOT_FOUND_EXCEPTION")] public static global::Org.Apache.Cordova.PluginResult.Status ClassNotFoundException { get { if (CLASS_NOT_FOUND_EXCEPTION_jfieldId == IntPtr.Zero) CLASS_NOT_FOUND_EXCEPTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "CLASS_NOT_FOUND_EXCEPTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, CLASS_NOT_FOUND_EXCEPTION_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult.Status> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (CLASS_NOT_FOUND_EXCEPTION_jfieldId == IntPtr.Zero) CLASS_NOT_FOUND_EXCEPTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "CLASS_NOT_FOUND_EXCEPTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, CLASS_NOT_FOUND_EXCEPTION_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } static IntPtr ERROR_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult.Status']/field[@name='ERROR']" [Register ("ERROR")] public static global::Org.Apache.Cordova.PluginResult.Status Error { get { if (ERROR_jfieldId == IntPtr.Zero) ERROR_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "ERROR", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, ERROR_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult.Status> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (ERROR_jfieldId == IntPtr.Zero) ERROR_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "ERROR", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, ERROR_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } static IntPtr ILLEGAL_ACCESS_EXCEPTION_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult.Status']/field[@name='ILLEGAL_ACCESS_EXCEPTION']" [Register ("ILLEGAL_ACCESS_EXCEPTION")] public static global::Org.Apache.Cordova.PluginResult.Status IllegalAccessException { get { if (ILLEGAL_ACCESS_EXCEPTION_jfieldId == IntPtr.Zero) ILLEGAL_ACCESS_EXCEPTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "ILLEGAL_ACCESS_EXCEPTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, ILLEGAL_ACCESS_EXCEPTION_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult.Status> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (ILLEGAL_ACCESS_EXCEPTION_jfieldId == IntPtr.Zero) ILLEGAL_ACCESS_EXCEPTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "ILLEGAL_ACCESS_EXCEPTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, ILLEGAL_ACCESS_EXCEPTION_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } static IntPtr INSTANTIATION_EXCEPTION_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult.Status']/field[@name='INSTANTIATION_EXCEPTION']" [Register ("INSTANTIATION_EXCEPTION")] public static global::Org.Apache.Cordova.PluginResult.Status InstantiationException { get { if (INSTANTIATION_EXCEPTION_jfieldId == IntPtr.Zero) INSTANTIATION_EXCEPTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "INSTANTIATION_EXCEPTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, INSTANTIATION_EXCEPTION_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult.Status> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (INSTANTIATION_EXCEPTION_jfieldId == IntPtr.Zero) INSTANTIATION_EXCEPTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "INSTANTIATION_EXCEPTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, INSTANTIATION_EXCEPTION_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } static IntPtr INVALID_ACTION_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult.Status']/field[@name='INVALID_ACTION']" [Register ("INVALID_ACTION")] public static global::Org.Apache.Cordova.PluginResult.Status InvalidAction { get { if (INVALID_ACTION_jfieldId == IntPtr.Zero) INVALID_ACTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "INVALID_ACTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, INVALID_ACTION_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult.Status> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (INVALID_ACTION_jfieldId == IntPtr.Zero) INVALID_ACTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "INVALID_ACTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, INVALID_ACTION_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } static IntPtr IO_EXCEPTION_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult.Status']/field[@name='IO_EXCEPTION']" [Register ("IO_EXCEPTION")] public static global::Org.Apache.Cordova.PluginResult.Status IoException { get { if (IO_EXCEPTION_jfieldId == IntPtr.Zero) IO_EXCEPTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "IO_EXCEPTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, IO_EXCEPTION_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult.Status> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (IO_EXCEPTION_jfieldId == IntPtr.Zero) IO_EXCEPTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "IO_EXCEPTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, IO_EXCEPTION_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } static IntPtr JSON_EXCEPTION_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult.Status']/field[@name='JSON_EXCEPTION']" [Register ("JSON_EXCEPTION")] public static global::Org.Apache.Cordova.PluginResult.Status JsonException { get { if (JSON_EXCEPTION_jfieldId == IntPtr.Zero) JSON_EXCEPTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "JSON_EXCEPTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, JSON_EXCEPTION_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult.Status> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (JSON_EXCEPTION_jfieldId == IntPtr.Zero) JSON_EXCEPTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "JSON_EXCEPTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, JSON_EXCEPTION_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } static IntPtr MALFORMED_URL_EXCEPTION_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult.Status']/field[@name='MALFORMED_URL_EXCEPTION']" [Register ("MALFORMED_URL_EXCEPTION")] public static global::Org.Apache.Cordova.PluginResult.Status MalformedUrlException { get { if (MALFORMED_URL_EXCEPTION_jfieldId == IntPtr.Zero) MALFORMED_URL_EXCEPTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "MALFORMED_URL_EXCEPTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, MALFORMED_URL_EXCEPTION_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult.Status> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (MALFORMED_URL_EXCEPTION_jfieldId == IntPtr.Zero) MALFORMED_URL_EXCEPTION_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "MALFORMED_URL_EXCEPTION", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, MALFORMED_URL_EXCEPTION_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } static IntPtr NO_RESULT_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult.Status']/field[@name='NO_RESULT']" [Register ("NO_RESULT")] public static global::Org.Apache.Cordova.PluginResult.Status NoResult { get { if (NO_RESULT_jfieldId == IntPtr.Zero) NO_RESULT_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "NO_RESULT", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, NO_RESULT_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult.Status> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (NO_RESULT_jfieldId == IntPtr.Zero) NO_RESULT_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "NO_RESULT", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, NO_RESULT_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } static IntPtr OK_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult.Status']/field[@name='OK']" [Register ("OK")] public static global::Org.Apache.Cordova.PluginResult.Status Ok { get { if (OK_jfieldId == IntPtr.Zero) OK_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "OK", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, OK_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult.Status> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (OK_jfieldId == IntPtr.Zero) OK_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "OK", "Lorg/apache/cordova/PluginResult$Status;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetStaticField (class_ref, OK_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/apache/cordova/PluginResult$Status", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Status); } } internal Status (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_valueOf_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult.Status']/method[@name='valueOf' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("valueOf", "(Ljava/lang/String;)Lorg/apache/cordova/PluginResult$Status;", "")] public static global::Org.Apache.Cordova.PluginResult.Status ValueOf (string p0) { if (id_valueOf_Ljava_lang_String_ == IntPtr.Zero) id_valueOf_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "valueOf", "(Ljava/lang/String;)Lorg/apache/cordova/PluginResult$Status;"); IntPtr native_p0 = JNIEnv.NewString (p0); global::Org.Apache.Cordova.PluginResult.Status __ret = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult.Status> (JNIEnv.CallStaticObjectMethod (class_ref, id_valueOf_Ljava_lang_String_, new JValue (native_p0)), JniHandleOwnership.TransferLocalRef); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static IntPtr id_values; // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult.Status']/method[@name='values' and count(parameter)=0]" [Register ("values", "()[Lorg/apache/cordova/PluginResult$Status;", "")] public static global::Org.Apache.Cordova.PluginResult.Status[] Values () { if (id_values == IntPtr.Zero) id_values = JNIEnv.GetStaticMethodID (class_ref, "values", "()[Lorg/apache/cordova/PluginResult$Status;"); return (global::Org.Apache.Cordova.PluginResult.Status[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_values), JniHandleOwnership.TransferLocalRef, typeof (global::Org.Apache.Cordova.PluginResult.Status)); } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/apache/cordova/PluginResult", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (PluginResult); } } protected PluginResult (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Lorg_apache_cordova_PluginResult_Status_Ljava_util_List_; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/constructor[@name='PluginResult' and count(parameter)=2 and parameter[1][@type='org.apache.cordova.PluginResult.Status'] and parameter[2][@type='java.util.List']]" [Register (".ctor", "(Lorg/apache/cordova/PluginResult$Status;Ljava/util/List;)V", "")] public PluginResult (global::Org.Apache.Cordova.PluginResult.Status p0, global::System.Collections.Generic.IList<global::Org.Apache.Cordova.PluginResult> p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; IntPtr native_p1 = global::Android.Runtime.JavaList<global::Org.Apache.Cordova.PluginResult>.ToLocalJniHandle (p1);; if (GetType () != typeof (PluginResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/PluginResult$Status;Ljava/util/List;)V", new JValue (p0), new JValue (native_p1)), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/PluginResult$Status;Ljava/util/List;)V", new JValue (p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p1); return; } if (id_ctor_Lorg_apache_cordova_PluginResult_Status_Ljava_util_List_ == IntPtr.Zero) id_ctor_Lorg_apache_cordova_PluginResult_Status_Ljava_util_List_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/PluginResult$Status;Ljava/util/List;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_Ljava_util_List_, new JValue (p0), new JValue (native_p1)), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_Ljava_util_List_, new JValue (p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p1); } static IntPtr id_ctor_Lorg_apache_cordova_PluginResult_Status_Ljava_lang_String_; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/constructor[@name='PluginResult' and count(parameter)=2 and parameter[1][@type='org.apache.cordova.PluginResult.Status'] and parameter[2][@type='java.lang.String']]" [Register (".ctor", "(Lorg/apache/cordova/PluginResult$Status;Ljava/lang/String;)V", "")] public PluginResult (global::Org.Apache.Cordova.PluginResult.Status p0, string p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; IntPtr native_p1 = JNIEnv.NewString (p1);; if (GetType () != typeof (PluginResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/PluginResult$Status;Ljava/lang/String;)V", new JValue (p0), new JValue (native_p1)), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/PluginResult$Status;Ljava/lang/String;)V", new JValue (p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p1); return; } if (id_ctor_Lorg_apache_cordova_PluginResult_Status_Ljava_lang_String_ == IntPtr.Zero) id_ctor_Lorg_apache_cordova_PluginResult_Status_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/PluginResult$Status;Ljava/lang/String;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_Ljava_lang_String_, new JValue (p0), new JValue (native_p1)), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_Ljava_lang_String_, new JValue (p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p1); } static IntPtr id_ctor_Lorg_apache_cordova_PluginResult_Status_Lorg_json_JSONArray_; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/constructor[@name='PluginResult' and count(parameter)=2 and parameter[1][@type='org.apache.cordova.PluginResult.Status'] and parameter[2][@type='org.json.JSONArray']]" [Register (".ctor", "(Lorg/apache/cordova/PluginResult$Status;Lorg/json/JSONArray;)V", "")] public PluginResult (global::Org.Apache.Cordova.PluginResult.Status p0, global::Org.Json.JSONArray p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; if (GetType () != typeof (PluginResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/PluginResult$Status;Lorg/json/JSONArray;)V", new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/PluginResult$Status;Lorg/json/JSONArray;)V", new JValue (p0), new JValue (p1)); return; } if (id_ctor_Lorg_apache_cordova_PluginResult_Status_Lorg_json_JSONArray_ == IntPtr.Zero) id_ctor_Lorg_apache_cordova_PluginResult_Status_Lorg_json_JSONArray_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/PluginResult$Status;Lorg/json/JSONArray;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_Lorg_json_JSONArray_, new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_Lorg_json_JSONArray_, new JValue (p0), new JValue (p1)); } static IntPtr id_ctor_Lorg_apache_cordova_PluginResult_Status_Lorg_json_JSONObject_; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/constructor[@name='PluginResult' and count(parameter)=2 and parameter[1][@type='org.apache.cordova.PluginResult.Status'] and parameter[2][@type='org.json.JSONObject']]" [Register (".ctor", "(Lorg/apache/cordova/PluginResult$Status;Lorg/json/JSONObject;)V", "")] public PluginResult (global::Org.Apache.Cordova.PluginResult.Status p0, global::Org.Json.JSONObject p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; if (GetType () != typeof (PluginResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/PluginResult$Status;Lorg/json/JSONObject;)V", new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/PluginResult$Status;Lorg/json/JSONObject;)V", new JValue (p0), new JValue (p1)); return; } if (id_ctor_Lorg_apache_cordova_PluginResult_Status_Lorg_json_JSONObject_ == IntPtr.Zero) id_ctor_Lorg_apache_cordova_PluginResult_Status_Lorg_json_JSONObject_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/PluginResult$Status;Lorg/json/JSONObject;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_Lorg_json_JSONObject_, new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_Lorg_json_JSONObject_, new JValue (p0), new JValue (p1)); } static IntPtr id_ctor_Lorg_apache_cordova_PluginResult_Status_I; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/constructor[@name='PluginResult' and count(parameter)=2 and parameter[1][@type='org.apache.cordova.PluginResult.Status'] and parameter[2][@type='int']]" [Register (".ctor", "(Lorg/apache/cordova/PluginResult$Status;I)V", "")] public PluginResult (global::Org.Apache.Cordova.PluginResult.Status p0, int p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; if (GetType () != typeof (PluginResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/PluginResult$Status;I)V", new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/PluginResult$Status;I)V", new JValue (p0), new JValue (p1)); return; } if (id_ctor_Lorg_apache_cordova_PluginResult_Status_I == IntPtr.Zero) id_ctor_Lorg_apache_cordova_PluginResult_Status_I = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/PluginResult$Status;I)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_I, new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_I, new JValue (p0), new JValue (p1)); } static IntPtr id_ctor_Lorg_apache_cordova_PluginResult_Status_F; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/constructor[@name='PluginResult' and count(parameter)=2 and parameter[1][@type='org.apache.cordova.PluginResult.Status'] and parameter[2][@type='float']]" [Register (".ctor", "(Lorg/apache/cordova/PluginResult$Status;F)V", "")] public PluginResult (global::Org.Apache.Cordova.PluginResult.Status p0, float p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; if (GetType () != typeof (PluginResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/PluginResult$Status;F)V", new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/PluginResult$Status;F)V", new JValue (p0), new JValue (p1)); return; } if (id_ctor_Lorg_apache_cordova_PluginResult_Status_F == IntPtr.Zero) id_ctor_Lorg_apache_cordova_PluginResult_Status_F = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/PluginResult$Status;F)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_F, new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_F, new JValue (p0), new JValue (p1)); } static IntPtr id_ctor_Lorg_apache_cordova_PluginResult_Status_Z; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/constructor[@name='PluginResult' and count(parameter)=2 and parameter[1][@type='org.apache.cordova.PluginResult.Status'] and parameter[2][@type='boolean']]" [Register (".ctor", "(Lorg/apache/cordova/PluginResult$Status;Z)V", "")] public PluginResult (global::Org.Apache.Cordova.PluginResult.Status p0, bool p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; if (GetType () != typeof (PluginResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/PluginResult$Status;Z)V", new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/PluginResult$Status;Z)V", new JValue (p0), new JValue (p1)); return; } if (id_ctor_Lorg_apache_cordova_PluginResult_Status_Z == IntPtr.Zero) id_ctor_Lorg_apache_cordova_PluginResult_Status_Z = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/PluginResult$Status;Z)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_Z, new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_Z, new JValue (p0), new JValue (p1)); } static IntPtr id_ctor_Lorg_apache_cordova_PluginResult_Status_arrayB; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/constructor[@name='PluginResult' and count(parameter)=2 and parameter[1][@type='org.apache.cordova.PluginResult.Status'] and parameter[2][@type='byte[]']]" [Register (".ctor", "(Lorg/apache/cordova/PluginResult$Status;[B)V", "")] public PluginResult (global::Org.Apache.Cordova.PluginResult.Status p0, byte[] p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; IntPtr native_p1 = JNIEnv.NewArray (p1);; if (GetType () != typeof (PluginResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/PluginResult$Status;[B)V", new JValue (p0), new JValue (native_p1)), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/PluginResult$Status;[B)V", new JValue (p0), new JValue (native_p1)); if (p1 != null) { JNIEnv.CopyArray (native_p1, p1); JNIEnv.DeleteLocalRef (native_p1); } return; } if (id_ctor_Lorg_apache_cordova_PluginResult_Status_arrayB == IntPtr.Zero) id_ctor_Lorg_apache_cordova_PluginResult_Status_arrayB = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/PluginResult$Status;[B)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_arrayB, new JValue (p0), new JValue (native_p1)), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_arrayB, new JValue (p0), new JValue (native_p1)); if (p1 != null) { JNIEnv.CopyArray (native_p1, p1); JNIEnv.DeleteLocalRef (native_p1); } } static IntPtr id_ctor_Lorg_apache_cordova_PluginResult_Status_arrayBZ; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/constructor[@name='PluginResult' and count(parameter)=3 and parameter[1][@type='org.apache.cordova.PluginResult.Status'] and parameter[2][@type='byte[]'] and parameter[3][@type='boolean']]" [Register (".ctor", "(Lorg/apache/cordova/PluginResult$Status;[BZ)V", "")] public PluginResult (global::Org.Apache.Cordova.PluginResult.Status p0, byte[] p1, bool p2) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; IntPtr native_p1 = JNIEnv.NewArray (p1);; if (GetType () != typeof (PluginResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/PluginResult$Status;[BZ)V", new JValue (p0), new JValue (native_p1), new JValue (p2)), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/PluginResult$Status;[BZ)V", new JValue (p0), new JValue (native_p1), new JValue (p2)); if (p1 != null) { JNIEnv.CopyArray (native_p1, p1); JNIEnv.DeleteLocalRef (native_p1); } return; } if (id_ctor_Lorg_apache_cordova_PluginResult_Status_arrayBZ == IntPtr.Zero) id_ctor_Lorg_apache_cordova_PluginResult_Status_arrayBZ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/PluginResult$Status;[BZ)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_arrayBZ, new JValue (p0), new JValue (native_p1), new JValue (p2)), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_arrayBZ, new JValue (p0), new JValue (native_p1), new JValue (p2)); if (p1 != null) { JNIEnv.CopyArray (native_p1, p1); JNIEnv.DeleteLocalRef (native_p1); } } static IntPtr id_ctor_Lorg_apache_cordova_PluginResult_Status_; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/constructor[@name='PluginResult' and count(parameter)=1 and parameter[1][@type='org.apache.cordova.PluginResult.Status']]" [Register (".ctor", "(Lorg/apache/cordova/PluginResult$Status;)V", "")] public PluginResult (global::Org.Apache.Cordova.PluginResult.Status p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; if (GetType () != typeof (PluginResult)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/PluginResult$Status;)V", new JValue (p0)), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/PluginResult$Status;)V", new JValue (p0)); return; } if (id_ctor_Lorg_apache_cordova_PluginResult_Status_ == IntPtr.Zero) id_ctor_Lorg_apache_cordova_PluginResult_Status_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/PluginResult$Status;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_, new JValue (p0)), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_PluginResult_Status_, new JValue (p0)); } static Delegate cb_getJSONString; #pragma warning disable 0169 static Delegate GetGetJSONStringHandler () { if (cb_getJSONString == null) cb_getJSONString = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetJSONString); return cb_getJSONString; } static IntPtr n_GetJSONString (IntPtr jnienv, IntPtr native__this) { global::Org.Apache.Cordova.PluginResult __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.JSONString); } #pragma warning restore 0169 static IntPtr id_getJSONString; [Obsolete (@"deprecated")] public virtual string JSONString { // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/method[@name='getJSONString' and count(parameter)=0]" [Register ("getJSONString", "()Ljava/lang/String;", "GetGetJSONStringHandler")] get { if (id_getJSONString == IntPtr.Zero) id_getJSONString = JNIEnv.GetMethodID (class_ref, "getJSONString", "()Ljava/lang/String;"); if (GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getJSONString), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getJSONString", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } } static Delegate cb_getKeepCallback; #pragma warning disable 0169 static Delegate GetGetKeepCallbackHandler () { if (cb_getKeepCallback == null) cb_getKeepCallback = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_GetKeepCallback); return cb_getKeepCallback; } static bool n_GetKeepCallback (IntPtr jnienv, IntPtr native__this) { global::Org.Apache.Cordova.PluginResult __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.KeepCallback; } #pragma warning restore 0169 static Delegate cb_setKeepCallback_Z; #pragma warning disable 0169 static Delegate GetSetKeepCallback_ZHandler () { if (cb_setKeepCallback_Z == null) cb_setKeepCallback_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_SetKeepCallback_Z); return cb_setKeepCallback_Z; } static void n_SetKeepCallback_Z (IntPtr jnienv, IntPtr native__this, bool p0) { global::Org.Apache.Cordova.PluginResult __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.KeepCallback = p0; } #pragma warning restore 0169 static IntPtr id_getKeepCallback; static IntPtr id_setKeepCallback_Z; public virtual bool KeepCallback { // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/method[@name='getKeepCallback' and count(parameter)=0]" [Register ("getKeepCallback", "()Z", "GetGetKeepCallbackHandler")] get { if (id_getKeepCallback == IntPtr.Zero) id_getKeepCallback = JNIEnv.GetMethodID (class_ref, "getKeepCallback", "()Z"); if (GetType () == ThresholdType) return JNIEnv.CallBooleanMethod (Handle, id_getKeepCallback); else return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getKeepCallback", "()Z")); } // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/method[@name='setKeepCallback' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("setKeepCallback", "(Z)V", "GetSetKeepCallback_ZHandler")] set { if (id_setKeepCallback_Z == IntPtr.Zero) id_setKeepCallback_Z = JNIEnv.GetMethodID (class_ref, "setKeepCallback", "(Z)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setKeepCallback_Z, new JValue (value)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setKeepCallback", "(Z)V"), new JValue (value)); } } static Delegate cb_getMessage; #pragma warning disable 0169 static Delegate GetGetMessageHandler () { if (cb_getMessage == null) cb_getMessage = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetMessage); return cb_getMessage; } static IntPtr n_GetMessage (IntPtr jnienv, IntPtr native__this) { global::Org.Apache.Cordova.PluginResult __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Message); } #pragma warning restore 0169 static IntPtr id_getMessage; public virtual string Message { // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/method[@name='getMessage' and count(parameter)=0]" [Register ("getMessage", "()Ljava/lang/String;", "GetGetMessageHandler")] get { if (id_getMessage == IntPtr.Zero) id_getMessage = JNIEnv.GetMethodID (class_ref, "getMessage", "()Ljava/lang/String;"); if (GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getMessage), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getMessage", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } } static Delegate cb_getMessageType; #pragma warning disable 0169 static Delegate GetGetMessageTypeHandler () { if (cb_getMessageType == null) cb_getMessageType = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetMessageType); return cb_getMessageType; } static int n_GetMessageType (IntPtr jnienv, IntPtr native__this) { global::Org.Apache.Cordova.PluginResult __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.MessageType; } #pragma warning restore 0169 static IntPtr id_getMessageType; public virtual int MessageType { // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/method[@name='getMessageType' and count(parameter)=0]" [Register ("getMessageType", "()I", "GetGetMessageTypeHandler")] get { if (id_getMessageType == IntPtr.Zero) id_getMessageType = JNIEnv.GetMethodID (class_ref, "getMessageType", "()I"); if (GetType () == ThresholdType) return JNIEnv.CallIntMethod (Handle, id_getMessageType); else return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getMessageType", "()I")); } } static Delegate cb_getMultipartMessagesSize; #pragma warning disable 0169 static Delegate GetGetMultipartMessagesSizeHandler () { if (cb_getMultipartMessagesSize == null) cb_getMultipartMessagesSize = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetMultipartMessagesSize); return cb_getMultipartMessagesSize; } static int n_GetMultipartMessagesSize (IntPtr jnienv, IntPtr native__this) { global::Org.Apache.Cordova.PluginResult __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.MultipartMessagesSize; } #pragma warning restore 0169 static IntPtr id_getMultipartMessagesSize; public virtual int MultipartMessagesSize { // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/method[@name='getMultipartMessagesSize' and count(parameter)=0]" [Register ("getMultipartMessagesSize", "()I", "GetGetMultipartMessagesSizeHandler")] get { if (id_getMultipartMessagesSize == IntPtr.Zero) id_getMultipartMessagesSize = JNIEnv.GetMethodID (class_ref, "getMultipartMessagesSize", "()I"); if (GetType () == ThresholdType) return JNIEnv.CallIntMethod (Handle, id_getMultipartMessagesSize); else return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getMultipartMessagesSize", "()I")); } } static Delegate cb_getStrMessage; #pragma warning disable 0169 static Delegate GetGetStrMessageHandler () { if (cb_getStrMessage == null) cb_getStrMessage = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetStrMessage); return cb_getStrMessage; } static IntPtr n_GetStrMessage (IntPtr jnienv, IntPtr native__this) { global::Org.Apache.Cordova.PluginResult __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.StrMessage); } #pragma warning restore 0169 static IntPtr id_getStrMessage; public virtual string StrMessage { // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/method[@name='getStrMessage' and count(parameter)=0]" [Register ("getStrMessage", "()Ljava/lang/String;", "GetGetStrMessageHandler")] get { if (id_getStrMessage == IntPtr.Zero) id_getStrMessage = JNIEnv.GetMethodID (class_ref, "getStrMessage", "()Ljava/lang/String;"); if (GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getStrMessage), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getStrMessage", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } } static Delegate cb_getMultipartMessage_I; #pragma warning disable 0169 static Delegate GetGetMultipartMessage_IHandler () { if (cb_getMultipartMessage_I == null) cb_getMultipartMessage_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_GetMultipartMessage_I); return cb_getMultipartMessage_I; } static IntPtr n_GetMultipartMessage_I (IntPtr jnienv, IntPtr native__this, int p0) { global::Org.Apache.Cordova.PluginResult __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.GetMultipartMessage (p0)); } #pragma warning restore 0169 static IntPtr id_getMultipartMessage_I; // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/method[@name='getMultipartMessage' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("getMultipartMessage", "(I)Lorg/apache/cordova/PluginResult;", "GetGetMultipartMessage_IHandler")] public virtual global::Org.Apache.Cordova.PluginResult GetMultipartMessage (int p0) { if (id_getMultipartMessage_I == IntPtr.Zero) id_getMultipartMessage_I = JNIEnv.GetMethodID (class_ref, "getMultipartMessage", "(I)Lorg/apache/cordova/PluginResult;"); if (GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (JNIEnv.CallObjectMethod (Handle, id_getMultipartMessage_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getMultipartMessage", "(I)Lorg/apache/cordova/PluginResult;"), new JValue (p0)), JniHandleOwnership.TransferLocalRef); } static Delegate cb_getStatus; #pragma warning disable 0169 static Delegate GetGetStatusHandler () { if (cb_getStatus == null) cb_getStatus = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetStatus); return cb_getStatus; } static int n_GetStatus (IntPtr jnienv, IntPtr native__this) { global::Org.Apache.Cordova.PluginResult __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.GetStatus (); } #pragma warning restore 0169 static IntPtr id_getStatus; // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/method[@name='getStatus' and count(parameter)=0]" [Register ("getStatus", "()I", "GetGetStatusHandler")] public virtual int GetStatus () { if (id_getStatus == IntPtr.Zero) id_getStatus = JNIEnv.GetMethodID (class_ref, "getStatus", "()I"); if (GetType () == ThresholdType) return JNIEnv.CallIntMethod (Handle, id_getStatus); else return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getStatus", "()I")); } static Delegate cb_toCallbackString_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetToCallbackString_Ljava_lang_String_Handler () { if (cb_toCallbackString_Ljava_lang_String_ == null) cb_toCallbackString_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_ToCallbackString_Ljava_lang_String_); return cb_toCallbackString_Ljava_lang_String_; } static IntPtr n_ToCallbackString_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Apache.Cordova.PluginResult __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.NewString (__this.ToCallbackString (p0)); return __ret; } #pragma warning restore 0169 static IntPtr id_toCallbackString_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/method[@name='toCallbackString' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("toCallbackString", "(Ljava/lang/String;)Ljava/lang/String;", "GetToCallbackString_Ljava_lang_String_Handler")] public virtual string ToCallbackString (string p0) { if (id_toCallbackString_Ljava_lang_String_ == IntPtr.Zero) id_toCallbackString_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "toCallbackString", "(Ljava/lang/String;)Ljava/lang/String;"); IntPtr native_p0 = JNIEnv.NewString (p0); string __ret; if (GetType () == ThresholdType) __ret = JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_toCallbackString_Ljava_lang_String_, new JValue (native_p0)), JniHandleOwnership.TransferLocalRef); else __ret = JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "toCallbackString", "(Ljava/lang/String;)Ljava/lang/String;"), new JValue (native_p0)), JniHandleOwnership.TransferLocalRef); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static Delegate cb_toErrorCallbackString_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetToErrorCallbackString_Ljava_lang_String_Handler () { if (cb_toErrorCallbackString_Ljava_lang_String_ == null) cb_toErrorCallbackString_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_ToErrorCallbackString_Ljava_lang_String_); return cb_toErrorCallbackString_Ljava_lang_String_; } static IntPtr n_ToErrorCallbackString_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Apache.Cordova.PluginResult __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.NewString (__this.ToErrorCallbackString (p0)); return __ret; } #pragma warning restore 0169 static IntPtr id_toErrorCallbackString_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/method[@name='toErrorCallbackString' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("toErrorCallbackString", "(Ljava/lang/String;)Ljava/lang/String;", "GetToErrorCallbackString_Ljava_lang_String_Handler")] public virtual string ToErrorCallbackString (string p0) { if (id_toErrorCallbackString_Ljava_lang_String_ == IntPtr.Zero) id_toErrorCallbackString_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "toErrorCallbackString", "(Ljava/lang/String;)Ljava/lang/String;"); IntPtr native_p0 = JNIEnv.NewString (p0); string __ret; if (GetType () == ThresholdType) __ret = JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_toErrorCallbackString_Ljava_lang_String_, new JValue (native_p0)), JniHandleOwnership.TransferLocalRef); else __ret = JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "toErrorCallbackString", "(Ljava/lang/String;)Ljava/lang/String;"), new JValue (native_p0)), JniHandleOwnership.TransferLocalRef); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static Delegate cb_toSuccessCallbackString_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetToSuccessCallbackString_Ljava_lang_String_Handler () { if (cb_toSuccessCallbackString_Ljava_lang_String_ == null) cb_toSuccessCallbackString_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_ToSuccessCallbackString_Ljava_lang_String_); return cb_toSuccessCallbackString_Ljava_lang_String_; } static IntPtr n_ToSuccessCallbackString_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Apache.Cordova.PluginResult __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.NewString (__this.ToSuccessCallbackString (p0)); return __ret; } #pragma warning restore 0169 static IntPtr id_toSuccessCallbackString_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginResult']/method[@name='toSuccessCallbackString' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("toSuccessCallbackString", "(Ljava/lang/String;)Ljava/lang/String;", "GetToSuccessCallbackString_Ljava_lang_String_Handler")] public virtual string ToSuccessCallbackString (string p0) { if (id_toSuccessCallbackString_Ljava_lang_String_ == IntPtr.Zero) id_toSuccessCallbackString_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "toSuccessCallbackString", "(Ljava/lang/String;)Ljava/lang/String;"); IntPtr native_p0 = JNIEnv.NewString (p0); string __ret; if (GetType () == ThresholdType) __ret = JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_toSuccessCallbackString_Ljava_lang_String_, new JValue (native_p0)), JniHandleOwnership.TransferLocalRef); else __ret = JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "toSuccessCallbackString", "(Ljava/lang/String;)Ljava/lang/String;"), new JValue (native_p0)), JniHandleOwnership.TransferLocalRef); JNIEnv.DeleteLocalRef (native_p0); return __ret; } } }
//////////////////////////////////////////////////////////////////////////////// // // // MIT X11 license, Copyright (c) 2005-2006 by: // // // // Authors: // // Michael Dominic K. <michaldominik@gmail.com> // // // // Permission is hereby granted, free of charge, to any person obtaining a // // copy of this software and associated documentation files (the "Software"), // // to deal in the Software without restriction, including without limitation // // the rights to use, copy, modify, merge, publish, distribute, sublicense, // // and/or sell copies of the Software, and to permit persons to whom the // // Software is furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included // // in all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // // USE OR OTHER DEALINGS IN THE SOFTWARE. // // // //////////////////////////////////////////////////////////////////////////////// namespace Diva.Core { using System; using Widgets; using System.Xml; using Util; using System.Collections.Generic; using System.Collections; using Basics; public class OpenerTask : Task, IBoilProvider { // Private structs //////////////////////////////////////////// struct ObjectInfo { public ObjectContainer Container; public int[] Depends; public string SystemType; public int RefId; /* CONSTRUCTOR */ public ObjectInfo (ObjectContainer container) { Container = container; Depends = container.Depends.ToArray (); SystemType = container.SystemType; RefId = container.RefId; } public override string ToString () { return String.Format ("Type: {0} Deps count: {1} Id: {2}", SystemType, Depends.Length, RefId); } public bool IsUnBoilable (IBoilProvider provider) { if (Depends.Length == 0) return true; foreach (int id in Depends) if (! (provider.Contains (id))) return false; return true; } } // Enums ////////////////////////////////////////////////////// enum OpenerTaskStep { Init, Header, ProjectInfoRead, ObjectListRead, ObjectListParse, ObjectListUnBoil, FindRoots, Finished }; // Fields ///////////////////////////////////////////////////// string fileName; // Filename we're reading XmlDocument xmlDocument; // Our document //XmlNode projectInfoNode; // <projectinfo> node IEnumerator objectsEnumerator; // Enumerator List <ObjectInfo> objectsList; // Objects list ObjectListContainer objectListContainer; OpenerTaskStep currentStep; // Our current step Dictionary <int, object> idToObject; // Id -> object Dictionary <object, int> objectToId; // Object -> Id string projectName = String.Empty; string projectDirectory = String.Empty; TagList projectTagList; StuffList projectStuffList; TrackList projectTrackList; ClipList projectClipList; MediaItemList projectMediaItemList; Commander projectCommander; Gdv.Pipeline projectPipeline; Gdv.ProjectFormat projectFormat; // Properties ///////////////////////////////////////////////// public string ProjectName { get { return projectName; } } public string ProjectDirectory { get { return projectDirectory; } } public TagList ProjectTagList { get { return projectTagList; } } public StuffList ProjectStuffList { get { return projectStuffList; } } public TrackList ProjectTrackList { get { return projectTrackList; } } public ClipList ProjectClipList { get { return projectClipList; } } public MediaItemList ProjectMediaItemList { get { return projectMediaItemList; } } public Commander ProjectCommander { get { return projectCommander; } } public Gdv.Pipeline ProjectPipeline { get { return projectPipeline; } } public Gdv.ProjectFormat ProjectFormat { get { return projectFormat; } } // Public methods ///////////////////////////////////////////// /* CONSTRUCTOR */ public OpenerTask (string fileName) { this.fileName = fileName; } public override void Reset () { objectToId = new Dictionary <object, int> (); idToObject = new Dictionary <int, object> (); xmlDocument = null; //projectInfoNode = null; currentStep = OpenerTaskStep.Init; base.Reset (); } public int GetIdForObject (object o) { return objectToId [o]; } public object GetObjectForId (int id) { return idToObject [id]; } public bool Contains (int id) { return idToObject.ContainsKey (id); } // Private methods //////////////////////////////////////////// protected override TaskStatus ExecuteStep (int s) { bool cont = true; // Main switch (currentStep) { case OpenerTaskStep.Init: objectsList = new List <ObjectInfo> (); xmlDocument = new XmlDocument (); xmlDocument.Load (fileName); currentStep = OpenerTaskStep.Header; break; case OpenerTaskStep.Header: //ReadHeader (); currentStep = OpenerTaskStep.ProjectInfoRead; break; case OpenerTaskStep.ProjectInfoRead: foreach (XmlNode node in xmlDocument.DocumentElement.ChildNodes) if (node.Name == "projectinfo") ResolveProjectInfoNode (node); // FIXME: Fail if not found/not resolved currentStep = OpenerTaskStep.ObjectListRead; break; case OpenerTaskStep.ObjectListRead: foreach (XmlNode node in xmlDocument.DocumentElement.ChildNodes) if (node.Name == "objectlist") objectListContainer = (ObjectListContainer) DataFactory.MakeDataElement (node as XmlElement); if (objectListContainer == null) throw new Exception ("ObjectListContainer not found!"); currentStep = OpenerTaskStep.ObjectListParse; break; case OpenerTaskStep.ObjectListParse: bool flush = EnumerateSomeObjects (); if (flush) currentStep = OpenerTaskStep.ObjectListUnBoil; break; case OpenerTaskStep.ObjectListUnBoil: bool done = UnBoilSomeObjects (); if (done) currentStep = OpenerTaskStep.FindRoots; break; case OpenerTaskStep.FindRoots: projectTrackList = (TrackList) FindRoot ("tracklist"); projectTagList = (TagList) FindRoot ("taglist"); projectStuffList = (StuffList) FindRoot ("stufflist"); projectClipList = (ClipList) FindRoot ("cliplist"); projectMediaItemList = (MediaItemList) FindRoot ("mediaitemlist"); projectPipeline = (Gdv.Pipeline) FindRoot ("pipeline"); projectCommander = (Commander) FindRoot ("commander"); projectFormat = (Gdv.ProjectFormat) FindRoot ("projectformat"); currentStep = OpenerTaskStep.Finished; break; case OpenerTaskStep.Finished: cont = false; break; default: break; } // Post if (cont) return TaskStatus.Running; else return TaskStatus.Done; } /* void ReadHeader () { // FIXME: Read all the attributes from the <divaproject> element }*/ void ResolveProjectInfoNode (XmlNode node) { foreach (XmlNode childNode in node) { switch (childNode.Name) { case "name": projectName = childNode.FirstChild.Value; break; case "directory": projectDirectory = childNode.FirstChild.Value; break; // FIXME: Duration etc. } } } bool EnumerateSomeObjects () { if (objectsEnumerator == null) objectsEnumerator = objectListContainer.FindAllObjects ().GetEnumerator (); for (int i = 0; i < 10; i++) { if (objectsEnumerator.MoveNext () == false) return true; ObjectContainer container = (ObjectContainer) objectsEnumerator.Current; ObjectInfo newInfo = new ObjectInfo (container); objectsList.Add (newInfo); } return false; } ObjectInfo GetNextCandidate () { foreach (ObjectInfo objInfo in objectsList) if (objInfo.IsUnBoilable (this)) return objInfo; throw new Exception ("FIXME: No more unboilable objects found. Recursive?"); } bool UnBoilSomeObjects () { for (int i = 0; i < 5; i++) { // All unboiled if (objectsList.Count == 0) return true; ObjectInfo objInfo = GetNextCandidate (); object o = BoilFactory.UnBoil (objInfo.Container, this); objectsList.Remove (objInfo); // Add idToObject [objInfo.RefId] = o; objectToId [o] = objInfo.RefId; } return false; } object FindRoot (string rootString) { ObjectContainer container = objectListContainer.FindObjectContainer (rootString); return idToObject [container.RefId]; } } }
//----------------------------------------------------------------------- // <copyright file="Transfer.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Akka.Actor; using Akka.Pattern; namespace Akka.Streams.Implementation { public class SubReceive { private Receive _currentReceive; public SubReceive(Receive initial) { _currentReceive = initial; } public Receive CurrentReceive => _currentReceive; public void Become(Receive receive) => _currentReceive = receive; } internal interface IInputs { TransferState NeedsInput { get; } TransferState NeedsInputOrComplete { get; } object DequeueInputElement(); SubReceive SubReceive { get; } void Cancel(); bool IsClosed { get; } bool IsOpen { get; } bool AreInputsDepleted { get; } bool AreInputsAvailable { get; } } internal static class DefaultInputTransferStates { public static TransferState NeedsInput(IInputs inputs) => new LambdaTransferState(() => inputs.AreInputsAvailable, () => inputs.AreInputsDepleted); public static TransferState NeedsInputOrComplete(IInputs inputs) => new LambdaTransferState(() => inputs.AreInputsAvailable || inputs.AreInputsDepleted, () => false); } internal interface IOutputs { SubReceive SubReceive { get; } TransferState NeedsDemand { get; } TransferState NeedsDemandOrCancel { get; } long DemandCount { get; } bool IsDemandAvailable { get; } void EnqueueOutputElement(object element); void Complete(); void Cancel(); void Error(Exception e); bool IsClosed { get; } bool IsOpen { get; } } internal static class DefaultOutputTransferStates { public static TransferState NeedsDemand(IOutputs outputs) => new LambdaTransferState(() => outputs.IsDemandAvailable, () => outputs.IsClosed); public static TransferState NeedsDemandOrCancel(IOutputs outputs) => new LambdaTransferState(() => outputs.IsDemandAvailable || outputs.IsClosed, () => false); } public abstract class TransferState { public abstract bool IsReady { get; } public abstract bool IsCompleted { get; } public bool IsExecutable => IsReady && !IsCompleted; public TransferState Or(TransferState other) => new LambdaTransferState(() => IsReady || other.IsReady, () => IsCompleted && other.IsCompleted); public TransferState And(TransferState other) => new LambdaTransferState(() => IsReady && other.IsReady, () => IsCompleted || other.IsCompleted); } internal sealed class LambdaTransferState : TransferState { private readonly Func<bool> _isReady; private readonly Func<bool> _isCompleted; public override bool IsReady => _isReady(); public override bool IsCompleted => _isCompleted(); public LambdaTransferState(Func<bool> isReady, Func<bool> isCompleted) { _isReady = isReady; _isCompleted = isCompleted; } } internal sealed class Completed : TransferState { public static readonly Completed Instance = new Completed(); private Completed() { } public override bool IsReady => false; public override bool IsCompleted => true; } internal sealed class NotInitialized : TransferState { public static readonly NotInitialized Instance = new NotInitialized(); private NotInitialized() { } public override bool IsReady => false; public override bool IsCompleted => false; } internal class WaitingForUpstreamSubscription : TransferState { public readonly int Remaining; public readonly TransferPhase AndThen; public WaitingForUpstreamSubscription(int remaining, TransferPhase andThen) { Remaining = remaining; AndThen = andThen; } public override bool IsReady => false; public override bool IsCompleted => false; } internal sealed class Always : TransferState { public static readonly Always Instance = new Always(); private Always() { } public override bool IsReady => true; public override bool IsCompleted => false; } public struct TransferPhase { public readonly TransferState Precondition; public readonly Action Action; public TransferPhase(TransferState precondition, Action action) : this() { Precondition = precondition; Action = action; } } public interface IPump { TransferState TransferState { get; set; } Action CurrentAction { get; set; } bool IsPumpFinished { get; } void InitialPhase(int waitForUpstream, TransferPhase andThen); void WaitForUpstream(int waitForUpstream); void GotUpstreamSubscription(); void NextPhase(TransferPhase phase); // Exchange input buffer elements and output buffer "requests" until one of them becomes empty. // Generate upstream requestMore for every Nth consumed input element void Pump(); void PumpFailed(Exception e); void PumpFinished(); } internal abstract class PumpBase : IPump { protected PumpBase() { TransferState = NotInitialized.Instance; CurrentAction = () => { throw new IllegalStateException("Pump has not been initialized with a phase"); }; } public TransferState TransferState { get; set; } public Action CurrentAction { get; set; } public bool IsPumpFinished => TransferState.IsCompleted; public void InitialPhase(int waitForUpstream, TransferPhase andThen) => Pumps.InitialPhase(this, waitForUpstream, andThen); public void WaitForUpstream(int waitForUpstream) => Pumps.WaitForUpstream(this, waitForUpstream); public void GotUpstreamSubscription() => Pumps.GotUpstreamSubscription(this); public void NextPhase(TransferPhase phase) => Pumps.NextPhase(this, phase); public void Pump() => Pumps.Pump(this); public abstract void PumpFailed(Exception e); public abstract void PumpFinished(); } internal static class Pumps { public static void Init(this IPump self) { self.TransferState = NotInitialized.Instance; self.CurrentAction = () => { throw new IllegalStateException("Pump has not been initialized with a phase"); }; } public static readonly TransferPhase CompletedPhase = new TransferPhase(Completed.Instance, () => { throw new IllegalStateException("The action of completed phase must never be executed"); }); public static void InitialPhase(this IPump self, int waitForUpstream, TransferPhase andThen) { if (waitForUpstream < 1) throw new ArgumentException($"WaitForUpstream must be >= 1 (was {waitForUpstream})"); if(self.TransferState != NotInitialized.Instance) throw new IllegalStateException($"Initial state expected NotInitialized, but got {self.TransferState}"); self.TransferState = new WaitingForUpstreamSubscription(waitForUpstream, andThen); } public static void WaitForUpstream(this IPump self, int waitForUpstream) { if(waitForUpstream < 1) throw new ArgumentException($"WaitForUpstream must be >= 1 (was {waitForUpstream})"); self.TransferState = new WaitingForUpstreamSubscription(waitForUpstream, new TransferPhase(self.TransferState, self.CurrentAction)); } public static void GotUpstreamSubscription(this IPump self) { if (self.TransferState is WaitingForUpstreamSubscription) { var t = (WaitingForUpstreamSubscription) self.TransferState; if (t.Remaining == 1) { self.TransferState = t.AndThen.Precondition; self.CurrentAction = t.AndThen.Action; } else self.TransferState = new WaitingForUpstreamSubscription(t.Remaining - 1, t.AndThen); } self.Pump(); } public static void NextPhase(this IPump self, TransferPhase phase) { if (self.TransferState is WaitingForUpstreamSubscription) { var w = (WaitingForUpstreamSubscription) self.TransferState; self.TransferState = new WaitingForUpstreamSubscription(w.Remaining, phase); } else { self.TransferState = phase.Precondition; self.CurrentAction = phase.Action; } } public static bool IsPumpFinished(this IPump self) => self.TransferState.IsCompleted; public static void Pump(this IPump self) { try { while (self.TransferState.IsExecutable) self.CurrentAction(); } catch (Exception e) { self.PumpFailed(e); } if(self.IsPumpFinished) self.PumpFinished(); } } }
//Copyright (C) 2005 Richard J. Northedge // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //This file is based on the Heap.java source file found in the //original java implementation of OpenNLP. That source file contains the following header: //Copyright (C) 2005 Thomas Morton // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. using System; using System.Collections.Generic; namespace OpenNLP.Tools.Util { /// <summary> /// This class implements the heap interface using a generic List as the underlying /// data structure. This heap allows values which are equals to be inserted, however /// the order in which they are extracted is arbitrary. /// </summary> public class ListHeap<T> : IHeap<T>, IEnumerable<T> { private List<T> mList; private readonly IComparer<T> mComparer; private readonly int mSize; private T mMax; /// <summary> /// True if the heap is empty. /// </summary> public virtual bool IsEmpty { get { return (mList.Count == 0); } } /// <summary> /// Creates a new heap with the specified size using the sorted based on the /// specified comparator. /// </summary> /// <param name="size"> /// The size of the heap. /// </param> /// <param name="comparer"> /// The comparer to be used to sort heap elements. /// </param> public ListHeap(int size, IComparer<T> comparer) { mSize = size; mComparer = comparer; mList = new List<T>(size); } /// <summary> /// Createa a new heap of the specified size. /// </summary> /// <param name="size"> /// The size of the new heap. /// </param> public ListHeap(int size) : this(size, null) { } private int ParentIndex(int index) { return (index - 1) / 2; } private int LeftIndex(int index) { return (index + 1) * 2 - 1; } private int RightIndex(int index) { return (index + 1) * 2; } /// <summary> /// The size of the heap. /// </summary> public virtual int Size { get { return mList.Count; } set { if (value > mList.Count) { return ; } else { var newList = new List<T>(value); for (int currentItem = 0; currentItem < value; currentItem++) { newList.Add(this.Extract()); } mList = newList; } } } private void Swap(int firstIndex, int secondIndex) { T firstObject = mList[firstIndex]; T secondObject = mList[secondIndex]; mList[secondIndex] = firstObject; mList[firstIndex] = secondObject; } private bool LessThan(T firstObject, T secondObject) { if (mComparer != null) { return (mComparer.Compare(firstObject, secondObject) < 0); } else { return (((IComparable) firstObject).CompareTo(secondObject) < 0); } } private bool GreaterThan(T firstObject, T secondObject) { if (mComparer != null) { return (mComparer.Compare(firstObject, secondObject) > 0); } else { return (((IComparable) firstObject).CompareTo(secondObject) > 0); } } private void Heapify(int index) { while (true) { int left = LeftIndex(index); int right = RightIndex(index); int smallest; if (left < mList.Count && LessThan(mList[left], mList[index])) { smallest = left; } else { smallest = index; } if (right < mList.Count && LessThan(mList[right], mList[smallest])) { smallest = right; } if (smallest != index) { Swap(smallest, index); index = smallest; } else { break; } } } public virtual T Extract() { if (mList.Count == 0) { throw new NotSupportedException("Heap Underflow"); } T mMax = mList[0]; int last = mList.Count - 1; if (last != 0) { mList[0] = mList[last]; mList.RemoveAt(last); Heapify(0); } else { mList.RemoveAt(last); } return mMax; } /// <summary> /// Resets the heap size to its original value. /// </summary> public virtual void ResetSize() { this.Size = mSize; } /// <summary> /// Gets the object on top of the heap. /// </summary> public virtual T Top { get { if (mList.Count == 0) { throw new NotSupportedException("Heap Underflow"); } return (mList[0]); } } public virtual void Add(T item) { /* keep track of min to prevent unnecessary insertion */ if (mMax == null) { mMax = item; } else if (GreaterThan(item, mMax)) { if (mList.Count < mSize) { mMax = item; } else { return; } } mList.Add(item); int index = mList.Count - 1; //percolate new node to correct position in heap. while (index > 0 && GreaterThan(mList[ParentIndex(index)], item)) { mList[index] = mList[ParentIndex(index)]; index = ParentIndex(index); } mList[index] = item; } public virtual void Clear() { mList.Clear(); } public virtual System.Collections.IEnumerator GetEnumerator() { return (mList.GetEnumerator()); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return (mList.GetEnumerator()); } } }
//============================================================================= // System : Sandcastle Help File Builder Plug-Ins // File : CompletionNotificationConfigDlg.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 03/09/2008 // Note : Copyright 2007-2008, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains a form that is used to configure the settings for the // Completion Notification plug-in. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.5.2.0 09/10/2007 EFW Created the code // 1.6.0.6 03/09/2008 EFW Added support for log file XSL transform //============================================================================= using System; using System.Collections; using System.ComponentModel; using System.Globalization; using System.IO; using System.Windows.Forms; using System.Xml; using System.Xml.XPath; using SandcastleBuilder.Utils; namespace SandcastleBuilder.PlugIns { /// <summary> /// This form is used to configure the settings for the /// <see cref="CompletionNotificationPlugIn"/>. /// </summary> internal partial class CompletionNotificationConfigDlg : Form { private XmlDocument config; // The configuration /// <summary> /// This is used to return the configuration information /// </summary> public string Configuration { get { return config.OuterXml; } } /// <summary> /// Constructor /// </summary> /// <param name="currentConfig">The current XML configuration /// XML fragment</param> public CompletionNotificationConfigDlg(string currentConfig) { XPathNavigator navigator, root, node; UserCredentials credentials; string attrValue; int port; InitializeComponent(); lnkCodePlexSHFB.Links[0].LinkData = "http://SHFB.CodePlex.com"; // Load the current settings config = new XmlDocument(); config.LoadXml(currentConfig); navigator = config.CreateNavigator(); root = navigator.SelectSingleNode("configuration"); if(root.IsEmptyElement) return; node = root.SelectSingleNode("smtpServer"); if(node != null) { txtSmtpServer.Text = node.GetAttribute("host", String.Empty); attrValue = node.GetAttribute("port", String.Empty); if(attrValue.Length != 0) if(Int32.TryParse(attrValue, out port)) udcSmtpPort.Value = port; } credentials = UserCredentials.FromXPathNavigator(root); chkUseDefaultCredentials.Checked = credentials.UseDefaultCredentials; txtUserName.Text = credentials.UserName; txtPassword.Text = credentials.Password; node = root.SelectSingleNode("fromEMail"); if(node != null) txtFromEMail.Text = node.GetAttribute("address", String.Empty); node = root.SelectSingleNode("successEMail"); if(node != null) { txtSuccessEMailAddress.Text = node.GetAttribute("address", String.Empty); attrValue = node.GetAttribute("attachLog", string.Empty); if(attrValue.Length != 0) chkAttachLogFileOnSuccess.Checked = Convert.ToBoolean(attrValue, CultureInfo.InvariantCulture); } node = root.SelectSingleNode("failureEMail"); if(node != null) { txtFailureEMailAddress.Text = node.GetAttribute("address", String.Empty); attrValue = node.GetAttribute("attachLog", String.Empty); if(attrValue.Length != 0) chkAttachLogFileOnFailure.Checked = Convert.ToBoolean(attrValue, CultureInfo.InvariantCulture); } node = root.SelectSingleNode("xslTransform"); if(node != null) txtXSLTransform.Text = node.GetAttribute("filename", String.Empty); } /// <summary> /// Close without saving /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } /// <summary> /// Go to the CodePlex home page of the Sandcastle Help File Builder /// project. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void lnkCodePlexSHFB_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { System.Diagnostics.Process.Start((string)e.Link.LinkData); } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); MessageBox.Show("Unable to launch link target. " + "Reason: " + ex.Message, Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } /// <summary> /// Enable or disable the user name and password controls based on /// the Default Credentials check state. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void chkUseDefaultCredentials_CheckedChanged(object sender, EventArgs e) { txtUserName.Enabled = txtPassword.Enabled = !chkUseDefaultCredentials.Checked; } /// <summary> /// Validate the configuration and save it /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnOK_Click(object sender, EventArgs e) { XmlAttribute attr; XmlNode root, node; UserCredentials credentials; bool isValid = true; txtSmtpServer.Text = txtSmtpServer.Text.Trim(); txtUserName.Text = txtUserName.Text.Trim(); txtPassword.Text = txtPassword.Text.Trim(); txtSuccessEMailAddress.Text = txtSuccessEMailAddress.Text.Trim(); txtFailureEMailAddress.Text = txtFailureEMailAddress.Text.Trim(); txtXSLTransform.Text = txtXSLTransform.Text.Trim(); epErrors.Clear(); if(!chkUseDefaultCredentials.Checked) { if(txtUserName.Text.Length == 0) { epErrors.SetError(txtUserName, "A user name is " + "required if not using default credentials"); isValid = false; } if(txtPassword.Text.Length == 0) { epErrors.SetError(txtPassword, "A password is " + "required if not using default credentials"); isValid = false; } } if(txtFailureEMailAddress.Text.Length == 0) { epErrors.SetError(txtFailureEMailAddress, "A failure " + "e-mail address is required"); isValid = false; } if(!isValid) return; // Store the changes root = config.SelectSingleNode("configuration"); node = root.SelectSingleNode("smtpServer"); if(node == null) { node = config.CreateNode(XmlNodeType.Element, "smtpServer", null); root.AppendChild(node); attr = config.CreateAttribute("host"); node.Attributes.Append(attr); attr = config.CreateAttribute("port"); node.Attributes.Append(attr); } node.Attributes["host"].Value = txtSmtpServer.Text; node.Attributes["port"].Value = udcSmtpPort.Value.ToString( CultureInfo.InvariantCulture); credentials = new UserCredentials(chkUseDefaultCredentials.Checked, txtUserName.Text, txtPassword.Text); credentials.ToXml(config, root); node = root.SelectSingleNode("fromEMail"); if(node == null) { node = config.CreateNode(XmlNodeType.Element, "fromEMail", null); root.AppendChild(node); attr = config.CreateAttribute("address"); node.Attributes.Append(attr); } node.Attributes["address"].Value = txtFromEMail.Text; node = root.SelectSingleNode("successEMail"); if(node == null) { node = config.CreateNode(XmlNodeType.Element, "successEMail", null); root.AppendChild(node); attr = config.CreateAttribute("address"); node.Attributes.Append(attr); attr = config.CreateAttribute("attachLog"); node.Attributes.Append(attr); } node.Attributes["address"].Value = txtSuccessEMailAddress.Text; node.Attributes["attachLog"].Value = chkAttachLogFileOnSuccess.Checked.ToString().ToLower( CultureInfo.InvariantCulture); node = root.SelectSingleNode("failureEMail"); if(node == null) { node = config.CreateNode(XmlNodeType.Element, "failureEMail", null); root.AppendChild(node); attr = config.CreateAttribute("address"); node.Attributes.Append(attr); attr = config.CreateAttribute("attachLog"); node.Attributes.Append(attr); } node.Attributes["address"].Value = txtFailureEMailAddress.Text; node.Attributes["attachLog"].Value = chkAttachLogFileOnFailure.Checked.ToString().ToLower( CultureInfo.InvariantCulture); node = root.SelectSingleNode("xslTransform"); if(node == null) { node = config.CreateNode(XmlNodeType.Element, "xslTransform", null); root.AppendChild(node); attr = config.CreateAttribute("filename"); node.Attributes.Append(attr); } node.Attributes["filename"].Value = txtXSLTransform.Text; this.DialogResult = DialogResult.OK; this.Close(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.Contracts; using System.Globalization; using System.Text; namespace System.Net.Http.Headers { public class ContentRangeHeaderValue : ICloneable { private string _unit; private long? _from; private long? _to; private long? _length; public string Unit { get { return _unit; } set { HeaderUtilities.CheckValidToken(value, "value"); _unit = value; } } public long? From { get { return _from; } } public long? To { get { return _to; } } public long? Length { get { return _length; } } public bool HasLength // e.g. "Content-Range: bytes 12-34/*" { get { return _length != null; } } public bool HasRange // e.g. "Content-Range: bytes */1234" { get { return _from != null; } } public ContentRangeHeaderValue(long from, long to, long length) { // Scenario: "Content-Range: bytes 12-34/5678" if (length < 0) { throw new ArgumentOutOfRangeException("length"); } if ((to < 0) || (to > length)) { throw new ArgumentOutOfRangeException("to"); } if ((from < 0) || (from > to)) { throw new ArgumentOutOfRangeException("from"); } _from = from; _to = to; _length = length; _unit = HeaderUtilities.BytesUnit; } public ContentRangeHeaderValue(long length) { // Scenario: "Content-Range: bytes */1234" if (length < 0) { throw new ArgumentOutOfRangeException("length"); } _length = length; _unit = HeaderUtilities.BytesUnit; } public ContentRangeHeaderValue(long from, long to) { // Scenario: "Content-Range: bytes 12-34/*" if (to < 0) { throw new ArgumentOutOfRangeException("to"); } if ((from < 0) || (from > to)) { throw new ArgumentOutOfRangeException("from"); } _from = from; _to = to; _unit = HeaderUtilities.BytesUnit; } private ContentRangeHeaderValue() { } private ContentRangeHeaderValue(ContentRangeHeaderValue source) { Contract.Requires(source != null); _from = source._from; _to = source._to; _length = source._length; _unit = source._unit; } public override bool Equals(object obj) { ContentRangeHeaderValue other = obj as ContentRangeHeaderValue; if (other == null) { return false; } return ((_from == other._from) && (_to == other._to) && (_length == other._length) && string.Equals(_unit, other._unit, StringComparison.OrdinalIgnoreCase)); } public override int GetHashCode() { int result = StringComparer.OrdinalIgnoreCase.GetHashCode(_unit); if (HasRange) { result = result ^ _from.GetHashCode() ^ _to.GetHashCode(); } if (HasLength) { result = result ^ _length.GetHashCode(); } return result; } public override string ToString() { StringBuilder sb = new StringBuilder(_unit); sb.Append(' '); if (HasRange) { sb.Append(_from.Value.ToString(NumberFormatInfo.InvariantInfo)); sb.Append('-'); sb.Append(_to.Value.ToString(NumberFormatInfo.InvariantInfo)); } else { sb.Append('*'); } sb.Append('/'); if (HasLength) { sb.Append(_length.Value.ToString(NumberFormatInfo.InvariantInfo)); } else { sb.Append('*'); } return sb.ToString(); } public static ContentRangeHeaderValue Parse(string input) { int index = 0; return (ContentRangeHeaderValue)GenericHeaderParser.ContentRangeParser.ParseValue(input, null, ref index); } public static bool TryParse(string input, out ContentRangeHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (GenericHeaderParser.ContentRangeParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (ContentRangeHeaderValue)output; return true; } return false; } internal static int GetContentRangeLength(string input, int startIndex, out object parsedValue) { Contract.Requires(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Parse the unit string: <unit> in '<unit> <from>-<to>/<length>' int unitLength = HttpRuleParser.GetTokenLength(input, startIndex); if (unitLength == 0) { return 0; } string unit = input.Substring(startIndex, unitLength); int current = startIndex + unitLength; int separatorLength = HttpRuleParser.GetWhitespaceLength(input, current); if (separatorLength == 0) { return 0; } current = current + separatorLength; if (current == input.Length) { return 0; } // Read range values <from> and <to> in '<unit> <from>-<to>/<length>' int fromStartIndex = current; int fromLength = 0; int toStartIndex = 0; int toLength = 0; if (!TryGetRangeLength(input, ref current, out fromLength, out toStartIndex, out toLength)) { return 0; } // After the range is read we expect the length separator '/' if ((current == input.Length) || (input[current] != '/')) { return 0; } current++; // Skip '/' separator current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (current == input.Length) { return 0; } // We may not have a length (e.g. 'bytes 1-2/*'). But if we do, parse the length now. int lengthStartIndex = current; int lengthLength = 0; if (!TryGetLengthLength(input, ref current, out lengthLength)) { return 0; } if (!TryCreateContentRange(input, unit, fromStartIndex, fromLength, toStartIndex, toLength, lengthStartIndex, lengthLength, out parsedValue)) { return 0; } return current - startIndex; } private static bool TryGetLengthLength(string input, ref int current, out int lengthLength) { lengthLength = 0; if (input[current] == '*') { current++; } else { // Parse length value: <length> in '<unit> <from>-<to>/<length>' lengthLength = HttpRuleParser.GetNumberLength(input, current, false); if ((lengthLength == 0) || (lengthLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + lengthLength; } current = current + HttpRuleParser.GetWhitespaceLength(input, current); return true; } private static bool TryGetRangeLength(string input, ref int current, out int fromLength, out int toStartIndex, out int toLength) { fromLength = 0; toStartIndex = 0; toLength = 0; // Check if we have a value like 'bytes */133'. If yes, skip the range part and continue parsing the // length separator '/'. if (input[current] == '*') { current++; } else { // Parse first range value: <from> in '<unit> <from>-<to>/<length>' fromLength = HttpRuleParser.GetNumberLength(input, current, false); if ((fromLength == 0) || (fromLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + fromLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // Afer the first value, the '-' character must follow. if ((current == input.Length) || (input[current] != '-')) { // We need a '-' character otherwise this can't be a valid range. return false; } current++; // skip the '-' character current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (current == input.Length) { return false; } // Parse second range value: <to> in '<unit> <from>-<to>/<length>' toStartIndex = current; toLength = HttpRuleParser.GetNumberLength(input, current, false); if ((toLength == 0) || (toLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + toLength; } current = current + HttpRuleParser.GetWhitespaceLength(input, current); return true; } private static bool TryCreateContentRange(string input, string unit, int fromStartIndex, int fromLength, int toStartIndex, int toLength, int lengthStartIndex, int lengthLength, out object parsedValue) { parsedValue = null; long from = 0; if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(fromStartIndex, fromLength), out from)) { return false; } long to = 0; if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(toStartIndex, toLength), out to)) { return false; } // 'from' must not be greater than 'to' if ((fromLength > 0) && (toLength > 0) && (from > to)) { return false; } long length = 0; if ((lengthLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(lengthStartIndex, lengthLength), out length)) { return false; } // 'from' and 'to' must be less than 'length' if ((toLength > 0) && (lengthLength > 0) && (to >= length)) { return false; } ContentRangeHeaderValue result = new ContentRangeHeaderValue(); result._unit = unit; if (fromLength > 0) { result._from = from; result._to = to; } if (lengthLength > 0) { result._length = length; } parsedValue = result; return true; } object ICloneable.Clone() { return new ContentRangeHeaderValue(this); } } }
/////////////////////////////////////////////////////////////////////////// // Description: Data Access class for the table 'Currency' // Generated by LLBLGen v1.21.2003.712 Final on: 19 September 2006, 13:10:33 // Because the Base Class already implements IDispose, this class doesn't. /////////////////////////////////////////////////////////////////////////// using System; using System.Data; using System.Data.SqlTypes; using System.Data.SqlClient; namespace BkNet.DataAccess { /// <summary> /// Purpose: Data Access class for the table 'Currency'. /// </summary> public class Currency : DBInteractionBase { #region Class Member Declarations private SqlBoolean _published; private SqlDateTime _createdDate, _updatedDate; private SqlInt32 _createdBy, _updatedBy, _ordering, _id; private SqlString _kode, _nama, _keterangan; #endregion /// <summary> /// Purpose: Class constructor. /// </summary> public Currency() { // Nothing for now. } /// <summary> /// Purpose: IsExist method. This method will check Exsisting data from database. /// Addes By Ekitea On 19 September 2006 /// </summary> /// <returns></returns> public bool IsExist() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[Currency_IsExist]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode)); cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama)); cmdToExecute.Parameters.Add(new SqlParameter("@IsExist", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, false, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); int IsExist = int.Parse(cmdToExecute.Parameters["@IsExist"].Value.ToString()); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'Currency_IsExist' reported the ErrorCode: " + _errorCode); } return IsExist==1; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("Currency::IsExist::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Insert method. This method will insert one new row into the database. /// </summary> /// <returns>True if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>Id</LI> /// <LI>Kode</LI> /// <LI>Nama</LI> /// <LI>Keterangan. May be SqlString.Null</LI> /// <LI>Published</LI> /// <LI>Ordering</LI> /// <LI>CreatedBy</LI> /// <LI>CreatedDate</LI> /// <LI>UpdatedBy. May be SqlInt32.Null</LI> /// <LI>UpdatedDate. May be SqlDateTime.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override bool Insert() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[Currency_Insert]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode)); cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama)); cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan)); cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 1, 0, "", DataRowVersion.Proposed, _published)); cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 23, 3, "", DataRowVersion.Proposed, _createdDate)); cmdToExecute.Parameters.Add(new SqlParameter("@UpdatedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _updatedBy)); cmdToExecute.Parameters.Add(new SqlParameter("@UpdatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 23, 3, "", DataRowVersion.Proposed, _updatedDate)); cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _id = (SqlInt32)cmdToExecute.Parameters["@Id"].Value; _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'Currency_Insert' reported the ErrorCode: " + _errorCode); } return true; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("Currency::Insert::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Update method. This method will Update one existing row in the database. /// </summary> /// <returns>True if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>Id</LI> /// <LI>Kode</LI> /// <LI>Nama</LI> /// <LI>Keterangan. May be SqlString.Null</LI> /// <LI>Published</LI> /// <LI>Ordering</LI> /// <LI>CreatedBy</LI> /// <LI>CreatedDate</LI> /// <LI>UpdatedBy. May be SqlInt32.Null</LI> /// <LI>UpdatedDate. May be SqlDateTime.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override bool Update() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[Currency_Update]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode)); cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama)); cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan)); cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 1, 0, "", DataRowVersion.Proposed, _published)); cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 23, 3, "", DataRowVersion.Proposed, _createdDate)); cmdToExecute.Parameters.Add(new SqlParameter("@UpdatedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _updatedBy)); cmdToExecute.Parameters.Add(new SqlParameter("@UpdatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 23, 3, "", DataRowVersion.Proposed, _updatedDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'Currency_Update' reported the ErrorCode: " + _errorCode); } return true; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("Currency::Update::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Delete method. This method will Delete one existing row in the database, based on the Primary Key. /// </summary> /// <returns>True if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>Id</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override bool Delete() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[Currency_Delete]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'Currency_Delete' reported the ErrorCode: " + _errorCode); } return true; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("Currency::Delete::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Select method. This method will Select one existing row from the database, based on the Primary Key. /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>Id</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// <LI>Id</LI> /// <LI>Kode</LI> /// <LI>Nama</LI> /// <LI>Keterangan</LI> /// <LI>Published</LI> /// <LI>Ordering</LI> /// <LI>CreatedBy</LI> /// <LI>CreatedDate</LI> /// <LI>UpdatedBy</LI> /// <LI>UpdatedDate</LI> /// </UL> /// Will fill all properties corresponding with a field in the table with the value of the row selected. /// </remarks> public override DataTable SelectOne() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[Currency_SelectOne]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("Currency"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'Currency_SelectOne' reported the ErrorCode: " + _errorCode); } if(toReturn.Rows.Count > 0) { _id = (Int32)toReturn.Rows[0]["Id"]; _kode = (string)toReturn.Rows[0]["Kode"]; _nama = (string)toReturn.Rows[0]["Nama"]; _keterangan = toReturn.Rows[0]["Keterangan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Keterangan"]; _published = (bool)toReturn.Rows[0]["Published"]; _ordering = (Int32)toReturn.Rows[0]["Ordering"]; _createdBy = (Int32)toReturn.Rows[0]["CreatedBy"]; _createdDate = (DateTime)toReturn.Rows[0]["CreatedDate"]; _updatedBy = toReturn.Rows[0]["UpdatedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["UpdatedBy"]; _updatedDate = toReturn.Rows[0]["UpdatedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["UpdatedDate"]; } return toReturn; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("Currency::SelectOne::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } /// <summary> /// Purpose: SelectAll method. This method will Select all rows from the table. /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override DataTable SelectAll() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[Currency_SelectAll]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("Currency"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'Currency_SelectAll' reported the ErrorCode: " + _errorCode); } return toReturn; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("Currency::SelectAll::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } /// <summary> /// Purpose: GetList method. This method will Select all rows from the table where is active. /// Added by Ekitea On 19 September 2006 /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public DataTable GetList() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[Currency_GetList]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("Currency"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'Currency_GetList' reported the ErrorCode: " + _errorCode); } return toReturn; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("Currency::GetList::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } #region Class Property Declarations public SqlInt32 Id { get { return _id; } set { SqlInt32 idTmp = (SqlInt32)value; if(idTmp.IsNull) { throw new ArgumentOutOfRangeException("Id", "Id can't be NULL"); } _id = value; } } public SqlString Kode { get { return _kode; } set { SqlString kodeTmp = (SqlString)value; if(kodeTmp.IsNull) { throw new ArgumentOutOfRangeException("Kode", "Kode can't be NULL"); } _kode = value; } } public SqlString Nama { get { return _nama; } set { SqlString namaTmp = (SqlString)value; if(namaTmp.IsNull) { throw new ArgumentOutOfRangeException("Nama", "Nama can't be NULL"); } _nama = value; } } public SqlString Keterangan { get { return _keterangan; } set { _keterangan = value; } } public SqlBoolean Published { get { return _published; } set { SqlBoolean publishedTmp = (SqlBoolean)value; if(publishedTmp.IsNull) { throw new ArgumentOutOfRangeException("Published", "Published can't be NULL"); } _published = value; } } public SqlInt32 Ordering { get { return _ordering; } set { SqlInt32 orderingTmp = (SqlInt32)value; if(orderingTmp.IsNull) { throw new ArgumentOutOfRangeException("Ordering", "Ordering can't be NULL"); } _ordering = value; } } public SqlInt32 CreatedBy { get { return _createdBy; } set { SqlInt32 createdByTmp = (SqlInt32)value; if(createdByTmp.IsNull) { throw new ArgumentOutOfRangeException("CreatedBy", "CreatedBy can't be NULL"); } _createdBy = value; } } public SqlDateTime CreatedDate { get { return _createdDate; } set { SqlDateTime createdDateTmp = (SqlDateTime)value; if(createdDateTmp.IsNull) { throw new ArgumentOutOfRangeException("CreatedDate", "CreatedDate can't be NULL"); } _createdDate = value; } } public SqlInt32 UpdatedBy { get { return _updatedBy; } set { _updatedBy = value; } } public SqlDateTime UpdatedDate { get { return _updatedDate; } set { _updatedDate = value; } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Region.ClientStack.LindenUDP; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.UDP.Linden { /// <summary> /// A module that just holds commands for inspecting the current state of the Linden UDP stack. /// </summary> /// <remarks> /// All actual client stack functionality remains in OpenSim.Region.ClientStack.LindenUDP /// </remarks> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LindenUDPInfoModule")] public class LindenUDPInfoModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>(); public string Name { get { return "Linden UDP Module"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { // m_log.DebugFormat("[LINDEN UDP INFO MODULE]: INITIALIZED MODULE"); } public void PostInitialise() { // m_log.DebugFormat("[LINDEN UDP INFO MODULE]: POST INITIALIZED MODULE"); } public void Close() { // m_log.DebugFormat("[LINDEN UDP INFO MODULE]: CLOSED MODULE"); } public void AddRegion(Scene scene) { // m_log.DebugFormat("[LINDEN UDP INFO MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); lock (m_scenes) m_scenes[scene.RegionInfo.RegionID] = scene; scene.AddCommand( "Comms", this, "show pqueues", "show pqueues [full]", "Show priority queue data for each client", "Without the 'full' option, only root agents are shown." + " With the 'full' option child agents are also shown.", (mod, cmd) => MainConsole.Instance.Output(GetPQueuesReport(cmd))); scene.AddCommand( "Comms", this, "show queues", "show queues [full]", "Show queue data for each client", "Without the 'full' option, only root agents are shown.\n" + "With the 'full' option child agents are also shown.\n\n" + "Type - Rt is a root (avatar) client whilst cd is a child (neighbour interacting) client.\n" + "Since Last In - Time in milliseconds since last packet received.\n" + "Pkts In - Number of packets processed from the client.\n" + "Pkts Out - Number of packets sent to the client.\n" + "Pkts Resent - Number of packets resent to the client.\n" + "Bytes Unacked - Number of bytes transferred to the client that are awaiting acknowledgement.\n" + "Q Pkts * - Number of packets of various types (land, wind, etc.) to be sent to the client that are waiting for available bandwidth.\n", (mod, cmd) => MainConsole.Instance.Output(GetQueuesReport(cmd))); scene.AddCommand( "Comms", this, "show image queues", "show image queues <first-name> <last-name>", "Show the image queues (textures downloaded via UDP) for a particular client.", (mod, cmd) => MainConsole.Instance.Output(GetImageQueuesReport(cmd))); scene.AddCommand( "Comms", this, "clear image queues", "clear image queues <first-name> <last-name>", "Clear the image queues (textures downloaded via UDP) for a particular client.", (mod, cmd) => MainConsole.Instance.Output(HandleImageQueuesClear(cmd))); scene.AddCommand( "Comms", this, "show throttles", "show throttles [full]", "Show throttle settings for each client and for the server overall", "Without the 'full' option, only root agents are shown." + " With the 'full' option child agents are also shown.", (mod, cmd) => MainConsole.Instance.Output(GetThrottlesReport(cmd))); scene.AddCommand( "Comms", this, "emergency-monitoring", "emergency-monitoring", "Go on/off emergency monitoring mode", "Go on/off emergency monitoring mode", HandleEmergencyMonitoring); scene.AddCommand( "Comms", this, "show client stats", "show client stats [first_name last_name]", "Show client request stats", "Without the 'first_name last_name' option, all clients are shown." + " With the 'first_name last_name' option only a specific client is shown.", (mod, cmd) => MainConsole.Instance.Output(HandleClientStatsReport(cmd))); } public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[LINDEN UDP INFO MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); lock (m_scenes) m_scenes.Remove(scene.RegionInfo.RegionID); } public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[LINDEN UDP INFO MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); } protected string HandleImageQueuesClear(string[] cmd) { if (cmd.Length != 5) return "Usage: image queues clear <first-name> <last-name>"; string firstName = cmd[3]; string lastName = cmd[4]; List<ScenePresence> foundAgents = new List<ScenePresence>(); lock (m_scenes) { foreach (Scene scene in m_scenes.Values) { ScenePresence sp = scene.GetScenePresence(firstName, lastName); if (sp != null) foundAgents.Add(sp); } } if (foundAgents.Count == 0) return string.Format("No agents found for {0} {1}", firstName, lastName); StringBuilder report = new StringBuilder(); foreach (ScenePresence agent in foundAgents) { LLClientView client = agent.ControllingClient as LLClientView; if (client == null) return "This command is only supported for LLClientView"; int requestsDeleted = client.ImageManager.ClearImageQueue(); report.AppendFormat( "In region {0} ({1} agent) cleared {2} requests\n", agent.Scene.RegionInfo.RegionName, agent.IsChildAgent ? "child" : "root", requestsDeleted); } return report.ToString(); } protected void HandleEmergencyMonitoring(string module, string[] cmd) { bool mode = true; if (cmd.Length == 1 || (cmd.Length > 1 && cmd[1] == "on")) { mode = true; MainConsole.Instance.Output("Emergency Monitoring ON"); } else { mode = false; MainConsole.Instance.Output("Emergency Monitoring OFF"); } foreach (Scene s in m_scenes.Values) s.EmergencyMonitoring = mode; } protected string GetColumnEntry(string entry, int maxLength, int columnPadding) { return string.Format( "{0,-" + maxLength + "}{1,-" + columnPadding + "}", entry.Length > maxLength ? entry.Substring(0, maxLength) : entry, ""); } /// <summary> /// Generate UDP Queue data report for each client /// </summary> /// <param name="showParams"></param> /// <returns></returns> protected string GetPQueuesReport(string[] showParams) { bool showChildren = false; string pname = ""; if (showParams.Length > 2 && showParams[2] == "full") showChildren = true; else if (showParams.Length > 3) pname = showParams[2] + " " + showParams[3]; StringBuilder report = new StringBuilder(); int columnPadding = 2; int maxNameLength = 18; int maxRegionNameLength = 14; int maxTypeLength = 4; // int totalInfoFieldsLength = maxNameLength + columnPadding + maxRegionNameLength + columnPadding + maxTypeLength + columnPadding; report.Append(GetColumnEntry("User", maxNameLength, columnPadding)); report.Append(GetColumnEntry("Region", maxRegionNameLength, columnPadding)); report.Append(GetColumnEntry("Type", maxTypeLength, columnPadding)); report.AppendFormat( "{0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7} {10,7} {11,7}\n", "Pri 0", "Pri 1", "Pri 2", "Pri 3", "Pri 4", "Pri 5", "Pri 6", "Pri 7", "Pri 8", "Pri 9", "Pri 10", "Pri 11"); lock (m_scenes) { foreach (Scene scene in m_scenes.Values) { scene.ForEachClient( delegate(IClientAPI client) { if (client is LLClientView) { bool isChild = client.SceneAgent.IsChildAgent; if (isChild && !showChildren) return; string name = client.Name; if (pname != "" && name != pname) return; string regionName = scene.RegionInfo.RegionName; report.Append(GetColumnEntry(name, maxNameLength, columnPadding)); report.Append(GetColumnEntry(regionName, maxRegionNameLength, columnPadding)); report.Append(GetColumnEntry(isChild ? "Cd" : "Rt", maxTypeLength, columnPadding)); report.AppendLine(((LLClientView)client).EntityUpdateQueue.ToString()); } }); } } return report.ToString(); } /// <summary> /// Generate an image queue report /// </summary> /// <param name="showParams"></param> /// <returns></returns> private string GetImageQueuesReport(string[] showParams) { if (showParams.Length < 5 || showParams.Length > 6) return "Usage: show image queues <first-name> <last-name> [full]"; string firstName = showParams[3]; string lastName = showParams[4]; bool showChildAgents = showParams.Length == 6; List<ScenePresence> foundAgents = new List<ScenePresence>(); lock (m_scenes) { foreach (Scene scene in m_scenes.Values) { ScenePresence sp = scene.GetScenePresence(firstName, lastName); if (sp != null && (showChildAgents || !sp.IsChildAgent)) foundAgents.Add(sp); } } if (foundAgents.Count == 0) return string.Format("No agents found for {0} {1}", firstName, lastName); StringBuilder report = new StringBuilder(); foreach (ScenePresence agent in foundAgents) { LLClientView client = agent.ControllingClient as LLClientView; if (client == null) return "This command is only supported for LLClientView"; J2KImage[] images = client.ImageManager.GetImages(); report.AppendFormat( "In region {0} ({1} agent)\n", agent.Scene.RegionInfo.RegionName, agent.IsChildAgent ? "child" : "root"); report.AppendFormat("Images in queue: {0}\n", images.Length); if (images.Length > 0) { report.AppendFormat( "{0,-36} {1,-8} {2,-10} {3,-9} {4,-9} {5,-7}\n", "Texture ID", "Last Seq", "Priority", "Start Pkt", "Has Asset", "Decoded"); foreach (J2KImage image in images) report.AppendFormat( "{0,36} {1,8} {2,10} {3,10} {4,9} {5,7}\n", image.TextureID, image.LastSequence, image.Priority, image.StartPacket, image.HasAsset, image.IsDecoded); } } return report.ToString(); } /// <summary> /// Generate UDP Queue data report for each client /// </summary> /// <param name="showParams"></param> /// <returns></returns> protected string GetQueuesReport(string[] showParams) { bool showChildren = false; string pname = ""; if (showParams.Length > 2 && showParams[2] == "full") showChildren = true; else if (showParams.Length > 3) pname = showParams[2] + " " + showParams[3]; StringBuilder report = new StringBuilder(); int columnPadding = 2; int maxNameLength = 18; int maxRegionNameLength = 14; int maxTypeLength = 4; int totalInfoFieldsLength = maxNameLength + columnPadding + maxRegionNameLength + columnPadding + maxTypeLength + columnPadding; report.Append(GetColumnEntry("User", maxNameLength, columnPadding)); report.Append(GetColumnEntry("Region", maxRegionNameLength, columnPadding)); report.Append(GetColumnEntry("Type", maxTypeLength, columnPadding)); report.AppendFormat( "{0,7} {1,7} {2,7} {3,7} {4,9} {5,7} {6,7} {7,7} {8,7} {9,7} {10,8} {11,7}\n", "Since", "Pkts", "Pkts", "Pkts", "Bytes", "Q Pkts", "Q Pkts", "Q Pkts", "Q Pkts", "Q Pkts", "Q Pkts", "Q Pkts"); report.AppendFormat("{0,-" + totalInfoFieldsLength + "}", ""); report.AppendFormat( "{0,7} {1,7} {2,7} {3,7} {4,9} {5,7} {6,7} {7,7} {8,7} {9,7} {10,8} {11,7}\n", "Last In", "In", "Out", "Resent", "Unacked", "Resend", "Land", "Wind", "Cloud", "Task", "Texture", "Asset"); lock (m_scenes) { foreach (Scene scene in m_scenes.Values) { scene.ForEachClient( delegate(IClientAPI client) { if (client is IStatsCollector) { bool isChild = client.SceneAgent.IsChildAgent; if (isChild && !showChildren) return; string name = client.Name; if (pname != "" && name != pname) return; string regionName = scene.RegionInfo.RegionName; report.Append(GetColumnEntry(name, maxNameLength, columnPadding)); report.Append(GetColumnEntry(regionName, maxRegionNameLength, columnPadding)); report.Append(GetColumnEntry(isChild ? "Cd" : "Rt", maxTypeLength, columnPadding)); IStatsCollector stats = (IStatsCollector)client; report.AppendLine(stats.Report()); } }); } } return report.ToString(); } /// <summary> /// Show throttle data /// </summary> /// <param name="showParams"></param> /// <returns></returns> protected string GetThrottlesReport(string[] showParams) { bool showChildren = false; string pname = ""; if (showParams.Length > 2 && showParams[2] == "full") showChildren = true; else if (showParams.Length > 3) pname = showParams[2] + " " + showParams[3]; StringBuilder report = new StringBuilder(); int columnPadding = 2; int maxNameLength = 18; int maxRegionNameLength = 14; int maxTypeLength = 4; int totalInfoFieldsLength = maxNameLength + columnPadding + maxRegionNameLength + columnPadding + maxTypeLength + columnPadding; report.Append(GetColumnEntry("User", maxNameLength, columnPadding)); report.Append(GetColumnEntry("Region", maxRegionNameLength, columnPadding)); report.Append(GetColumnEntry("Type", maxTypeLength, columnPadding)); report.AppendFormat( "{0,8} {1,8} {2,7} {3,8} {4,7} {5,7} {6,7} {7,7} {8,9} {9,7}\n", "Max", "Target", "Actual", "Resend", "Land", "Wind", "Cloud", "Task", "Texture", "Asset"); report.AppendFormat("{0,-" + totalInfoFieldsLength + "}", ""); report.AppendFormat( "{0,8} {1,8} {2,7} {3,8} {4,7} {5,7} {6,7} {7,7} {8,9} {9,7}\n", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s"); report.AppendLine(); lock (m_scenes) { foreach (Scene scene in m_scenes.Values) { scene.ForEachClient( delegate(IClientAPI client) { if (client is LLClientView) { LLClientView llClient = client as LLClientView; bool isChild = client.SceneAgent.IsChildAgent; if (isChild && !showChildren) return; string name = client.Name; if (pname != "" && name != pname) return; string regionName = scene.RegionInfo.RegionName; LLUDPClient llUdpClient = llClient.UDPClient; ClientInfo ci = llUdpClient.GetClientInfo(); report.Append(GetColumnEntry(name, maxNameLength, columnPadding)); report.Append(GetColumnEntry(regionName, maxRegionNameLength, columnPadding)); report.Append(GetColumnEntry(isChild ? "Cd" : "Rt", maxTypeLength, columnPadding)); report.AppendFormat( "{0,8} {1,8} {2,7} {3,8} {4,7} {5,7} {6,7} {7,7} {8,9} {9,7}\n", ci.maxThrottle > 0 ? ((ci.maxThrottle * 8) / 1000).ToString() : "-", llUdpClient.FlowThrottle.AdaptiveEnabled ? ((ci.targetThrottle * 8) / 1000).ToString() : (llUdpClient.FlowThrottle.TotalDripRequest * 8 / 1000).ToString(), (ci.totalThrottle * 8) / 1000, (ci.resendThrottle * 8) / 1000, (ci.landThrottle * 8) / 1000, (ci.windThrottle * 8) / 1000, (ci.cloudThrottle * 8) / 1000, (ci.taskThrottle * 8) / 1000, (ci.textureThrottle * 8) / 1000, (ci.assetThrottle * 8) / 1000); } }); } } return report.ToString(); } /// <summary> /// Show client stats data /// </summary> /// <param name="showParams"></param> /// <returns></returns> protected string HandleClientStatsReport(string[] showParams) { // NOTE: This writes to m_log on purpose. We want to store this information // in case we need to analyze it later. // if (showParams.Length <= 4) { m_log.InfoFormat("[INFO]: {0,-12} {1,-20} {2,-6} {3,-11} {4,-11} {5,-16}", "Region", "Name", "Root", "Time", "Reqs/min", "AgentUpdates"); foreach (Scene scene in m_scenes.Values) { scene.ForEachClient( delegate(IClientAPI client) { if (client is LLClientView) { LLClientView llClient = client as LLClientView; ClientInfo cinfo = llClient.UDPClient.GetClientInfo(); int avg_reqs = cinfo.AsyncRequests.Values.Sum() + cinfo.GenericRequests.Values.Sum() + cinfo.SyncRequests.Values.Sum(); avg_reqs = avg_reqs / ((DateTime.Now - cinfo.StartedTime).Minutes + 1); string childAgentStatus; if (llClient.SceneAgent != null) childAgentStatus = llClient.SceneAgent.IsChildAgent ? "N" : "Y"; else childAgentStatus = "Off!"; m_log.InfoFormat("[INFO]: {0,-12} {1,-20} {2,-6} {3,-11} {4,-11} {5,-16}", scene.RegionInfo.RegionName, llClient.Name, childAgentStatus, (DateTime.Now - cinfo.StartedTime).Minutes, avg_reqs, string.Format( "{0} ({1:0.00}%)", llClient.TotalAgentUpdates, cinfo.SyncRequests.ContainsKey("AgentUpdate") ? (float)cinfo.SyncRequests["AgentUpdate"] / llClient.TotalAgentUpdates * 100 : 0)); } }); } return string.Empty; } string fname = "", lname = ""; if (showParams.Length > 3) fname = showParams[3]; if (showParams.Length > 4) lname = showParams[4]; foreach (Scene scene in m_scenes.Values) { scene.ForEachClient( delegate(IClientAPI client) { if (client is LLClientView) { LLClientView llClient = client as LLClientView; if (llClient.Name == fname + " " + lname) { ClientInfo cinfo = llClient.GetClientInfo(); AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(llClient.CircuitCode); if (aCircuit == null) // create a dummy one aCircuit = new AgentCircuitData(); if (!llClient.SceneAgent.IsChildAgent) m_log.InfoFormat("[INFO]: {0} # {1} # {2}", llClient.Name, Util.GetViewerName(aCircuit), aCircuit.Id0); int avg_reqs = cinfo.AsyncRequests.Values.Sum() + cinfo.GenericRequests.Values.Sum() + cinfo.SyncRequests.Values.Sum(); avg_reqs = avg_reqs / ((DateTime.Now - cinfo.StartedTime).Minutes + 1); m_log.InfoFormat("[INFO]:"); m_log.InfoFormat("[INFO]: {0} # {1} # Time: {2}min # Avg Reqs/min: {3}", scene.RegionInfo.RegionName, (llClient.SceneAgent.IsChildAgent ? "Child" : "Root"), (DateTime.Now - cinfo.StartedTime).Minutes, avg_reqs); Dictionary<string, int> sortedDict = (from entry in cinfo.AsyncRequests orderby entry.Value descending select entry) .ToDictionary(pair => pair.Key, pair => pair.Value); PrintRequests("TOP ASYNC", sortedDict, cinfo.AsyncRequests.Values.Sum()); sortedDict = (from entry in cinfo.SyncRequests orderby entry.Value descending select entry) .ToDictionary(pair => pair.Key, pair => pair.Value); PrintRequests("TOP SYNC", sortedDict, cinfo.SyncRequests.Values.Sum()); sortedDict = (from entry in cinfo.GenericRequests orderby entry.Value descending select entry) .ToDictionary(pair => pair.Key, pair => pair.Value); PrintRequests("TOP GENERIC", sortedDict, cinfo.GenericRequests.Values.Sum()); } } }); } return string.Empty; } private void PrintRequests(string type, Dictionary<string, int> sortedDict, int sum) { m_log.InfoFormat("[INFO]:"); m_log.InfoFormat("[INFO]: {0,25}", type); foreach (KeyValuePair<string, int> kvp in sortedDict.Take(12)) m_log.InfoFormat("[INFO]: {0,25} {1,-6}", kvp.Key, kvp.Value); m_log.InfoFormat("[INFO]: {0,25}", "..."); m_log.InfoFormat("[INFO]: {0,25} {1,-6}", "Total", sum); } } }
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 ZigNetApi.Areas.HelpPage.ModelDescriptions; using ZigNetApi.Areas.HelpPage.Models; namespace ZigNetApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System.Collections.Generic; using UnityEngine; using System; namespace UnityEditor.Rendering { public static class DialogText { public static readonly string title = "Material Upgrader"; public static readonly string proceed = "Proceed"; public static readonly string ok = "Ok"; public static readonly string cancel = "Cancel"; public static readonly string noSelectionMessage = "You must select at least one material."; public static readonly string projectBackMessage = "Make sure to have a project backup before proceeding."; } public class MaterialUpgrader { public delegate void MaterialFinalizer(Material mat); string m_OldShader; string m_NewShader; MaterialFinalizer m_Finalizer; Dictionary<string, string> m_TextureRename = new Dictionary<string, string>(); Dictionary<string, string> m_FloatRename = new Dictionary<string, string>(); Dictionary<string, string> m_ColorRename = new Dictionary<string, string>(); Dictionary<string, float> m_FloatPropertiesToSet = new Dictionary<string, float>(); Dictionary<string, Color> m_ColorPropertiesToSet = new Dictionary<string, Color>(); List<string> m_TexturesToRemove = new List<string>(); Dictionary<string, Texture> m_TexturesToSet = new Dictionary<string, Texture>(); class KeywordFloatRename { public string keyword; public string property; public float setVal, unsetVal; } List<KeywordFloatRename> m_KeywordFloatRename = new List<KeywordFloatRename>(); [Flags] public enum UpgradeFlags { None = 0, LogErrorOnNonExistingProperty = 1, CleanupNonUpgradedProperties = 2, LogMessageWhenNoUpgraderFound = 4 } public void Upgrade(Material material, UpgradeFlags flags) { Material newMaterial; if ((flags & UpgradeFlags.CleanupNonUpgradedProperties) != 0) { newMaterial = new Material(Shader.Find(m_NewShader)); } else { newMaterial = UnityEngine.Object.Instantiate(material) as Material; newMaterial.shader = Shader.Find(m_NewShader); } Convert(material, newMaterial); material.shader = Shader.Find(m_NewShader); material.CopyPropertiesFromMaterial(newMaterial); UnityEngine.Object.DestroyImmediate(newMaterial); if (m_Finalizer != null) m_Finalizer(material); } // Overridable function to implement custom material upgrading functionality public virtual void Convert(Material srcMaterial, Material dstMaterial) { foreach (var t in m_TextureRename) { dstMaterial.SetTextureScale(t.Value, srcMaterial.GetTextureScale(t.Key)); dstMaterial.SetTextureOffset(t.Value, srcMaterial.GetTextureOffset(t.Key)); dstMaterial.SetTexture(t.Value, srcMaterial.GetTexture(t.Key)); } foreach (var t in m_FloatRename) dstMaterial.SetFloat(t.Value, srcMaterial.GetFloat(t.Key)); foreach (var t in m_ColorRename) dstMaterial.SetColor(t.Value, srcMaterial.GetColor(t.Key)); foreach (var prop in m_TexturesToRemove) dstMaterial.SetTexture(prop, null); foreach (var prop in m_TexturesToSet) dstMaterial.SetTexture(prop.Key, prop.Value); foreach (var prop in m_FloatPropertiesToSet) dstMaterial.SetFloat(prop.Key, prop.Value); foreach (var prop in m_ColorPropertiesToSet) dstMaterial.SetColor(prop.Key, prop.Value); foreach (var t in m_KeywordFloatRename) dstMaterial.SetFloat(t.property, srcMaterial.IsKeywordEnabled(t.keyword) ? t.setVal : t.unsetVal); } public void RenameShader(string oldName, string newName, MaterialFinalizer finalizer = null) { m_OldShader = oldName; m_NewShader = newName; m_Finalizer = finalizer; } public void RenameTexture(string oldName, string newName) { m_TextureRename[oldName] = newName; } public void RenameFloat(string oldName, string newName) { m_FloatRename[oldName] = newName; } public void RenameColor(string oldName, string newName) { m_ColorRename[oldName] = newName; } public void RemoveTexture(string name) { m_TexturesToRemove.Add(name); } public void SetFloat(string propertyName, float value) { m_FloatPropertiesToSet[propertyName] = value; } public void SetColor(string propertyName, Color value) { m_ColorPropertiesToSet[propertyName] = value; } public void SetTexture(string propertyName, Texture value) { m_TexturesToSet[propertyName] = value; } public void RenameKeywordToFloat(string oldName, string newName, float setVal, float unsetVal) { m_KeywordFloatRename.Add(new KeywordFloatRename { keyword = oldName, property = newName, setVal = setVal, unsetVal = unsetVal }); } static bool IsMaterialPath(string path) { return path.EndsWith(".mat", StringComparison.OrdinalIgnoreCase); } static MaterialUpgrader GetUpgrader(List<MaterialUpgrader> upgraders, Material material) { if (material == null || material.shader == null) return null; string shaderName = material.shader.name; for (int i = 0; i != upgraders.Count; i++) { if (upgraders[i].m_OldShader == shaderName) return upgraders[i]; } return null; } //@TODO: Only do this when it exceeds memory consumption... static void SaveAssetsAndFreeMemory() { AssetDatabase.SaveAssets(); GC.Collect(); EditorUtility.UnloadUnusedAssetsImmediate(); AssetDatabase.Refresh(); } public static void UpgradeProjectFolder(List<MaterialUpgrader> upgraders, string progressBarName, UpgradeFlags flags = UpgradeFlags.None) { if (!EditorUtility.DisplayDialog(DialogText.title, "The upgrade will overwrite materials in your project. " + DialogText.projectBackMessage, DialogText.proceed, DialogText.cancel)) return; int totalMaterialCount = 0; foreach (string s in UnityEditor.AssetDatabase.GetAllAssetPaths()) { if (IsMaterialPath(s)) totalMaterialCount++; } int materialIndex = 0; foreach (string path in UnityEditor.AssetDatabase.GetAllAssetPaths()) { if (IsMaterialPath(path)) { materialIndex++; if (UnityEditor.EditorUtility.DisplayCancelableProgressBar(progressBarName, string.Format("({0} of {1}) {2}", materialIndex, totalMaterialCount, path), (float)materialIndex / (float)totalMaterialCount)) break; Material m = UnityEditor.AssetDatabase.LoadMainAssetAtPath(path) as Material; Upgrade(m, upgraders, flags); //SaveAssetsAndFreeMemory(); } } UnityEditor.EditorUtility.ClearProgressBar(); } public static void Upgrade(Material material, MaterialUpgrader upgrader, UpgradeFlags flags) { var upgraders = new List<MaterialUpgrader>(); upgraders.Add(upgrader); Upgrade(material, upgraders, flags); } public static void Upgrade(Material material, List<MaterialUpgrader> upgraders, UpgradeFlags flags) { if (material == null) return; var upgrader = GetUpgrader(upgraders, material); if (upgrader != null) upgrader.Upgrade(material, flags); else if ((flags & UpgradeFlags.LogMessageWhenNoUpgraderFound) == UpgradeFlags.LogMessageWhenNoUpgraderFound) Debug.Log(string.Format("{0} material was not upgraded. There's no upgrader to convert {1} shader to selected pipeline", material.name, material.shader.name)); } public static void UpgradeSelection(List<MaterialUpgrader> upgraders, string progressBarName, UpgradeFlags flags = UpgradeFlags.None) { var selection = Selection.objects; if (selection == null) { EditorUtility.DisplayDialog(DialogText.title, DialogText.noSelectionMessage, DialogText.ok); return; } List<Material> selectedMaterials = new List<Material>(selection.Length); for (int i = 0; i < selection.Length; ++i) { Material mat = selection[i] as Material; if (mat != null) selectedMaterials.Add(mat); } int selectedMaterialsCount = selectedMaterials.Count; if (selectedMaterialsCount == 0) { EditorUtility.DisplayDialog(DialogText.title, DialogText.noSelectionMessage, DialogText.ok); return; } if (!EditorUtility.DisplayDialog(DialogText.title, string.Format("The upgrade will overwrite {0} selected material{1}. ", selectedMaterialsCount, selectedMaterialsCount > 1 ? "s" : "") + DialogText.projectBackMessage, DialogText.proceed, DialogText.cancel)) return; string lastMaterialName = ""; for (int i = 0; i < selectedMaterialsCount; i++) { if (UnityEditor.EditorUtility.DisplayCancelableProgressBar(progressBarName, string.Format("({0} of {1}) {2}", i, selectedMaterialsCount, lastMaterialName), (float)i / (float)selectedMaterialsCount)) break; var material = selectedMaterials[i]; Upgrade(material, upgraders, flags); if (material != null) lastMaterialName = material.name; } UnityEditor.EditorUtility.ClearProgressBar(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.IO { // Class for creating FileStream objects, and some basic file management // routines such as Delete, etc. public static class File { private static Encoding s_UTF8NoBOM; internal const int DefaultBufferSize = 4096; public static StreamReader OpenText(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return new StreamReader(path); } public static StreamWriter CreateText(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return new StreamWriter(path, append: false); } public static StreamWriter AppendText(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return new StreamWriter(path, append: true); } // Copies an existing file to a new file. An exception is raised if the // destination file already exists. Use the // Copy(string, string, boolean) method to allow // overwriting an existing file. // // The caller must have certain FileIOPermissions. The caller must have // Read permission to sourceFileName and Create // and Write permissions to destFileName. // public static void Copy(string sourceFileName, string destFileName) { if (sourceFileName == null) throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName); if (destFileName == null) throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName); if (sourceFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName)); if (destFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName)); InternalCopy(sourceFileName, destFileName, false); } // Copies an existing file to a new file. If overwrite is // false, then an IOException is thrown if the destination file // already exists. If overwrite is true, the file is // overwritten. // // The caller must have certain FileIOPermissions. The caller must have // Read permission to sourceFileName // and Write permissions to destFileName. // public static void Copy(string sourceFileName, string destFileName, bool overwrite) { if (sourceFileName == null) throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName); if (destFileName == null) throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName); if (sourceFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName)); if (destFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName)); InternalCopy(sourceFileName, destFileName, overwrite); } /// <devdoc> /// Note: This returns the fully qualified name of the destination file. /// </devdoc> internal static string InternalCopy(string sourceFileName, string destFileName, bool overwrite) { Debug.Assert(sourceFileName != null); Debug.Assert(destFileName != null); Debug.Assert(sourceFileName.Length > 0); Debug.Assert(destFileName.Length > 0); string fullSourceFileName = Path.GetFullPath(sourceFileName); string fullDestFileName = Path.GetFullPath(destFileName); FileSystem.Current.CopyFile(fullSourceFileName, fullDestFileName, overwrite); return fullDestFileName; } // Creates a file in a particular path. If the file exists, it is replaced. // The file is opened with ReadWrite access and cannot be opened by another // application until it has been closed. An IOException is thrown if the // directory specified doesn't exist. // // Your application must have Create, Read, and Write permissions to // the file. // public static FileStream Create(string path) { return Create(path, DefaultBufferSize); } // Creates a file in a particular path. If the file exists, it is replaced. // The file is opened with ReadWrite access and cannot be opened by another // application until it has been closed. An IOException is thrown if the // directory specified doesn't exist. // // Your application must have Create, Read, and Write permissions to // the file. // public static FileStream Create(string path, int bufferSize) { return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize); } public static FileStream Create(string path, int bufferSize, FileOptions options) { return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, options); } // Deletes a file. The file specified by the designated path is deleted. // If the file does not exist, Delete succeeds without throwing // an exception. // // On NT, Delete will fail for a file that is open for normal I/O // or a file that is memory mapped. // // Your application must have Delete permission to the target file. // public static void Delete(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); string fullPath = Path.GetFullPath(path); FileSystem.Current.DeleteFile(fullPath); } // Tests if a file exists. The result is true if the file // given by the specified path exists; otherwise, the result is // false. Note that if path describes a directory, // Exists will return true. // // Your application must have Read permission for the target directory. // public static bool Exists(string path) { try { if (path == null) return false; if (path.Length == 0) return false; path = Path.GetFullPath(path); // After normalizing, check whether path ends in directory separator. // Otherwise, FillAttributeInfo removes it and we may return a false positive. // GetFullPath should never return null Debug.Assert(path != null, "File.Exists: GetFullPath returned null"); if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1])) { return false; } return InternalExists(path); } catch (ArgumentException) { } catch (NotSupportedException) { } // Security can throw this on ":" catch (SecurityException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; } internal static bool InternalExists(string path) { return FileSystem.Current.FileExists(path); } public static FileStream Open(string path, FileMode mode) { return Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None); } public static FileStream Open(string path, FileMode mode, FileAccess access) { return Open(path, mode, access, FileShare.None); } public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share) { return new FileStream(path, mode, access, share); } internal static DateTimeOffset GetUtcDateTimeOffset(DateTime dateTime) { // File and Directory UTC APIs treat a DateTimeKind.Unspecified as UTC whereas // ToUniversalTime treats this as local. if (dateTime.Kind == DateTimeKind.Unspecified) { return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); } return dateTime.ToUniversalTime(); } public static void SetCreationTime(string path, DateTime creationTime) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetCreationTime(fullPath, creationTime, asDirectory: false); } public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetCreationTime(fullPath, GetUtcDateTimeOffset(creationTimeUtc), asDirectory: false); } public static DateTime GetCreationTime(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetCreationTime(fullPath).LocalDateTime; } public static DateTime GetCreationTimeUtc(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetCreationTime(fullPath).UtcDateTime; } public static void SetLastAccessTime(string path, DateTime lastAccessTime) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: false); } public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastAccessTime(fullPath, GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: false); } public static DateTime GetLastAccessTime(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetLastAccessTime(fullPath).LocalDateTime; } public static DateTime GetLastAccessTimeUtc(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetLastAccessTime(fullPath).UtcDateTime; } public static void SetLastWriteTime(string path, DateTime lastWriteTime) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: false); } public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetLastWriteTime(fullPath, GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: false); } public static DateTime GetLastWriteTime(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetLastWriteTime(fullPath).LocalDateTime; } public static DateTime GetLastWriteTimeUtc(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetLastWriteTime(fullPath).UtcDateTime; } public static FileAttributes GetAttributes(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.Current.GetAttributes(fullPath); } public static void SetAttributes(string path, FileAttributes fileAttributes) { string fullPath = Path.GetFullPath(path); FileSystem.Current.SetAttributes(fullPath, fileAttributes); } public static FileStream OpenRead(string path) { return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); } public static FileStream OpenWrite(string path) { return new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); } public static string ReadAllText(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return InternalReadAllText(path, Encoding.UTF8); } public static string ReadAllText(string path, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return InternalReadAllText(path, encoding); } private static string InternalReadAllText(string path, Encoding encoding) { Debug.Assert(path != null); Debug.Assert(encoding != null); Debug.Assert(path.Length > 0); using (StreamReader sr = new StreamReader(path, encoding, detectEncodingFromByteOrderMarks: true)) return sr.ReadToEnd(); } public static void WriteAllText(string path, string contents) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); using (StreamWriter sw = new StreamWriter(path)) { sw.Write(contents); } } public static void WriteAllText(string path, string contents, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); using (StreamWriter sw = new StreamWriter(path, false, encoding)) { sw.Write(contents); } } public static byte[] ReadAllBytes(string path) { return InternalReadAllBytes(path); } private static byte[] InternalReadAllBytes(string path) { // bufferSize == 1 used to avoid unnecessary buffer in FileStream using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1)) { long fileLength = fs.Length; if (fileLength > int.MaxValue) throw new IOException(SR.IO_FileTooLong2GB); int index = 0; int count = (int)fileLength; byte[] bytes = new byte[count]; while (count > 0) { int n = fs.Read(bytes, index, count); if (n == 0) throw Error.GetEndOfFile(); index += n; count -= n; } return bytes; } } public static void WriteAllBytes(string path, byte[] bytes) { if (path == null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); if (bytes == null) throw new ArgumentNullException(nameof(bytes)); InternalWriteAllBytes(path, bytes); } private static void InternalWriteAllBytes(string path, byte[] bytes) { Debug.Assert(path != null); Debug.Assert(path.Length != 0); Debug.Assert(bytes != null); using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) { fs.Write(bytes, 0, bytes.Length); } } public static string[] ReadAllLines(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return InternalReadAllLines(path, Encoding.UTF8); } public static string[] ReadAllLines(string path, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return InternalReadAllLines(path, encoding); } private static string[] InternalReadAllLines(string path, Encoding encoding) { Debug.Assert(path != null); Debug.Assert(encoding != null); Debug.Assert(path.Length != 0); string line; List<string> lines = new List<string>(); using (StreamReader sr = new StreamReader(path, encoding)) while ((line = sr.ReadLine()) != null) lines.Add(line); return lines.ToArray(); } public static IEnumerable<string> ReadLines(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return ReadLinesIterator.CreateIterator(path, Encoding.UTF8); } public static IEnumerable<string> ReadLines(string path, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return ReadLinesIterator.CreateIterator(path, encoding); } public static void WriteAllLines(string path, string[] contents) { WriteAllLines(path, (IEnumerable<string>)contents); } public static void WriteAllLines(string path, IEnumerable<string> contents) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); InternalWriteAllLines(new StreamWriter(path), contents); } public static void WriteAllLines(string path, string[] contents, Encoding encoding) { WriteAllLines(path, (IEnumerable<string>)contents, encoding); } public static void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); InternalWriteAllLines(new StreamWriter(path, false, encoding), contents); } private static void InternalWriteAllLines(TextWriter writer, IEnumerable<string> contents) { Debug.Assert(writer != null); Debug.Assert(contents != null); using (writer) { foreach (string line in contents) { writer.WriteLine(line); } } } public static void AppendAllText(string path, string contents) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); using (StreamWriter sw = new StreamWriter(path, append: true)) { sw.Write(contents); } } public static void AppendAllText(string path, string contents, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); using (StreamWriter sw = new StreamWriter(path, true, encoding)) { sw.Write(contents); } } public static void AppendAllLines(string path, IEnumerable<string> contents) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); InternalWriteAllLines(new StreamWriter(path, append: true), contents); } public static void AppendAllLines(string path, IEnumerable<string> contents, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); InternalWriteAllLines(new StreamWriter(path, true, encoding), contents); } public static void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors: false); } public static void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { if (sourceFileName == null) throw new ArgumentNullException(nameof(sourceFileName)); if (destinationFileName == null) throw new ArgumentNullException(nameof(destinationFileName)); FileSystem.Current.ReplaceFile( Path.GetFullPath(sourceFileName), Path.GetFullPath(destinationFileName), destinationBackupFileName != null ? Path.GetFullPath(destinationBackupFileName) : null, ignoreMetadataErrors); } // Moves a specified file to a new location and potentially a new file name. // This method does work across volumes. // // The caller must have certain FileIOPermissions. The caller must // have Read and Write permission to // sourceFileName and Write // permissions to destFileName. // public static void Move(string sourceFileName, string destFileName) { if (sourceFileName == null) throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName); if (destFileName == null) throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName); if (sourceFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName)); if (destFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName)); string fullSourceFileName = Path.GetFullPath(sourceFileName); string fullDestFileName = Path.GetFullPath(destFileName); if (!InternalExists(fullSourceFileName)) { throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, fullSourceFileName), fullSourceFileName); } FileSystem.Current.MoveFile(fullSourceFileName, fullDestFileName); } public static void Encrypt(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); // TODO: Not supported on Unix or in WinRt, and the EncryptFile API isn't currently // available in OneCore. For now, we just throw PNSE everywhere. When the API is // available, we can put this into the FileSystem abstraction and implement it // properly for Win32. throw new PlatformNotSupportedException(SR.PlatformNotSupported_FileEncryption); } public static void Decrypt(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); // TODO: Not supported on Unix or in WinRt, and the EncryptFile API isn't currently // available in OneCore. For now, we just throw PNSE everywhere. When the API is // available, we can put this into the FileSystem abstraction and implement it // properly for Win32. throw new PlatformNotSupportedException(SR.PlatformNotSupported_FileEncryption); } // UTF-8 without BOM and with error detection. Same as the default encoding for StreamWriter. private static Encoding UTF8NoBOM => s_UTF8NoBOM ?? (s_UTF8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); // If we use the path-taking constructors we will not have FileOptions.Asynchronous set and // we will have asynchronous file access faked by the thread pool. We want the real thing. private static StreamReader AsyncStreamReader(string path, Encoding encoding) { FileStream stream = new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); return new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true); } private static StreamWriter AsyncStreamWriter(string path, Encoding encoding, bool append) { FileStream stream = new FileStream( path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); return new StreamWriter(stream, encoding); } public static Task<string> ReadAllTextAsync(string path, CancellationToken cancellationToken = default(CancellationToken)) => ReadAllTextAsync(path, Encoding.UTF8, cancellationToken); public static Task<string> ReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled<string>(cancellationToken) : InternalReadAllTextAsync(path, encoding, cancellationToken); } private static async Task<string> InternalReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(encoding != null); char[] buffer = null; StringBuilder sb = null; StreamReader sr = AsyncStreamReader(path, encoding); try { cancellationToken.ThrowIfCancellationRequested(); sb = StringBuilderCache.Acquire(); buffer = ArrayPool<char>.Shared.Rent(sr.CurrentEncoding.GetMaxCharCount(DefaultBufferSize)); for (;;) { int read = await sr.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); if (read == 0) { return sb.ToString(); } sb.Append(buffer, 0, read); cancellationToken.ThrowIfCancellationRequested(); } } finally { sr.Dispose(); if (buffer != null) { ArrayPool<char>.Shared.Return(buffer); } if (sb != null) { StringBuilderCache.Release(sb); } } } public static Task WriteAllTextAsync(string path, string contents, CancellationToken cancellationToken = default(CancellationToken)) => WriteAllTextAsync(path, contents, UTF8NoBOM, cancellationToken); public static Task WriteAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (string.IsNullOrEmpty(contents)) { new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read).Dispose(); return Task.CompletedTask; } return InternalWriteAllTextAsync(AsyncStreamWriter(path, encoding, append: false), contents, cancellationToken); } public static Task<byte[]> ReadAllBytesAsync(string path, CancellationToken cancellationToken = default(CancellationToken)) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<byte[]>(cancellationToken); } FileStream fs = new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); bool returningInternalTask = false; try { long fileLength = fs.Length; if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<byte[]>(cancellationToken); } if (fileLength > int.MaxValue) { return Task.FromException<byte[]>(new IOException(SR.IO_FileTooLong2GB)); } if (fileLength == 0) { return Task.FromResult(Array.Empty<byte>()); } returningInternalTask = true; return InternalReadAllBytesAsync(fs, (int)fileLength, cancellationToken); } finally { if (!returningInternalTask) { fs.Dispose(); } } } private static async Task<byte[]> InternalReadAllBytesAsync(FileStream fs, int count, CancellationToken cancellationToken) { using (fs) { int index = 0; byte[] bytes = new byte[count]; do { int n = await fs.ReadAsync(bytes, index, count - index, cancellationToken).ConfigureAwait(false); if (n == 0) { throw Error.GetEndOfFile(); } index += n; } while (index < count); return bytes; } } public static Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); if (bytes == null) throw new ArgumentNullException(nameof(bytes)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : InternalWriteAllBytesAsync(path, bytes, cancellationToken); } private static async Task InternalWriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(bytes != null); using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan)) { await fs.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false); await fs.FlushAsync(cancellationToken).ConfigureAwait(false); } } public static Task<string[]> ReadAllLinesAsync(string path, CancellationToken cancellationToken = default(CancellationToken)) => ReadAllLinesAsync(path, Encoding.UTF8, cancellationToken); public static Task<string[]> ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled<string[]>(cancellationToken) : InternalReadAllLinesAsync(path, encoding, cancellationToken); } private static async Task<string[]> InternalReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(encoding != null); using (StreamReader sr = AsyncStreamReader(path, encoding)) { cancellationToken.ThrowIfCancellationRequested(); string line; List<string> lines = new List<string>(); while ((line = await sr.ReadLineAsync().ConfigureAwait(false)) != null) { lines.Add(line); cancellationToken.ThrowIfCancellationRequested(); } return lines.ToArray(); } } public static Task WriteAllLinesAsync(string path, IEnumerable<string> contents, CancellationToken cancellationToken = default(CancellationToken)) => WriteAllLinesAsync(path, contents, UTF8NoBOM, cancellationToken); public static Task WriteAllLinesAsync(string path, IEnumerable<string> contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : InternalWriteAllLinesAsync(AsyncStreamWriter(path, encoding, append: false), contents, cancellationToken); } private static async Task InternalWriteAllLinesAsync(TextWriter writer, IEnumerable<string> contents, CancellationToken cancellationToken) { Debug.Assert(writer != null); Debug.Assert(contents != null); using (writer) { foreach (string line in contents) { cancellationToken.ThrowIfCancellationRequested(); // Note that this working depends on the fix to #14563, and cannot be ported without // either also porting that fix, or explicitly checking for line being null. await writer.WriteLineAsync(line).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); await writer.FlushAsync().ConfigureAwait(false); } } private static async Task InternalWriteAllTextAsync(StreamWriter sw, string contents, CancellationToken cancellationToken) { char[] buffer = null; try { buffer = ArrayPool<char>.Shared.Rent(DefaultBufferSize); int count = contents.Length; int index = 0; while (index < count) { int batchSize = Math.Min(DefaultBufferSize, count - index); contents.CopyTo(index, buffer, 0, batchSize); cancellationToken.ThrowIfCancellationRequested(); await sw.WriteAsync(buffer, 0, batchSize).ConfigureAwait(false); index += batchSize; } cancellationToken.ThrowIfCancellationRequested(); await sw.FlushAsync().ConfigureAwait(false); } finally { sw.Dispose(); if (buffer != null) { ArrayPool<char>.Shared.Return(buffer); } } } public static Task AppendAllTextAsync(string path, string contents, CancellationToken cancellationToken = default(CancellationToken)) => AppendAllTextAsync(path, contents, UTF8NoBOM, cancellationToken); public static Task AppendAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (string.IsNullOrEmpty(contents)) { // Just to throw exception if there is a problem opening the file. new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read).Dispose(); return Task.CompletedTask; } return InternalWriteAllTextAsync(AsyncStreamWriter(path, encoding, append: true), contents, cancellationToken); } public static Task AppendAllLinesAsync(string path, IEnumerable<string> contents, CancellationToken cancellationToken = default(CancellationToken)) => AppendAllLinesAsync(path, contents, UTF8NoBOM, cancellationToken); public static Task AppendAllLinesAsync(string path, IEnumerable<string> contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : InternalWriteAllLinesAsync(AsyncStreamWriter(path, encoding, append: true), contents, cancellationToken); } } }
// 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.Numerics; internal partial class VectorTest { private const int Pass = 100; private const int Fail = -1; private class VectorRelopTest<T> where T : struct, IComparable<T>, IEquatable<T> { public static int VectorRelOp(T larger, T smaller) { const int Pass = 100; const int Fail = -1; int returnVal = Pass; Vector<T> A = new Vector<T>(larger); Vector<T> B = new Vector<T>(smaller); Vector<T> C = new Vector<T>(larger); Vector<T> D; // less than Vector<T> condition = Vector.LessThan<T>(A, B); D = Vector.ConditionalSelect(condition, A, B); for (int i = 0; i < Vector<T>.Count; i++) { if (!D[i].Equals(B[i])) { Console.WriteLine("Less than condition failed for type " + typeof(T).Name + " at index " + i); returnVal = Fail; } } condition = Vector.LessThan<T>(B, A); D = Vector.ConditionalSelect(condition, A, B); for (int i = 0; i < Vector<T>.Count; i++) { if (!D[i].Equals(A[i])) { Console.WriteLine("Less than condition failed for type " + typeof(T).Name + " at index " + i); returnVal = Fail; } } // greater than condition = Vector.GreaterThan<T>(A, B); D = Vector.ConditionalSelect(condition, A, B); for (int i = 0; i < Vector<T>.Count; i++) { if (!D[i].Equals(A[i])) { Console.WriteLine("Greater than condition failed for type " + typeof(T).Name + " at index " + i); returnVal = Fail; } } condition = Vector.GreaterThan<T>(B, A); D = Vector.ConditionalSelect(condition, A, B); for (int i = 0; i < Vector<T>.Count; i++) { if (!D[i].Equals(B[i])) { Console.WriteLine("Greater than condition failed for type " + typeof(T).Name + " at index " + i); returnVal = Fail; } } // less than or equal condition = Vector.LessThanOrEqual<T>(A, C); D = Vector.ConditionalSelect(condition, A, B); for (int i = 0; i < Vector<T>.Count; i++) { if (!D[i].Equals(A[i])) { Console.WriteLine("Less than or equal condition failed for type " + typeof(T).Name + " at index " + i); returnVal = Fail; } } condition = Vector.LessThanOrEqual<T>(A, B); D = Vector.ConditionalSelect(condition, A, B); for (int i = 0; i < Vector<T>.Count; i++) { if (!D[i].Equals(B[i])) { Console.WriteLine("Less than or equal condition failed for type " + typeof(T).Name + " at index " + i); returnVal = Fail; } } // greater than or equal condition = Vector.GreaterThanOrEqual<T>(A, C); D = Vector.ConditionalSelect(condition, A, B); for (int i = 0; i < Vector<T>.Count; i++) { if (!D[i].Equals(A[i])) { Console.WriteLine("Greater than or equal condition failed for type " + typeof(T).Name + " at index " + i); returnVal = Fail; } } condition = Vector.GreaterThanOrEqual<T>(B, C); D = Vector.ConditionalSelect(condition, A, B); for (int i = 0; i < Vector<T>.Count; i++) { if (!D[i].Equals(B[i])) { Console.WriteLine("Greater than or equal condition failed for type " + typeof(T).Name + " at index " + i); returnVal = Fail; } } // equal condition = Vector.Equals<T>(A, C); D = Vector.ConditionalSelect(condition, A, B); for (int i = 0; i < Vector<T>.Count; i++) { if (!D[i].Equals(A[i])) { Console.WriteLine("Equal condition failed for type " + typeof(T).Name + " at index " + i); returnVal = Fail; } } condition = Vector.Equals<T>(B, C); D = Vector.ConditionalSelect(condition, A, B); for (int i = 0; i < Vector<T>.Count; i++) { if (!D[i].Equals(B[i])) { Console.WriteLine("Equal condition failed for type " + typeof(T).Name + " at index " + i); returnVal = Fail; } } return returnVal; } } private static int Main() { int returnVal = Pass; if (VectorRelopTest<float>.VectorRelOp(3, 2) != Pass) returnVal = Fail; if (VectorRelopTest<double>.VectorRelOp(3, 2) != Pass) returnVal = Fail; if (VectorRelopTest<int>.VectorRelOp(3, 2) != Pass) returnVal = Fail; if (VectorRelopTest<long>.VectorRelOp(3, 2) != Pass) returnVal = Fail; if (VectorRelopTest<ushort>.VectorRelOp(3, 2) != Pass) returnVal = Fail; if (VectorRelopTest<byte>.VectorRelOp(3, 2) != Pass) returnVal = Fail; if (VectorRelopTest<short>.VectorRelOp(-2, -3) != Pass) returnVal = Fail; if (VectorRelopTest<sbyte>.VectorRelOp(-2, -3) != Pass) returnVal = Fail; if (VectorRelopTest<uint>.VectorRelOp(3u, 2u) != Pass) returnVal = Fail; if (VectorRelopTest<ulong>.VectorRelOp(3ul, 2ul) != Pass) returnVal = Fail; JitLog jitLog = new JitLog(); // ConditionalSelect, LessThanOrEqual and GreaterThanOrEqual are defined // on the Vector type, so the overloads can't be distinguished. // if (!jitLog.Check("System.Numerics.Vector:ConditionalSelect(struct,struct,struct):struct")) returnVal = Fail; if (!jitLog.Check("System.Numerics.Vector:LessThanOrEqual(struct,struct):struct")) returnVal = Fail; if (!jitLog.Check("System.Numerics.Vector:GreaterThanOrEqual(struct,struct):struct")) returnVal = Fail; if (!jitLog.Check("Equals", "Single")) returnVal = Fail; if (!jitLog.Check("LessThan", "Single")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "Single")) returnVal = Fail; if (!jitLog.Check("op_BitwiseAnd", "Single")) returnVal = Fail; if (!jitLog.Check("op_ExclusiveOr", "Single")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "Single")) returnVal = Fail; // This relies on an implementation detail - i.e. that the One and Zero property are implemented // in the library by GetOneValue and GetZeroValue, respectively. if (!jitLog.Check("GetOneValue", "Single")) returnVal = Fail; if (!jitLog.Check("GetZeroValue", "Single")) returnVal = Fail; if (!jitLog.Check("Equals", "Double")) returnVal = Fail; if (!jitLog.Check("LessThan", "Double")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "Double")) returnVal = Fail; if (!jitLog.Check("op_BitwiseAnd", "Double")) returnVal = Fail; if (!jitLog.Check("op_ExclusiveOr", "Double")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "Double")) returnVal = Fail; // This relies on an implementation detail - i.e. that the One and Zero property are implemented // in the library by GetOneValue and GetZeroValue, respectively. if (!jitLog.Check("GetOneValue", "Double")) returnVal = Fail; if (!jitLog.Check("GetZeroValue", "Double")) returnVal = Fail; if (!jitLog.Check("Equals", "Int32")) returnVal = Fail; if (!jitLog.Check("LessThan", "Int32")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "Int32")) returnVal = Fail; if (!jitLog.Check("op_BitwiseAnd", "Int32")) returnVal = Fail; if (!jitLog.Check("op_ExclusiveOr", "Int32")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "Int32")) returnVal = Fail; // This relies on an implementation detail - i.e. that the One and Zero property are implemented // in the library by GetOneValue and GetZeroValue, respectively. if (!jitLog.Check("GetOneValue", "Int32")) returnVal = Fail; if (!jitLog.Check("GetZeroValue", "Int32")) returnVal = Fail; if (!jitLog.Check("Equals", "Int64")) returnVal = Fail; if (!jitLog.Check("LessThan", "Int64")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "Int64")) returnVal = Fail; if (!jitLog.Check("op_BitwiseAnd", "Int64")) returnVal = Fail; if (!jitLog.Check("op_ExclusiveOr", "Int64")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "Int64")) returnVal = Fail; // This relies on an implementation detail - i.e. that the One and Zero property are implemented // in the library by GetOneValue and GetZeroValue, respectively. if (!jitLog.Check("GetOneValue", "Int64")) returnVal = Fail; if (!jitLog.Check("GetZeroValue", "Int64")) returnVal = Fail; if (!jitLog.Check("Equals", "UInt16")) returnVal = Fail; if (!jitLog.Check("LessThan", "UInt16")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "UInt16")) returnVal = Fail; if (!jitLog.Check("op_BitwiseAnd", "UInt16")) returnVal = Fail; if (!jitLog.Check("op_ExclusiveOr", "UInt16")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "UInt16")) returnVal = Fail; // This relies on an implementation detail - i.e. that the One and Zero property are implemented // in the library by GetOneValue and GetZeroValue, respectively. if (!jitLog.Check("GetOneValue", "UInt16")) returnVal = Fail; if (!jitLog.Check("GetZeroValue", "UInt16")) returnVal = Fail; if (!jitLog.Check("Equals", "Byte")) returnVal = Fail; if (!jitLog.Check("LessThan", "Byte")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "Byte")) returnVal = Fail; if (!jitLog.Check("op_BitwiseAnd", "Byte")) returnVal = Fail; if (!jitLog.Check("op_ExclusiveOr", "Byte")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "Byte")) returnVal = Fail; // This relies on an implementation detail - i.e. that the One and Zero property are implemented // in the library by GetOneValue and GetZeroValue, respectively. if (!jitLog.Check("GetOneValue", "Byte")) returnVal = Fail; if (!jitLog.Check("GetZeroValue", "Byte")) returnVal = Fail; if (!jitLog.Check("Equals", "Int16")) returnVal = Fail; if (!jitLog.Check("LessThan", "Int16")) returnVal = Fail; if (!jitLog.Check("op_BitwiseAnd", "Int16")) returnVal = Fail; if (!jitLog.Check("op_ExclusiveOr", "Int16")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "Int16")) returnVal = Fail; // This relies on an implementation detail - i.e. that the One and Zero property are implemented // in the library by GetOneValue and GetZeroValue, respectively. if (!jitLog.Check("GetOneValue", "Int16")) returnVal = Fail; if (!jitLog.Check("GetZeroValue", "Int16")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "Int16")) returnVal = Fail; if (!jitLog.Check("Equals", "SByte")) returnVal = Fail; if (!jitLog.Check("LessThan", "SByte")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "SByte")) returnVal = Fail; if (!jitLog.Check("op_BitwiseAnd", "SByte")) returnVal = Fail; if (!jitLog.Check("op_ExclusiveOr", "SByte")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "SByte")) returnVal = Fail; // This relies on an implementation detail - i.e. that the One and Zero property are implemented // in the library by GetOneValue and GetZeroValue, respectively. if (!jitLog.Check("GetOneValue", "SByte")) returnVal = Fail; if (!jitLog.Check("GetZeroValue", "SByte")) returnVal = Fail; if (!jitLog.Check("Equals", "UInt32")) returnVal = Fail; if (!jitLog.Check("LessThan", "UInt32")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "UInt32")) returnVal = Fail; if (!jitLog.Check("op_BitwiseAnd", "UInt32")) returnVal = Fail; if (!jitLog.Check("op_ExclusiveOr", "UInt32")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "UInt32")) returnVal = Fail; // This relies on an implementation detail - i.e. that the One and Zero property are implemented // in the library by GetOneValue and GetZeroValue, respectively. if (!jitLog.Check("GetOneValue", "UInt32")) returnVal = Fail; if (!jitLog.Check("GetZeroValue", "UInt32")) returnVal = Fail; if (!jitLog.Check("Equals", "UInt64")) returnVal = Fail; if (!jitLog.Check("LessThan", "UInt64")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "UInt64")) returnVal = Fail; if (!jitLog.Check("op_BitwiseAnd", "UInt64")) returnVal = Fail; if (!jitLog.Check("op_ExclusiveOr", "UInt64")) returnVal = Fail; if (!jitLog.Check("GreaterThan", "UInt64")) returnVal = Fail; // This relies on an implementation detail - i.e. that the One and Zero property are implemented // in the library by GetOneValue and GetZeroValue, respectively. if (!jitLog.Check("GetOneValue", "UInt64")) returnVal = Fail; if (!jitLog.Check("GetZeroValue", "UInt64")) returnVal = Fail; jitLog.Dispose(); return returnVal; } }
using System; using System.Collections; using System.Threading; using NationalInstruments.DAQmx; using DAQ.Environment; using DAQ.FakeData; using DAQ.HAL; using Data; using Data.EDM; using EDMConfig; using EDMBlockHead.Acquire.Channels; using EDMBlockHead.Acquire.Input; namespace EDMBlockHead.Acquire { /// <summary> /// This class is the backend that takes EDM blocks. /// /// One thing that is not obvious is the way that pattern output works. BlockHead asks ScanMaster /// to output the pattern. It selects the "Scan B" profile (heaven forbid if there isn't such a profile). /// This way there is no tedious mucking around with copying parameters. BlockHead copies out the /// pg settings from the profile into the block config. /// </summary> public class Acquisitor { // stuff to coordinate the backend and frontend private Thread acquireThread; enum AcquisitorState {stopped, running, stopping}; private AcquisitorState backendState = AcquisitorState.stopped; public Object MonitorLockObject = new Object(); // the configuration for the block that is being taken private BlockConfig config; // daq variables ArrayList switchedChannels; ScannedAnalogInputCollection inputs; Task inputTask; Task singlePointInputTask; AnalogMultiChannelReader inputReader; AnalogMultiChannelReader singlePointInputReader; ScanMaster.Controller scanMaster; EDMPhaseLock.MainForm phaseLock; EDMHardwareControl.Controller hardwareController; // calling this method starts acquisition public void Start(BlockConfig config) { this.config = config; acquireThread = new Thread(new ThreadStart(this.Acquire)); acquireThread.Name = "BlockHead Acquisitor"; acquireThread.Priority = ThreadPriority.Normal; backendState = AcquisitorState.running; acquireThread.Start(); } // calling this method stops acquisition as soon as possible (usually after the current shot) public void Stop() { lock(this) { backendState = AcquisitorState.stopping; } } // this is the method that actually takes the data. It is called by Start() and shouldn't // be called directly public void Acquire() { // lock onto something that the front end can see Monitor.Enter(MonitorLockObject); scanMaster = new ScanMaster.Controller(); phaseLock = new EDMPhaseLock.MainForm(); hardwareController = new EDMHardwareControl.Controller(); // map modulations to physical channels MapChannels(); // map the analog inputs MapAnalogInputs(); Block b = new Block(); b.Config = config; b.SetTimeStamp(); foreach (ScannedAnalogInput channel in inputs.Channels) { b.detectors.Add(channel.Channel.Name); } try { // get things going AcquisitionStarting(); // enter the main loop for (int point = 0 ; point < (int)config.Settings["numberOfPoints"] ; point++) { // set the switch states and impose the appropriate wait times ThrowSwitches(point); // take a point Shot s; EDMPoint p; if (Environs.Debug) { // just stuff a made up shot in //Thread.Sleep(10); s = DataFaker.GetFakeShot(1900,50,10,3,3); ((TOF)s.TOFs[0]).Calibration = ((ScannedAnalogInput)inputs.Channels[0]).Calibration; p = new EDMPoint(); p.Shot = s; //Thread.Sleep(20); } else { // everything should be ready now so start the analog // input task (it will wait for a trigger) inputTask.Start(); // get the raw data double[,] analogData = inputReader.ReadMultiSample(inputs.GateLength); inputTask.Stop(); // extract the data for each scanned channel and put it in a TOF s = new Shot(); for (int i = 0 ; i < inputs.Channels.Count ; i++) { // extract the raw data double[] rawData = new double[inputs.GateLength]; for (int q = 0 ; q < inputs.GateLength ; q++) rawData[q] = analogData[i,q]; ScannedAnalogInput ipt = (ScannedAnalogInput)inputs.Channels[i]; // reduce the data double[] data = ipt.Reduce(rawData); TOF t = new TOF(); t.Calibration = ipt.Calibration; // the 1000000 is because clock period is in microseconds; t.ClockPeriod = 1000000 / ipt.CalculateClockRate(inputs.RawSampleRate); t.GateStartTime = inputs.GateStartTime; // this is a bit confusing. The chop is measured in points, so the gate // has to be adjusted by the number of points times the clock period! if (ipt.ReductionMode == DataReductionMode.Chop) t.GateStartTime += (ipt.ChopStart * t.ClockPeriod); t.Data = data; // the 1000000 is because clock period is in microseconds; t.ClockPeriod = 1000000 / ipt.CalculateClockRate(inputs.RawSampleRate); s.TOFs.Add(t); } p = new EDMPoint(); p.Shot = s; } // do the "SinglePointData" (i.e. things that are measured once per point) // We'll save the leakage monitor until right at the end. // keep an eye on what the phase lock is doing p.SinglePointData.Add("PhaseLockFrequency", phaseLock.OutputFrequency); p.SinglePointData.Add("PhaseLockError", phaseLock.PhaseError); // scan the analog inputs double[] spd; // fake some data if we're in debug mode if (Environs.Debug) { spd = new double[7]; spd[0] = 1; spd[1] = 2; spd[2] = 3; spd[3] = 4; spd[4] = 5; spd[5] = 6; spd[6] = 7; } else { singlePointInputTask.Start(); spd = singlePointInputReader.ReadSingleSample(); singlePointInputTask.Stop(); } p.SinglePointData.Add("ProbePD", spd[0]); p.SinglePointData.Add("PumpPD", spd[1]); p.SinglePointData.Add("MiniFlux1", spd[2]); p.SinglePointData.Add("MiniFlux2", spd[3]); p.SinglePointData.Add("MiniFlux3", spd[4]); p.SinglePointData.Add("CplusV", spd[5]); p.SinglePointData.Add("CminusV", spd[6]); //hardwareController.UpdateVMonitor(); //p.SinglePointData.Add("CplusV", hardwareController.CPlusMonitorVoltage); //hardwareController.UpdateLaserPhotodiodes(); //p.SinglePointData.Add("ProbePD", hardwareController.ProbePDVoltage); //p.SinglePointData.Add("PumpPD", hardwareController.PumpPDVoltage); //hardwareController.UpdateMiniFluxgates(); //p.SinglePointData.Add("MiniFlux1", hardwareController.MiniFlux1Voltage); //p.SinglePointData.Add("MiniFlux2", hardwareController.MiniFlux2Voltage); //p.SinglePointData.Add("MiniFlux3", hardwareController.MiniFlux3Voltage); hardwareController.ReadIMonitor(); p.SinglePointData.Add("NorthCurrent", hardwareController.NorthCurrent); p.SinglePointData.Add("SouthCurrent", hardwareController.SouthCurrent); //hardwareController.UpdatePiMonitor(); //p.SinglePointData.Add("piMonitor", hardwareController.PiFlipMonVoltage); //p.SinglePointData.Add("CminusV", hardwareController.CMinusMonitorVoltage); // Hopefully the leakage monitors will have finished reading by now. // We join them, read out the data, and then launch another asynchronous // acquisition. [If this is the first shot of the block, the leakage monitor // measurement will have been launched in AcquisitionStarting() ]. //hardwareController.WaitForIMonitorAsync(); //p.SinglePointData.Add("NorthCurrent", hardwareController.NorthCurrent); //p.SinglePointData.Add("SouthCurrent", hardwareController.SouthCurrent); //hardwareController.UpdateIMonitorAsync(); // randomise the Ramsey phase // TODO: check whether the .NET rng is good enough // TODO: reference where this number comes from //double d = 2.3814 * (new Random().NextDouble()); //hardwareController.SetScramblerVoltage(d); b.Points.Add(p); // update the front end Controller.GetController().GotPoint(point, p); if (CheckIfStopping()) { // release hardware AcquisitionStopping(); // signal anybody waiting on the lock that we're done Monitor.Pulse(MonitorLockObject); Monitor.Exit(MonitorLockObject); return; } } } catch (Exception e) { // try and stop the experiment gracefully try { AcquisitionStopping(); } catch (Exception) {} // about the best that can be done at this stage Monitor.Pulse(MonitorLockObject); Monitor.Exit(MonitorLockObject); throw e; } AcquisitionStopping(); // hand the new block back to the controller Controller.GetController().AcquisitionFinished(b); // signal anybody waiting on the lock that we're done Monitor.Pulse(MonitorLockObject); Monitor.Exit(MonitorLockObject); } private void MapChannels() { switchedChannels = new ArrayList(); TTLSwitchedChannel bChan = new TTLSwitchedChannel(); bChan.Channel = "b"; bChan.Invert = false; bChan.Modulation = config.GetModulationByName("B"); switchedChannels.Add(bChan); TTLSwitchedChannel notBChan = new TTLSwitchedChannel(); notBChan.Channel = "notB"; notBChan.Invert = true; notBChan.Modulation = config.GetModulationByName("B"); switchedChannels.Add(notBChan); TTLSwitchedChannel dbChan = new TTLSwitchedChannel(); dbChan.Channel = "db"; dbChan.Invert = false; dbChan.Modulation = config.GetModulationByName("DB"); switchedChannels.Add(dbChan); TTLSwitchedChannel notDBChan = new TTLSwitchedChannel(); notDBChan.Channel = "notDB"; notDBChan.Invert = true; notDBChan.Modulation = config.GetModulationByName("DB"); switchedChannels.Add(notDBChan); TTLSwitchedChannel piChan = new TTLSwitchedChannel(); piChan.Channel = "piFlipEnable"; piChan.Invert = false; piChan.Modulation = config.GetModulationByName("PI"); switchedChannels.Add(piChan); TTLSwitchedChannel notPIChan = new TTLSwitchedChannel(); notPIChan.Channel = "notPIFlipEnable"; notPIChan.Invert = true; notPIChan.Modulation = config.GetModulationByName("PI"); switchedChannels.Add(notPIChan); //ESwitchChannel eChan = new ESwitchChannel(); //eChan.Invert = false; //eChan.Modulation = config.GetModulationByName("E"); //switchedChannels.Add(eChan); //ESwitchRFChannel eChan = new ESwitchRFChannel(); //eChan.Invert = false; //eChan.Modulation = config.GetModulationByName("E"); //eChan.stepSizeRF = +0.25; //switchedChannels.Add(eChan); AnalogSwitchedChannel rf1AChannel = new AnalogSwitchedChannel(); rf1AChannel.Channel = "rf1Attenuator"; rf1AChannel.Modulation = config.GetModulationByName("RF1A"); switchedChannels.Add(rf1AChannel); AnalogSwitchedChannel rf2AChannel = new AnalogSwitchedChannel(); rf2AChannel.Channel = "rf2Attenuator"; rf2AChannel.Modulation = config.GetModulationByName("RF2A"); switchedChannels.Add(rf2AChannel); AnalogSwitchedChannel rf1FChannel = new AnalogSwitchedChannel(); rf1FChannel.Channel = "rf1FM"; rf1FChannel.Modulation = config.GetModulationByName("RF1F"); switchedChannels.Add(rf1FChannel); AnalogSwitchedChannel rf2FChannel = new AnalogSwitchedChannel(); rf2FChannel.Channel = "rf2FM"; rf2FChannel.Modulation = config.GetModulationByName("RF2F"); switchedChannels.Add(rf2FChannel); HardwareControllerSwitchChannel eChan = new HardwareControllerSwitchChannel(); eChan.Channel = "eChan"; eChan.Modulation = config.GetModulationByName("E"); switchedChannels.Add(eChan); //AnalogSwitchedChannel lf1Channel = new AnalogSwitchedChannel(); //lf1Channel.Channel = "flPZT"; //lf1Channel.Modulation = config.GetModulationByName("LF1"); //switchedChannels.Add(lf1Channel); HardwareControllerSwitchChannel lf1Channel = new HardwareControllerSwitchChannel(); lf1Channel.Channel = "probeAOM"; lf1Channel.Modulation = config.GetModulationByName("LF1"); switchedChannels.Add(lf1Channel); HardwareControllerSwitchChannel lf2Channel = new HardwareControllerSwitchChannel(); lf2Channel.Channel = "pumpAOM"; lf2Channel.Modulation = config.GetModulationByName("LF2"); switchedChannels.Add(lf2Channel); //AnalogSwitchedChannel lf3Channel = new HardwareControllerSwitchChannel(); //lf3Channel.Channel = "LF3"; //lf3Channel.Modulation = config.GetModulationByName("LF3"); //switchedChannels.Add(lf3Channel); } #region Map Inputs /* THIS VERSION FOR AR */ // this sets up the scanned analog inputs. It's complicated a bit by the fact that // each input would ideally have a different clock rate and gateLength. The board // doesn't support that though. public void MapAnalogInputs() { inputs = new ScannedAnalogInputCollection(); inputs.RawSampleRate = 100000; inputs.GateStartTime = (int)scanMaster.GetShotSetting("gateStartTime"); inputs.GateLength = 220; //inputs.GateLength = 1000; // NOTE: this long version is for null runs, don't set it so long that the shots overlap! // Comment the following line out if you're not null running. //inputs.GateLength = 3000; // this code should be used for normal running ScannedAnalogInput pmt = new ScannedAnalogInput(); pmt.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["top"]; pmt.ReductionMode = DataReductionMode.Chop; pmt.ChopStart = 140; pmt.ChopLength = 80; pmt.LowLimit = 0; pmt.HighLimit = 10; pmt.Calibration = 0.209145; // calibration from 5-8-08, b14. p52, high gain setting inputs.Channels.Add(pmt); // // this code can be enabled for faster null runs // ScannedAnalogInput pmt = new ScannedAnalogInput(); // pmt.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["pmt"]; // pmt.ReductionMode = DataReductionMode.Average; // pmt.AverageEvery = 40; // pmt.LowLimit = 0; // pmt.HighLimit = 10; // pmt.Calibration = 0.14; // inputs.Channels.Add(pmt); ScannedAnalogInput normPMT = new ScannedAnalogInput(); normPMT.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["norm"]; normPMT.ReductionMode = DataReductionMode.Chop; normPMT.ChopStart = 0; normPMT.ChopLength = 40; normPMT.LowLimit = 0; normPMT.HighLimit = 10; normPMT.Calibration = 0.0406658; // calibration from 5-8-08, b14. p52, high gain setting inputs.Channels.Add(normPMT); ScannedAnalogInput mag = new ScannedAnalogInput(); mag.ReductionMode = DataReductionMode.Average; mag.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["magnetometer"]; mag.AverageEvery = 20; mag.LowLimit = -10; mag.HighLimit = 10; mag.Calibration = 0.00001; inputs.Channels.Add(mag); ScannedAnalogInput gnd = new ScannedAnalogInput(); gnd.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["gnd"]; gnd.ReductionMode = DataReductionMode.Average; gnd.AverageEvery = 20; gnd.LowLimit = -1; gnd.HighLimit = 1; gnd.Calibration = 1; inputs.Channels.Add(gnd); ScannedAnalogInput battery = new ScannedAnalogInput(); battery.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["battery"]; battery.ReductionMode = DataReductionMode.Chop; battery.ChopStart = 140; battery.ChopLength = 80; battery.LowLimit = 0; battery.HighLimit = 10; battery.Calibration = 1; inputs.Channels.Add(battery); ScannedAnalogInput rfCurrent = new ScannedAnalogInput(); rfCurrent.ReductionMode = DataReductionMode.Average; rfCurrent.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["rfCurrent"]; rfCurrent.AverageEvery = 10; //Bandwidth of the ammeter is aprox 12kHz rfCurrent.LowLimit = -10; rfCurrent.HighLimit = 10; inputs.Channels.Add(rfCurrent); ScannedAnalogInput reflectedrf1Amplitude = new ScannedAnalogInput(); reflectedrf1Amplitude.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["reflectedrf1Amplitude"]; reflectedrf1Amplitude.ReductionMode = DataReductionMode.Chop; reflectedrf1Amplitude.ChopStart = 30; reflectedrf1Amplitude.ChopLength = 130; reflectedrf1Amplitude.LowLimit = -10; reflectedrf1Amplitude.HighLimit = 1; inputs.Channels.Add(reflectedrf1Amplitude); ScannedAnalogInput reflectedrf2Amplitude = new ScannedAnalogInput(); reflectedrf2Amplitude.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["reflectedrf2Amplitude"]; reflectedrf2Amplitude.ReductionMode = DataReductionMode.Chop; reflectedrf2Amplitude.ChopStart = 30; reflectedrf2Amplitude.ChopLength = 130; reflectedrf2Amplitude.LowLimit = -10; reflectedrf2Amplitude.HighLimit = 1; inputs.Channels.Add(reflectedrf2Amplitude); } ///* THIS VERSION FOR He/Kr */ //// this sets up the scanned analog inputs. It's complicated a bit by the fact that //// each input would ideally have a different clock rate and gateLength. The board //// doesn't support that though. //public void MapAnalogInputs() //{ // inputs = new ScannedAnalogInputCollection(); // inputs.RawSampleRate = 100000; // inputs.GateStartTime = (int)scanMaster.GetShotSetting("gateStartTime"); // inputs.GateLength = 300; // // this code should be used for normal running // ScannedAnalogInput pmt = new ScannedAnalogInput(); // pmt.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["pmt"]; // pmt.ReductionMode = DataReductionMode.Chop; // pmt.ChopStart = 180; // pmt.ChopLength = 120; // pmt.LowLimit = 0; // pmt.HighLimit = 10; // pmt.Calibration = 0.209145; // calibration from 5-8-08, b14. p52, high gain setting // inputs.Channels.Add(pmt); // ScannedAnalogInput normPMT = new ScannedAnalogInput(); // normPMT.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["norm"]; // normPMT.ReductionMode = DataReductionMode.Chop; // normPMT.ChopStart = 0; // normPMT.ChopLength = 40; // normPMT.LowLimit = 0; // normPMT.HighLimit = 10; // normPMT.Calibration = 0.0406658; // calibration from 5-8-08, b14. p52, high gain setting // inputs.Channels.Add(normPMT); // ScannedAnalogInput mag = new ScannedAnalogInput(); // mag.ReductionMode = DataReductionMode.Average; // mag.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["magnetometer"]; // mag.AverageEvery = 20; // mag.LowLimit = -10; // mag.HighLimit = 10; // mag.Calibration = 0.00001; // inputs.Channels.Add(mag); // ScannedAnalogInput gnd = new ScannedAnalogInput(); // gnd.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["gnd"]; // gnd.ReductionMode = DataReductionMode.Average; // gnd.AverageEvery = 20; // gnd.LowLimit = -1; // gnd.HighLimit = 1; // gnd.Calibration = 1; // inputs.Channels.Add(gnd); // ScannedAnalogInput battery = new ScannedAnalogInput(); // battery.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["battery"]; // battery.ReductionMode = DataReductionMode.Chop; // battery.ChopStart = 180; // battery.ChopLength = 120; // battery.LowLimit = 0; // battery.HighLimit = 10; // battery.Calibration = 1; // inputs.Channels.Add(battery); //} #endregion private void ConfigureSinglePointAnalogInputs() { // here we configure the scan of analog inputs that happens after each shot. singlePointInputTask = new Task("Blockhead single point inputs"); AddChannelToSinglePointTask("probePD"); //AddChannelToSinglePointTask("ground"); AddChannelToSinglePointTask("pumpPD"); //AddChannelToSinglePointTask("ground"); AddChannelToSinglePointTask("miniFlux1"); //AddChannelToSinglePointTask("ground"); AddChannelToSinglePointTask("miniFlux2"); //AddChannelToSinglePointTask("ground"); AddChannelToSinglePointTask("miniFlux3"); //AddChannelToSinglePointTask("ground"); AddChannelToSinglePointTask("cPlusMonitor"); //AddChannelToSinglePointTask("ground"); AddChannelToSinglePointTask("cMinusMonitor"); //AddChannelToSinglePointTask("northLeakage"); //AddChannelToSinglePointTask("ground"); //AddChannelToSinglePointTask("southLeakage"); //AddChannelToSinglePointTask("ground"); //singlePointInputTask.Timing.ConfigureSampleClock( // "", // 1000, // SampleClockActiveEdge.Rising, // SampleQuantityMode.FiniteSamples, // 1 // ); //singlePointInputTask.Triggers.StartTrigger.ConfigureNone(); if (!Environs.Debug) singlePointInputTask.Control(TaskAction.Verify); singlePointInputReader = new AnalogMultiChannelReader(singlePointInputTask.Stream); } private void AddChannelToSinglePointTask(string chan) { AnalogInputChannel aic = ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[chan]); aic.AddToTask(singlePointInputTask, 0, 10); } // configure hardware and start the pattern output private void AcquisitionStarting() { // iterate through the channels and ready them foreach (SwitchedChannel s in switchedChannels) s.AcquisitionStarting(); // copy running parameters into the BlockConfig StuffConfig(); // prepare the inputs inputTask = new Task("BlockHead analog input"); foreach (ScannedAnalogInput i in inputs.Channels) i.Channel.AddToTask( inputTask, i.LowLimit, i.HighLimit ); inputTask.Timing.ConfigureSampleClock( "", inputs.RawSampleRate, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, inputs.GateLength * inputs.Channels.Count ); inputTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger( (string)Environs.Hardware.GetInfo("analogTrigger0"), DigitalEdgeStartTriggerEdge.Rising ); if (!Environs.Debug) inputTask.Control(TaskAction.Verify); inputReader = new AnalogMultiChannelReader(inputTask.Stream); ConfigureSinglePointAnalogInputs(); // set the leakage monitor measurement time to 5ms. // With this setting it actually takes 26ms total to acquire two channels. //hardwareController.LeakageMonitorMeasurementTime = 0.005; hardwareController.ReconfigureIMonitors(); // Start the first asynchronous acquisition //hardwareController.UpdateIMonitorAsync(); } // If you want to store any information in the BlockConfig this is the place to do it. // This function is called at the start of every block. private void StuffConfig() { // dump all of the pg settings into the config - never know when they'll come in // handy ! ScanMaster.Acquire.Plugin.PluginSettings pgSettings = scanMaster.GetPGSettings(); foreach (String key in pgSettings.Keys) config.Settings[key] = pgSettings[key]; // rf parameters EDMHardwareControl.Controller hwController = new EDMHardwareControl.Controller(); config.Settings["greenSynthFrequency"] = hwController.GreenSynthOnFrequency; config.Settings["greenSynthDCFM"] = hwController.GreenSynthDCFM; config.Settings["greenSynthAmplitude"] = hwController.GreenSynthOnAmplitude; } private void ThrowSwitches(int point) { // this works out how long to wait before the switch - it looks at // all of the switched channels and figures out which ones are // switching. Of those channels it finds the longest wait. int delayBeforeSwitch = 0; foreach(SwitchedChannel s in switchedChannels) { int tempDelay = s.Modulation.DelayBeforeSwitch; // special case for the first point of a block - treat all channels as if they // are switching if (point != 0) { bool[] bits = s.Modulation.Waveform.Bits; // if this waveform is not switching just ignore its delay if ( bits[point] == bits[point - 1]) tempDelay = 0; } if (tempDelay > delayBeforeSwitch) delayBeforeSwitch = tempDelay; } // impose the delay if (delayBeforeSwitch != 0) Thread.Sleep(delayBeforeSwitch); // now actually throw the switches foreach(SwitchedChannel s in switchedChannels) { bool[] bits = s.Modulation.Waveform.Bits; if (point != 0) { if (bits[point] != bits[point - 1]) s.State = bits[point]; } else { s.State = bits[point]; } } // calculate and impose the post switching delays int delayAfterSwitch = 0; foreach(SwitchedChannel s in switchedChannels) { int tempDelay = s.Modulation.DelayAfterSwitch; // special case for the first point of a block - treat all channels as if they // are switching if (point != 0) { bool[] bits = s.Modulation.Waveform.Bits; // if this waveform is not switching just ignore its delay if ( bits[point] == bits[point - 1]) tempDelay = 0; } if (tempDelay > delayAfterSwitch) delayAfterSwitch = tempDelay; } // impose the delay if (delayAfterSwitch != 0) Thread.Sleep(delayAfterSwitch); } // stop pattern output and release hardware private void AcquisitionStopping() { foreach( SwitchedChannel s in switchedChannels) s.AcquisitionFinishing(); inputTask.Dispose(); singlePointInputTask.Dispose(); } private bool CheckIfStopping() { lock(this) { if (backendState == AcquisitorState.stopping) { backendState = AcquisitorState.stopped; return true; } else return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Contracts; using System.Diagnostics; using System.IO; using System.Runtime.WindowsRuntime.Internal; using Windows.Foundation; using Windows.Storage.Streams; namespace System.Runtime.InteropServices.WindowsRuntime { /// <summary> /// Contains a extension methods that expose operations on WinRT <code>Windows.Foundation.IBuffer</code>. /// </summary> public static class WindowsRuntimeBufferExtensions { #region (Byte []).AsBuffer extensions [CLSCompliant(false)] public static IBuffer AsBuffer(this Byte[] source) { if (source == null) throw new ArgumentNullException("source"); Contract.Ensures(Contract.Result<IBuffer>() != null); Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((UInt32)source.Length)); Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((UInt32)source.Length)); Contract.EndContractBlock(); return AsBuffer(source, 0, source.Length, source.Length); } [CLSCompliant(false)] public static IBuffer AsBuffer(this Byte[] source, Int32 offset, Int32 length) { if (source == null) throw new ArgumentNullException("source"); if (offset < 0) throw new ArgumentOutOfRangeException("offset"); if (length < 0) throw new ArgumentOutOfRangeException("length"); if (source.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); Contract.Ensures(Contract.Result<IBuffer>() != null); Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((UInt32)length)); Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((UInt32)length)); Contract.EndContractBlock(); return AsBuffer(source, offset, length, length); } [CLSCompliant(false)] public static IBuffer AsBuffer(this Byte[] source, Int32 offset, Int32 length, Int32 capacity) { if (source == null) throw new ArgumentNullException("source"); if (offset < 0) throw new ArgumentOutOfRangeException("offset"); if (length < 0) throw new ArgumentOutOfRangeException("length"); if (length < 0) throw new ArgumentOutOfRangeException("capacity"); if (source.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); if (source.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity); Contract.Ensures(Contract.Result<IBuffer>() != null); Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((UInt32)length)); Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((UInt32)capacity)); Contract.EndContractBlock(); return new WindowsRuntimeBuffer(source, offset, length, capacity); } #endregion (Byte []).AsBuffer extensions #region (Byte []).CopyTo extensions for copying to an (IBuffer) /// <summary> /// Copies the contents of <code>source</code> to <code>destination</code> starting at offset 0. /// This method does <em>NOT</em> update <code>destination.Length</code>. /// </summary> /// <param name="source">Array to copy data from.</param> /// <param name="destination">The buffer to copy to.</param> [CLSCompliant(false)] public static void CopyTo(this Byte[] source, IBuffer destination) { if (source == null) throw new ArgumentNullException("source"); if (destination == null) throw new ArgumentNullException("destination"); Contract.EndContractBlock(); CopyTo(source, 0, destination, 0, source.Length); } /// <summary> /// Copies <code>count</code> bytes from <code>source</code> starting at offset <code>sourceIndex</code> /// to <code>destination</code> starting at <code>destinationIndex</code>. /// This method does <em>NOT</em> update <code>destination.Length</code>. /// </summary> /// <param name="source">Array to copy data from.</param> /// <param name="sourceIndex">Position in the array from where to start copying.</param> /// <param name="destination">The buffer to copy to.</param> /// <param name="destinationIndex">Position in the buffer to where to start copying.</param> /// <param name="count">The number of bytes to copy.</param> [CLSCompliant(false)] public static void CopyTo(this Byte[] source, Int32 sourceIndex, IBuffer destination, UInt32 destinationIndex, Int32 count) { if (source == null) throw new ArgumentNullException("source"); if (destination == null) throw new ArgumentNullException("destination"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (sourceIndex < 0) throw new ArgumentOutOfRangeException("sourceIndex"); if (destinationIndex < 0) throw new ArgumentOutOfRangeException("destinationIndex"); if (source.Length <= sourceIndex) throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds, "sourceIndex"); if (source.Length - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); if (destination.Capacity - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer); Contract.EndContractBlock(); // If destination is backed by a managed array, use the array instead of the pointer as it does not require pinning: Byte[] destDataArr; Int32 destDataOffs; if (destination.TryGetUnderlyingData(out destDataArr, out destDataOffs)) { Array.Copy(source, sourceIndex, destDataArr, (int)(destDataOffs + destinationIndex), count); return; } IntPtr destPtr = destination.GetPointerAtOffset(destinationIndex); Marshal.Copy(source, sourceIndex, destPtr, count); } #endregion (Byte []).CopyTo extensions for copying to an (IBuffer) #region (IBuffer).ToArray extensions for copying to a new (Byte []) [CLSCompliant(false)] public static Byte[] ToArray(this IBuffer source) { if (source == null) throw new ArgumentNullException("source"); Contract.EndContractBlock(); return ToArray(source, 0, checked((Int32)source.Length)); } [CLSCompliant(false)] public static Byte[] ToArray(this IBuffer source, UInt32 sourceIndex, Int32 count) { if (source == null) throw new ArgumentNullException("source"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (sourceIndex < 0) throw new ArgumentOutOfRangeException("sourceIndex"); if (source.Capacity <= sourceIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity); if (source.Capacity - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInSourceBuffer); Contract.EndContractBlock(); if (count == 0) return Array.Empty<Byte>(); Byte[] destination = new Byte[count]; source.CopyTo(sourceIndex, destination, 0, count); return destination; } #endregion (IBuffer).ToArray extensions for copying to a new (Byte []) #region (IBuffer).CopyTo extensions for copying to a (Byte []) [CLSCompliant(false)] public static void CopyTo(this IBuffer source, Byte[] destination) { if (source == null) throw new ArgumentNullException("source"); if (destination == null) throw new ArgumentNullException("destination"); Contract.EndContractBlock(); CopyTo(source, 0, destination, 0, checked((Int32)source.Length)); } [CLSCompliant(false)] public static void CopyTo(this IBuffer source, UInt32 sourceIndex, Byte[] destination, Int32 destinationIndex, Int32 count) { if (source == null) throw new ArgumentNullException("source"); if (destination == null) throw new ArgumentNullException("destination"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (sourceIndex < 0) throw new ArgumentOutOfRangeException("sourceIndex"); if (destinationIndex < 0) throw new ArgumentOutOfRangeException("destinationIndex"); if (source.Capacity <= sourceIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity); if (source.Capacity - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInSourceBuffer); if (destination.Length <= destinationIndex) throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds); if (destination.Length - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); Contract.EndContractBlock(); // If source is backed by a managed array, use the array instead of the pointer as it does not require pinning: Byte[] srcDataArr; Int32 srcDataOffs; if (source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs)) { Array.Copy(srcDataArr, (int)(srcDataOffs + sourceIndex), destination, destinationIndex, count); return; } IntPtr srcPtr = source.GetPointerAtOffset(sourceIndex); Marshal.Copy(srcPtr, destination, destinationIndex, count); } #endregion (IBuffer).CopyTo extensions for copying to a (Byte []) #region (IBuffer).CopyTo extensions for copying to an (IBuffer) [CLSCompliant(false)] public static void CopyTo(this IBuffer source, IBuffer destination) { if (source == null) throw new ArgumentNullException("source"); if (destination == null) throw new ArgumentNullException("destination"); Contract.EndContractBlock(); CopyTo(source, 0, destination, 0, source.Length); } [CLSCompliant(false)] public static void CopyTo(this IBuffer source, UInt32 sourceIndex, IBuffer destination, UInt32 destinationIndex, UInt32 count) { if (source == null) throw new ArgumentNullException("source"); if (destination == null) throw new ArgumentNullException("destination"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (sourceIndex < 0) throw new ArgumentOutOfRangeException("sourceIndex"); if (destinationIndex < 0) throw new ArgumentOutOfRangeException("destinationIndex"); if (source.Capacity <= sourceIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity); if (source.Capacity - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInSourceBuffer); if (destination.Capacity <= destinationIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity); if (destination.Capacity - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer); Contract.EndContractBlock(); // If source are destination are backed by managed arrays, use the arrays instead of the pointers as it does not require pinning: Byte[] srcDataArr, destDataArr; Int32 srcDataOffs, destDataOffs; bool srcIsManaged = source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs); bool destIsManaged = destination.TryGetUnderlyingData(out destDataArr, out destDataOffs); if (srcIsManaged && destIsManaged) { Debug.Assert(count <= Int32.MaxValue); Debug.Assert(sourceIndex <= Int32.MaxValue); Debug.Assert(destinationIndex <= Int32.MaxValue); Array.Copy(srcDataArr, srcDataOffs + (Int32)sourceIndex, destDataArr, destDataOffs + (Int32)destinationIndex, (Int32)count); return; } IntPtr srcPtr, destPtr; if (srcIsManaged) { Debug.Assert(count <= Int32.MaxValue); Debug.Assert(sourceIndex <= Int32.MaxValue); destPtr = destination.GetPointerAtOffset(destinationIndex); Marshal.Copy(srcDataArr, srcDataOffs + (Int32)sourceIndex, destPtr, (Int32)count); return; } if (destIsManaged) { Debug.Assert(count <= Int32.MaxValue); Debug.Assert(destinationIndex <= Int32.MaxValue); srcPtr = source.GetPointerAtOffset(sourceIndex); Marshal.Copy(srcPtr, destDataArr, destDataOffs + (Int32)destinationIndex, (Int32)count); return; } srcPtr = source.GetPointerAtOffset(sourceIndex); destPtr = destination.GetPointerAtOffset(destinationIndex); MemCopy(srcPtr, destPtr, count); } #endregion (IBuffer).CopyTo extensions for copying to an (IBuffer) #region Access to underlying array optimised for IBuffers backed by managed arrays (to avoid pinning) /// <summary> /// If the specified <code>IBuffer</code> is backed by a managed array, this method will return <code>true</code> and /// set <code>underlyingDataArray</code> to refer to that array /// and <code>underlyingDataArrayStartOffset</code> to the value at which the buffer data begins in that array. /// If the specified <code>IBuffer</code> is <em>not</em> backed by a managed array, this method will return <code>false</code>. /// This method is required by managed APIs that wish to use the buffer's data with other managed APIs that use /// arrays without a need for a memory copy. /// </summary> /// <param name="buffer">An <code>IBuffer</code>.</param> /// <param name="underlyingDataArray">Will be set to the data array backing <code>buffer</code> or to <code>null</code>.</param> /// <param name="underlyingDataArrayStartOffset">Will be set to the start offset of the buffer data in the backing array /// or to <code>-1</code>.</param> /// <returns>Whether the <code>IBuffer</code> is backed by a managed byte array.</returns> internal static bool TryGetUnderlyingData(this IBuffer buffer, out Byte[] underlyingDataArray, out Int32 underlyingDataArrayStartOffset) { if (buffer == null) throw new ArgumentNullException("buffer"); Contract.EndContractBlock(); WindowsRuntimeBuffer winRtBuffer = buffer as WindowsRuntimeBuffer; if (winRtBuffer == null) { underlyingDataArray = null; underlyingDataArrayStartOffset = -1; return false; } winRtBuffer.GetUnderlyingData(out underlyingDataArray, out underlyingDataArrayStartOffset); return true; } /// <summary> /// Checks if the underlying memory backing two <code>IBuffer</code> intances is actually the same memory. /// When applied to <code>IBuffer</code> instances backed by managed arrays this method is preferable to a naive comparison /// (such as <code>((IBufferByteAccess) buffer).Buffer == ((IBufferByteAccess) otherBuffer).Buffer</code>) because it avoids /// pinning the backing array which would be necessary if a direct memory pointer was obtained. /// </summary> /// <param name="buffer">An <code>IBuffer</code> instance.</param> /// <param name="otherBuffer">An <code>IBuffer</code> instance or <code>null</code>.</param> /// <returns><code>true</code> if the underlying <code>Buffer</code> memory pointer is the same for both specified /// <code>IBuffer</code> instances (i.e. if they are backed by the same memory); <code>false</code> otherwise.</returns> [CLSCompliant(false)] public static bool IsSameData(this IBuffer buffer, IBuffer otherBuffer) { if (buffer == null) throw new ArgumentNullException("buffer"); Contract.EndContractBlock(); if (otherBuffer == null) return false; if (buffer == otherBuffer) return true; Byte[] thisDataArr, otherDataArr; Int32 thisDataOffs, otherDataOffs; bool thisIsManaged = buffer.TryGetUnderlyingData(out thisDataArr, out thisDataOffs); bool otherIsManaged = otherBuffer.TryGetUnderlyingData(out otherDataArr, out otherDataOffs); if (thisIsManaged != otherIsManaged) return false; if (thisIsManaged) return (thisDataArr == otherDataArr) && (thisDataOffs == otherDataOffs); IBufferByteAccess thisBuff = (IBufferByteAccess)buffer; IBufferByteAccess otherBuff = (IBufferByteAccess)otherBuffer; unsafe { return (thisBuff.GetBuffer() == otherBuff.GetBuffer()); } } #endregion Access to underlying array optimised for IBuffers backed by managed arrays (to avoid pinning) #region Extensions for co-operation with memory streams (share mem stream data; expose data as managed/unmanaged mem stream) /// <summary> /// Creates a new <code>IBuffer<code> instance backed by the same memory as is backing the specified <code>MemoryStream</code>. /// The <code>MemoryStream</code> may re-sized in future, as a result the stream will be backed by a different memory region. /// In such case, the buffer created by this method will remain backed by the memory behind the stream at the time the buffer was created.<br /> /// This method can throw an <code>ObjectDisposedException</code> if the specified stream is closed.<br /> /// This method can throw an <code>UnauthorizedAccessException</code> if the specified stream cannot expose its underlying memory buffer. /// </summary> /// <param name="underlyingStream">A memory stream to share the data memory with the buffer being created.</param> /// <returns>A new <code>IBuffer<code> backed by the same memory as this specified stream.</returns> // The naming inconsistency with (Byte []).AsBuffer is intentional: as this extension method will appear on // MemoryStream, consistency with method names on MemoryStream is more important. There we already have an API // called GetBuffer which returns the underlying array. [CLSCompliant(false)] public static IBuffer GetWindowsRuntimeBuffer(this MemoryStream underlyingStream) { if (underlyingStream == null) throw new ArgumentNullException("underlyingStream"); Contract.Ensures(Contract.Result<IBuffer>() != null); Contract.Ensures(Contract.Result<IBuffer>().Length == underlyingStream.Length); Contract.Ensures(Contract.Result<IBuffer>().Capacity == underlyingStream.Capacity); Contract.EndContractBlock(); ArraySegment<byte> streamData; if (!underlyingStream.TryGetBuffer(out streamData)) { throw new UnauthorizedAccessException(SR.UnauthorizedAccess_InternalBuffer); } return new WindowsRuntimeBuffer(streamData.Array, (Int32)streamData.Offset, (Int32)underlyingStream.Length, underlyingStream.Capacity); } /// <summary> /// Creates a new <code>IBuffer<code> instance backed by the same memory as is backing the specified <code>MemoryStream</code>. /// The <code>MemoryStream</code> may re-sized in future, as a result the stream will be backed by a different memory region. /// In such case buffer created by this method will remain backed by the memory behind the stream at the time the buffer was created.<br /> /// This method can throw an <code>ObjectDisposedException</code> if the specified stream is closed.<br /> /// This method can throw an <code>UnauthorizedAccessException</code> if the specified stream cannot expose its underlying memory buffer. /// The created buffer begins at position <code>positionInStream</code> in the stream and extends over up to <code>length</code> bytes. /// If the stream has less than <code>length</code> bytes after the specified starting position, the created buffer covers only as many /// bytes as available in the stream. In either case, the <code>Length</code> and the <code>Capacity</code> properties of the created /// buffer are set accordingly: <code>Capacity</code> - number of bytes between <code>positionInStream</code> and the stream capacity end, /// but not more than <code>length</code>; <code>Length</code> - number of bytes between <code>positionInStream</code> and the stream /// length end, or zero if <code>positionInStream</code> is beyond stream length end, but not more than <code>length</code>. /// </summary> /// <param name="underlyingStream">A memory stream to share the data memory with the buffer being created.</param> /// <returns>A new <code>IBuffer<code> backed by the same memory as this specified stream.</returns> // The naming inconsistency with (Byte []).AsBuffer is intentional: as this extension method will appear on // MemoryStream, consistency with method names on MemoryStream is more important. There we already have an API // called GetBuffer which returns the underlying array. [CLSCompliant(false)] public static IBuffer GetWindowsRuntimeBuffer(this MemoryStream underlyingStream, Int32 positionInStream, Int32 length) { if (underlyingStream == null) throw new ArgumentNullException("underlyingStream"); if (positionInStream < 0) throw new ArgumentOutOfRangeException("positionInStream"); if (length < 0) throw new ArgumentOutOfRangeException("length"); if (underlyingStream.Capacity <= positionInStream) throw new ArgumentException(SR.Argument_StreamPositionBeyondEOS); Contract.Ensures(Contract.Result<IBuffer>() != null); Contract.Ensures(Contract.Result<IBuffer>().Length == length); Contract.Ensures(Contract.Result<IBuffer>().Capacity == length); Contract.EndContractBlock(); ArraySegment<byte> streamData; if (!underlyingStream.TryGetBuffer(out streamData)) { throw new UnauthorizedAccessException(SR.UnauthorizedAccess_InternalBuffer); } Int32 originInStream = streamData.Offset; Debug.Assert(underlyingStream.Length <= Int32.MaxValue); Int32 buffCapacity = Math.Min(length, underlyingStream.Capacity - positionInStream); Int32 buffLength = Math.Max(0, Math.Min(length, ((Int32)underlyingStream.Length) - positionInStream)); return new WindowsRuntimeBuffer(streamData.Array, originInStream + positionInStream, buffLength, buffCapacity); } [CLSCompliant(false)] public static Stream AsStream(this IBuffer source) { if (source == null) throw new ArgumentNullException("source"); Contract.Ensures(Contract.Result<Stream>() != null); Contract.Ensures(Contract.Result<Stream>().Length == (UInt32)source.Capacity); Contract.EndContractBlock(); Byte[] dataArr; Int32 dataOffs; if (source.TryGetUnderlyingData(out dataArr, out dataOffs)) { Debug.Assert(source.Capacity < Int32.MaxValue); return new MemoryStream(dataArr, dataOffs, (Int32)source.Capacity, true); } unsafe { IBufferByteAccess bufferByteAccess = (IBufferByteAccess)source; return new WindowsRuntimeBufferUnmanagedMemoryStream(source, (byte*)bufferByteAccess.GetBuffer()); } } #endregion Extensions for co-operation with memory streams (share mem stream data; expose data as managed/unmanaged mem stream) #region Extensions for direct by-offset access to buffer data elements [CLSCompliant(false)] public static Byte GetByte(this IBuffer source, UInt32 byteOffset) { if (source == null) throw new ArgumentNullException("source"); if (byteOffset < 0) throw new ArgumentOutOfRangeException("byteOffset"); if (source.Capacity <= byteOffset) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity, "byteOffset"); Contract.EndContractBlock(); Byte[] srcDataArr; Int32 srcDataOffs; if (source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs)) { return srcDataArr[srcDataOffs + byteOffset]; } IntPtr srcPtr = source.GetPointerAtOffset(byteOffset); unsafe { // Let's avoid an unnesecary call to Marshal.ReadByte(): Byte* ptr = (Byte*)srcPtr; return *ptr; } } #endregion Extensions for direct by-offset access to buffer data elements #region Private plumbing private class WindowsRuntimeBufferUnmanagedMemoryStream : UnmanagedMemoryStream { // We need this class because if we construct an UnmanagedMemoryStream on an IBuffer backed by native memory, // we must keep around a reference to the IBuffer from which we got the memory pointer. Otherwise the ref count // of the underlying COM object may drop to zero and the memory may get freed. private IBuffer _sourceBuffer; internal unsafe WindowsRuntimeBufferUnmanagedMemoryStream(IBuffer sourceBuffer, Byte* dataPtr) : base(dataPtr, (Int64)sourceBuffer.Length, (Int64)sourceBuffer.Capacity, FileAccess.ReadWrite) { _sourceBuffer = sourceBuffer; } } // class WindowsRuntimeBufferUnmanagedMemoryStream private static IntPtr GetPointerAtOffset(this IBuffer buffer, UInt32 offset) { Debug.Assert(0 <= offset); Debug.Assert(offset < buffer.Capacity); unsafe { IntPtr buffPtr = ((IBufferByteAccess)buffer).GetBuffer(); return new IntPtr((byte*)buffPtr + offset); } } private static unsafe void MemCopy(IntPtr src, IntPtr dst, UInt32 count) { if (count > Int32.MaxValue) { MemCopy(src, dst, Int32.MaxValue); MemCopy(src + Int32.MaxValue, dst + Int32.MaxValue, count - Int32.MaxValue); return; } Debug.Assert(count <= Int32.MaxValue); Int32 bCount = (Int32)count; // Copy via buffer. // Note: if becomes perf critical, we will port the routine that // copies the data without using Marshal (and byte[]) Byte[] tmp = new Byte[bCount]; Marshal.Copy(src, tmp, 0, bCount); Marshal.Copy(tmp, 0, dst, bCount); return; } #endregion Private plumbing } // class WindowsRuntimeBufferExtensions } // namespace // WindowsRuntimeBufferExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using Funq; using ServiceStack.CacheAccess; using ServiceStack.CacheAccess.Providers; using ServiceStack.Common; using ServiceStack.Common.Web; using ServiceStack.Html; using ServiceStack.IO; using ServiceStack.MiniProfiler; using ServiceStack.ServiceHost; using ServiceStack.VirtualPath; using ServiceStack.ServiceModel.Serialization; using ServiceStack.WebHost.Endpoints.Extensions; using ServiceStack.WebHost.Endpoints.Formats; using ServiceStack.WebHost.Endpoints.Support; using ServiceStack.WebHost.Endpoints.Utils; namespace ServiceStack.WebHost.Endpoints { public class EndpointHost { public static IAppHost AppHost { get; internal set; } public static IContentTypeFilter ContentTypeFilter { get; set; } public static List<Action<IHttpRequest, IHttpResponse>> RawRequestFilters { get; private set; } public static List<Action<IHttpRequest, IHttpResponse, object>> RequestFilters { get; private set; } public static List<Action<IHttpRequest, IHttpResponse, object>> ResponseFilters { get; private set; } public static List<IViewEngine> ViewEngines { get; set; } public static HandleUncaughtExceptionDelegate ExceptionHandler { get; set; } public static HandleServiceExceptionDelegate ServiceExceptionHandler { get; set; } public static List<HttpHandlerResolverDelegate> CatchAllHandlers { get; set; } private static bool pluginsLoaded = false; public static List<IPlugin> Plugins { get; set; } public static IVirtualPathProvider VirtualPathProvider { get; set; } public static DateTime StartedAt { get; set; } public static DateTime ReadyAt { get; set; } private static void Reset() { ContentTypeFilter = HttpResponseFilter.Instance; RawRequestFilters = new List<Action<IHttpRequest, IHttpResponse>>(); RequestFilters = new List<Action<IHttpRequest, IHttpResponse, object>>(); ResponseFilters = new List<Action<IHttpRequest, IHttpResponse, object>>(); ViewEngines = new List<IViewEngine>(); CatchAllHandlers = new List<HttpHandlerResolverDelegate>(); Plugins = new List<IPlugin> { new HtmlFormat(), new CsvFormat(), new MarkdownFormat(), new PredefinedRoutesFeature(), new MetadataFeature(), }; //Default Config for projects that want to use components but not WebFramework (e.g. MVC) Config = new EndpointHostConfig( "Empty Config", new ServiceManager(new Container(), new ServiceController(null))); } // Pre user config public static void ConfigureHost(IAppHost appHost, string serviceName, ServiceManager serviceManager) { Reset(); AppHost = appHost; EndpointHostConfig.Instance.ServiceName = serviceName; EndpointHostConfig.Instance.ServiceManager = serviceManager; var config = EndpointHostConfig.Instance; Config = config; // avoid cross-dependency on Config setter VirtualPathProvider = new FileSystemVirtualPathProvider(AppHost, Config.WebHostPhysicalPath); Config.DebugMode = appHost.GetType().Assembly.IsDebugBuild(); if (Config.DebugMode) { Plugins.Add(new RequestInfoFeature()); } } // Config has changed private static void ApplyConfigChanges() { config.ServiceEndpointsMetadataConfig = ServiceEndpointsMetadataConfig.Create(config.ServiceStackHandlerFactoryPath); JsonDataContractSerializer.Instance.UseBcl = config.UseBclJsonSerializers; JsonDataContractDeserializer.Instance.UseBcl = config.UseBclJsonSerializers; } //After configure called public static void AfterInit() { StartedAt = DateTime.UtcNow; if (config.EnableFeatures != Feature.All) { if ((Feature.Xml & config.EnableFeatures) != Feature.Xml) config.IgnoreFormatsInMetadata.Add("xml"); if ((Feature.Json & config.EnableFeatures) != Feature.Json) config.IgnoreFormatsInMetadata.Add("json"); if ((Feature.Jsv & config.EnableFeatures) != Feature.Jsv) config.IgnoreFormatsInMetadata.Add("jsv"); if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) config.IgnoreFormatsInMetadata.Add("csv"); if ((Feature.Html & config.EnableFeatures) != Feature.Html) config.IgnoreFormatsInMetadata.Add("html"); if ((Feature.Soap11 & config.EnableFeatures) != Feature.Soap11) config.IgnoreFormatsInMetadata.Add("soap11"); if ((Feature.Soap12 & config.EnableFeatures) != Feature.Soap12) config.IgnoreFormatsInMetadata.Add("soap12"); } if ((Feature.Html & config.EnableFeatures) != Feature.Html) Plugins.RemoveAll(x => x is HtmlFormat); if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) Plugins.RemoveAll(x => x is CsvFormat); if ((Feature.Markdown & config.EnableFeatures) != Feature.Markdown) Plugins.RemoveAll(x => x is MarkdownFormat); if ((Feature.PredefinedRoutes & config.EnableFeatures) != Feature.PredefinedRoutes) Plugins.RemoveAll(x => x is PredefinedRoutesFeature); if ((Feature.Metadata & config.EnableFeatures) != Feature.Metadata) Plugins.RemoveAll(x => x is MetadataFeature); if ((Feature.RequestInfo & config.EnableFeatures) != Feature.RequestInfo) Plugins.RemoveAll(x => x is RequestInfoFeature); if ((Feature.Razor & config.EnableFeatures) != Feature.Razor) Plugins.RemoveAll(x => x is IRazorPlugin); //external if ((Feature.ProtoBuf & config.EnableFeatures) != Feature.ProtoBuf) Plugins.RemoveAll(x => x is IProtoBufPlugin); //external if ((Feature.MsgPack & config.EnableFeatures) != Feature.MsgPack) Plugins.RemoveAll(x => x is IMsgPackPlugin); //external if (ExceptionHandler == null) { ExceptionHandler = (httpReq, httpRes, operationName, ex) => { var errorMessage = String.Format("Error occured while Processing Request: {0}", ex.Message); var statusCode = ex.ToStatusCode(); //httpRes.WriteToResponse always calls .Close in it's finally statement so //if there is a problem writing to response, by now it will be closed if (!httpRes.IsClosed) { httpRes.WriteErrorToResponse(httpReq, httpReq.ResponseContentType, operationName, errorMessage, ex, statusCode); } }; } if (config.ServiceStackHandlerFactoryPath != null) config.ServiceStackHandlerFactoryPath = config.ServiceStackHandlerFactoryPath.TrimStart('/'); var specifiedContentType = config.DefaultContentType; //Before plugins loaded ConfigurePlugins(); AppHost.LoadPlugin(Plugins.ToArray()); pluginsLoaded = true; AfterPluginsLoaded(specifiedContentType); var registeredCacheClient = AppHost.TryResolve<ICacheClient>(); using (registeredCacheClient) { if (registeredCacheClient == null) { Container.Register<ICacheClient>(new MemoryCacheClient()); } } ReadyAt = DateTime.UtcNow; } public static T TryResolve<T>() { return AppHost != null ? AppHost.TryResolve<T>() : default(T); } /// <summary> /// The AppHost.Container. Note: it is not thread safe to register dependencies after AppStart. /// </summary> public static Container Container { get { var aspHost = AppHost as AppHostBase; if (aspHost != null) return aspHost.Container; var listenerHost = AppHost as HttpListenerBase; return listenerHost != null ? listenerHost.Container : new Container(); //testing may use alt AppHost } } private static void ConfigurePlugins() { //Some plugins need to initialize before other plugins are registered. foreach (var plugin in Plugins) { var preInitPlugin = plugin as IPreInitPlugin; if (preInitPlugin != null) { preInitPlugin.Configure(AppHost); } } } private static void AfterPluginsLoaded(string specifiedContentType) { if (!String.IsNullOrEmpty(specifiedContentType)) config.DefaultContentType = specifiedContentType; else if (String.IsNullOrEmpty(config.DefaultContentType)) config.DefaultContentType = ContentType.Json; config.ServiceManager.AfterInit(); ServiceManager = config.ServiceManager; //reset operations } public static T GetPlugin<T>() where T : class, IPlugin { return Plugins.FirstOrDefault(x => x is T) as T; } public static void AddPlugin(params IPlugin[] plugins) { if (pluginsLoaded) { AppHost.LoadPlugin(plugins); } else { foreach (var plugin in plugins) { Plugins.Add(plugin); } } } public static ServiceManager ServiceManager { get { return config.ServiceManager; } set { config.ServiceManager = value; } } private static EndpointHostConfig config; public static EndpointHostConfig Config { get { return config; } set { if (value.ServiceName == null) throw new ArgumentNullException("ServiceName"); if (value.ServiceController == null) throw new ArgumentNullException("ServiceController"); config = value; ApplyConfigChanges(); } } public static bool DebugMode { get { return Config != null && Config.DebugMode; } } public static ServiceMetadata Metadata { get { return Config.Metadata; } } /// <summary> /// Applies the raw request filters. Returns whether or not the request has been handled /// and no more processing should be done. /// </summary> /// <returns></returns> public static bool ApplyPreRequestFilters(IHttpRequest httpReq, IHttpResponse httpRes) { foreach (var requestFilter in RawRequestFilters) { requestFilter(httpReq, httpRes); if (httpRes.IsClosed) break; } return httpRes.IsClosed; } /// <summary> /// Applies the request filters. Returns whether or not the request has been handled /// and no more processing should be done. /// </summary> /// <returns></returns> public static bool ApplyRequestFilters(IHttpRequest httpReq, IHttpResponse httpRes, object requestDto) { httpReq.ThrowIfNull("httpReq"); httpRes.ThrowIfNull("httpRes"); using (Profiler.Current.Step("Executing Request Filters")) { //Exec all RequestFilter attributes with Priority < 0 var attributes = FilterAttributeCache.GetRequestFilterAttributes(requestDto.GetType()); var i = 0; for (; i < attributes.Length && attributes[i].Priority < 0; i++) { var attribute = attributes[i]; ServiceManager.Container.AutoWire(attribute); attribute.RequestFilter(httpReq, httpRes, requestDto); if (AppHost != null) //tests AppHost.Release(attribute); if (httpRes.IsClosed) return httpRes.IsClosed; } //Exec global filters foreach (var requestFilter in RequestFilters) { requestFilter(httpReq, httpRes, requestDto); if (httpRes.IsClosed) return httpRes.IsClosed; } //Exec remaining RequestFilter attributes with Priority >= 0 for (; i < attributes.Length; i++) { var attribute = attributes[i]; ServiceManager.Container.AutoWire(attribute); attribute.RequestFilter(httpReq, httpRes, requestDto); if (AppHost != null) //tests AppHost.Release(attribute); if (httpRes.IsClosed) return httpRes.IsClosed; } return httpRes.IsClosed; } } /// <summary> /// Applies the response filters. Returns whether or not the request has been handled /// and no more processing should be done. /// </summary> /// <returns></returns> public static bool ApplyResponseFilters(IHttpRequest httpReq, IHttpResponse httpRes, object response) { httpReq.ThrowIfNull("httpReq"); httpRes.ThrowIfNull("httpRes"); using (Profiler.Current.Step("Executing Response Filters")) { var responseDto = response.ToResponseDto(); var attributes = responseDto != null ? FilterAttributeCache.GetResponseFilterAttributes(responseDto.GetType()) : null; //Exec all ResponseFilter attributes with Priority < 0 var i = 0; if (attributes != null) { for (; i < attributes.Length && attributes[i].Priority < 0; i++) { var attribute = attributes[i]; ServiceManager.Container.AutoWire(attribute); attribute.ResponseFilter(httpReq, httpRes, response); if (AppHost != null) //tests AppHost.Release(attribute); if (httpRes.IsClosed) return httpRes.IsClosed; } } //Exec global filters foreach (var responseFilter in ResponseFilters) { responseFilter(httpReq, httpRes, response); if (httpRes.IsClosed) return httpRes.IsClosed; } //Exec remaining RequestFilter attributes with Priority >= 0 if (attributes != null) { for (; i < attributes.Length; i++) { var attribute = attributes[i]; ServiceManager.Container.AutoWire(attribute); attribute.ResponseFilter(httpReq, httpRes, response); if (AppHost != null) //tests AppHost.Release(attribute); if (httpRes.IsClosed) return httpRes.IsClosed; } } return httpRes.IsClosed; } } internal static object ExecuteService(object request, EndpointAttributes endpointAttributes, IHttpRequest httpReq, IHttpResponse httpRes) { using (Profiler.Current.Step("Execute Service")) { return config.ServiceController.Execute(request, new HttpRequestContext(httpReq, httpRes, request, endpointAttributes)); } } public static IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext) { return AppHost != null ? AppHost.CreateServiceRunner<TRequest>(actionContext) : new ServiceRunner<TRequest>(null, actionContext); } /// <summary> /// Call to signal the completion of a ServiceStack-handled Request /// </summary> internal static void CompleteRequest() { try { if (AppHost != null) { AppHost.OnEndRequest(); } } catch (Exception ex) { } } public static void Dispose() { AppHost = null; } } }
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 Search.PersonalizedResults { 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 } }
/* ==================================================================== 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.Xml; using System.IO; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Data.Odbc; using System.Data.SqlClient; using System.Text; using System.Drawing; using System.Windows.Forms; using System.Text.RegularExpressions; using Microsoft.Win32; using fyiReporting.RDL; using fyiReporting.RdlDesign.Resources; namespace fyiReporting.RdlDesign { /// <summary> /// Static utility classes used in the Rdl Designer /// </summary> internal class DesignerUtility { static internal Color ColorFromHtml(string sc, Color dc) { Color c = dc; try { if (!sc.StartsWith("=")) // don't even try when color is an expression c = ColorTranslator.FromHtml(sc); } catch { // Probably should report this error } return c; } #if MONO static internal bool IsMono() { return true; } #else static internal bool IsMono() { // hack: this allows the same .exe to run under mono or windows Type t = Type.GetType("System.Int32"); return (t.GetType().ToString() == "System.MonoType"); } #endif /// <summary> /// Read the registry to find out the ODBC names /// </summary> static internal void FillOdbcNames(ComboBox cbOdbcNames) { if (cbOdbcNames.Items.Count > 0) return; // System names RegistryKey rk = (Registry.LocalMachine).OpenSubKey("Software"); if (rk == null) return; rk = rk.OpenSubKey("ODBC"); if (rk == null) return; rk = rk.OpenSubKey("ODBC.INI"); string[] nms = rk.GetSubKeyNames(); if (nms != null) { foreach (string name in nms) { if (name == "ODBC Data Sources" || name == "ODBC File DSN" || name == "ODBC") continue; cbOdbcNames.Items.Add(name); } } // User names rk = (Registry.CurrentUser).OpenSubKey("Software"); if (rk == null) return; rk = rk.OpenSubKey("ODBC"); if (rk == null) return; rk = rk.OpenSubKey("ODBC.INI"); nms = rk.GetSubKeyNames(); if (nms != null) { foreach (string name in nms) { if (name == "ODBC Data Sources" || name == "ODBC File DSN" || name == "ODBC") continue; cbOdbcNames.Items.Add(name); } } return; } static internal string FormatXml(string sDoc) { XmlDocument xDoc = new XmlDocument(); xDoc.PreserveWhitespace = false; xDoc.LoadXml(sDoc); // this will throw an exception if invalid XML StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); xtw.IndentChar = ' '; xtw.Indentation = 2; xtw.Formatting = Formatting.Indented; xDoc.WriteContentTo(xtw); xtw.Close(); sw.Close(); return sw.ToString(); } static internal bool GetSharedConnectionInfo(RdlUserControl dsr, string filename, out string dataProvider, out string connectInfo) { dataProvider = null; connectInfo = null; string pswd = null; string xml = ""; try { pswd = dsr.GetPassword(); if (pswd == null) return false; if (!filename.EndsWith(".dsr", StringComparison.InvariantCultureIgnoreCase)) filename += ".dsr"; xml = RDL.DataSourceReference.Retrieve(filename, pswd); } catch { MessageBox.Show(Strings.DesignerUtility_Show_SharedConnectionError, Strings.DesignerUtility_Show_TestConnection); dsr.ResetPassword(); // make sure to prompt again for the password return false; } XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(xml); XmlNode xNodeLoop = xDoc.FirstChild; foreach (XmlNode node in xNodeLoop.ChildNodes) { switch (node.Name) { case "DataProvider": dataProvider = node.InnerText; break; case "ConnectString": connectInfo = node.InnerText; break; default: break; } } return true; } static internal bool GetSharedConnectionInfo(RdlDesigner dsr, string filename, out string dataProvider, out string connectInfo) { dataProvider = null; connectInfo = null; string pswd = null; string xml = ""; try { pswd = dsr.GetPassword(); if (pswd == null) return false; if (!filename.EndsWith(".dsr", StringComparison.InvariantCultureIgnoreCase)) filename += ".dsr"; xml = RDL.DataSourceReference.Retrieve(filename, pswd); } catch { MessageBox.Show(Strings.DesignerUtility_Show_SharedConnectionError, Strings.DesignerUtility_Show_TestConnection); dsr.ResetPassword(); // make sure to prompt again for the password return false; } XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(xml); XmlNode xNodeLoop = xDoc.FirstChild; foreach (XmlNode node in xNodeLoop.ChildNodes) { switch (node.Name) { case "DataProvider": dataProvider = node.InnerText; break; case "ConnectString": connectInfo = node.InnerText; break; default: break; } } return true; } static internal void GetSqlData(string dataProvider, string connection, string sql, IList parameters, DataTable dt) { IDbConnection cnSQL=null; IDbCommand cmSQL=null; IDataReader dr=null; Cursor saveCursor=Cursor.Current; Cursor.Current = Cursors.WaitCursor; try { // Open up a connection cnSQL = RdlEngineConfig.GetConnection(dataProvider, connection); if (cnSQL == null) return; cnSQL.Open(); cmSQL = cnSQL.CreateCommand(); cmSQL.CommandText = sql; AddParameters(cmSQL, parameters); dr = cmSQL.ExecuteReader(CommandBehavior.SingleResult); object[] rowValues = new object[dt.Columns.Count]; while (dr.Read()) { int ci=0; foreach (DataColumn dc in dt.Columns) { object v = dr[dc.ColumnName]; // string val = Convert.ToString(dr[dc.ColumnName], System.Globalization.NumberFormatInfo.InvariantInfo); // rowValues[ci++] = val; rowValues[ci++] = v; } dt.Rows.Add(rowValues); } } finally { if (cnSQL != null) { cnSQL.Close(); cnSQL.Dispose(); if (cmSQL != null) { cmSQL.Dispose(); if (dr != null) dr.Close(); } } Cursor.Current=saveCursor; } return; } static internal bool GetConnnectionInfo(DesignXmlDraw d, string ds, out string dataProvider, out string connection) { XmlNode dsNode = d.DataSourceName(ds); dataProvider = null; connection = null; if (dsNode == null) return false; string dataSourceReference = d.GetElementValue(dsNode, "DataSourceReference", null); if (dataSourceReference != null) { // This is not very pretty code since it is assuming the structure of the windows parenting. // But there isn't any other way to get this information from here. Control p = d; MDIChild mc = null; while (p != null && !(p is RdlDesigner)) { if (p is MDIChild) mc = (MDIChild)p; p = p.Parent; } if (p == null || mc == null || mc.SourceFile == null) { MessageBox.Show(Strings.DataSetRowsCtl_ShowC_UnableLocateDSR); return false; } Uri filename = new Uri(Path.GetDirectoryName(mc.SourceFile.LocalPath) + Path.DirectorySeparatorChar + dataSourceReference); if (!DesignerUtility.GetSharedConnectionInfo((RdlDesigner)p, filename.LocalPath, out dataProvider, out connection)) { return false; } } else { XmlNode dp = DesignXmlDraw.FindNextInHierarchy(dsNode, "ConnectionProperties", "DataProvider"); if (dp == null) return false; dataProvider = dp.InnerText; dp = DesignXmlDraw.FindNextInHierarchy(dsNode, "ConnectionProperties", "ConnectString"); if (dp == null) return false; connection = dp.InnerText; } return true; } static internal List<SqlColumn> GetSqlColumns(DesignXmlDraw d, string ds, string sql) { string dataProvider; string connection; if (!GetConnnectionInfo(d, ds, out dataProvider, out connection)) return null; IList parameters=null; return GetSqlColumns(dataProvider, connection, sql, parameters); } static internal List<SqlColumn> GetSqlColumns(string dataProvider, string connection, string sql, IList parameters) { List<SqlColumn> cols = new List<SqlColumn>(); IDbConnection cnSQL=null; IDbCommand cmSQL=null; IDataReader dr=null; Cursor saveCursor=Cursor.Current; Cursor.Current = Cursors.WaitCursor; try { // Open up a connection cnSQL = RdlEngineConfig.GetConnection(dataProvider, connection); if (cnSQL == null) return cols; cnSQL.Open(); cmSQL = cnSQL.CreateCommand(); cmSQL.CommandText = sql; AddParameters(cmSQL, parameters); dr = cmSQL.ExecuteReader(CommandBehavior.SchemaOnly); for (int i=0; i < dr.FieldCount; i++) { SqlColumn sc = new SqlColumn(); sc.Name = dr.GetName(i).TrimEnd('\0'); sc.DataType = dr.GetFieldType(i); cols.Add(sc); } } catch (SqlException sqle) { MessageBox.Show(sqle.Message, Strings.DesignerUtility_Show_SQLError); } catch (Exception e) { MessageBox.Show(e.InnerException == null? e.Message:e.InnerException.Message, Strings.DesignerUtility_Show_Error); } finally { if (cnSQL != null) { if (cmSQL != null) { cmSQL.Dispose(); if (dr != null) dr.Close(); } cnSQL.Close(); cnSQL.Dispose(); } Cursor.Current=saveCursor; } return cols; } static internal List<SqlSchemaInfo> GetSchemaInfo(DesignXmlDraw d, string ds) { string dataProvider; string connection; if (!GetConnnectionInfo(d, ds, out dataProvider, out connection)) return null; return GetSchemaInfo(dataProvider, connection); } static internal List<SqlSchemaInfo> GetSchemaInfo(string dataProvider, string connection) { List<SqlSchemaInfo> schemaList = new List<SqlSchemaInfo>(); IDbConnection cnSQL = null; IDbCommand cmSQL = null; IDataReader dr = null; Cursor saveCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; // Get the schema information try { int ID_TABLE = 0; int ID_TYPE = 1; // Open up a connection cnSQL = RdlEngineConfig.GetConnection(dataProvider, connection); if (cnSQL == null) { MessageBox.Show(string.Format(Strings.DesignerUtility_Show_ConnectDataProviderError,dataProvider), Strings.DesignerUtility_Show_SQLError); return schemaList; } cnSQL.Open(); // Take advantage of .Net metadata if available if (cnSQL is System.Data.SqlClient.SqlConnection) return GetSchemaInfo((System.Data.SqlClient.SqlConnection) cnSQL, schemaList); if (cnSQL is System.Data.Odbc.OdbcConnection) return GetSchemaInfo((System.Data.Odbc.OdbcConnection)cnSQL, schemaList); if (cnSQL is System.Data.OleDb.OleDbConnection) return GetSchemaInfo((System.Data.OleDb.OleDbConnection)cnSQL, schemaList); // Obtain the query needed to get table/view list string sql = RdlEngineConfig.GetTableSelect(dataProvider, cnSQL); if (sql == null || sql.Length == 0) // when no query string; no meta information available return schemaList; // Obtain the query needed to get table/view list cmSQL = cnSQL.CreateCommand(); cmSQL.CommandText = sql; dr = cmSQL.ExecuteReader(); string type = "TABLE"; while (dr.Read()) { SqlSchemaInfo ssi = new SqlSchemaInfo(); if (ID_TYPE >= 0 && dr.FieldCount < ID_TYPE && (string) dr[ID_TYPE] == "VIEW") type = "VIEW"; ssi.Type = type; ssi.Name = (string) dr[ID_TABLE]; schemaList.Add(ssi); } } catch (SqlException sqle) { MessageBox.Show(sqle.Message, Strings.DesignerUtility_Show_SQLError); } catch (Exception e) { MessageBox.Show(e.InnerException == null? e.Message: e.InnerException.Message, Strings.DesignerUtility_Show_Error); } finally { if (cnSQL != null) { cnSQL.Close(); if (cmSQL != null) { cmSQL.Dispose(); } if ((dr != null) && (dataProvider != "SQLite")) { dr.Close(); } } Cursor.Current=saveCursor; } return schemaList; } static internal List<SqlSchemaInfo> GetSchemaInfo(System.Data.SqlClient.SqlConnection con, List<SqlSchemaInfo> schemaList) { try { DataTable tbl = con.GetSchema(System.Data.SqlClient.SqlClientMetaDataCollectionNames.Tables); foreach (DataRow row in tbl.Rows) { SqlSchemaInfo ssi = new SqlSchemaInfo(); ssi.Type = "TABLE"; string schema = row["table_schema"] as string; if (schema != null && schema != "dbo") ssi.Name = string.Format("{0}.{1}", schema, (string)row["table_name"]); else ssi.Name = (string)row["table_name"]; schemaList.Add(ssi); } tbl = con.GetSchema(System.Data.SqlClient.SqlClientMetaDataCollectionNames.Views); foreach (DataRow row in tbl.Rows) { SqlSchemaInfo ssi = new SqlSchemaInfo(); ssi.Type = "VIEW"; string schema = row["table_schema"] as string; if (schema != null && schema != "dbo") ssi.Name = string.Format("{0}.{1}", schema, (string)row["table_name"]); else ssi.Name = (string)row["table_name"]; schemaList.Add(ssi); } } catch { } schemaList.Sort(); return schemaList; } static internal List<SqlSchemaInfo> GetSchemaInfo(System.Data.OleDb.OleDbConnection con, List<SqlSchemaInfo> schemaList) { try { DataTable tbl = con.GetSchema(System.Data.OleDb.OleDbMetaDataCollectionNames.Tables); foreach (DataRow row in tbl.Rows) { SqlSchemaInfo ssi = new SqlSchemaInfo(); ssi.Type = "TABLE"; ssi.Name = (string)row["table_name"]; schemaList.Add(ssi); } tbl = con.GetSchema(System.Data.OleDb.OleDbMetaDataCollectionNames.Views); foreach (DataRow row in tbl.Rows) { SqlSchemaInfo ssi = new SqlSchemaInfo(); ssi.Type = "VIEW"; ssi.Name = (string)row["table_name"]; schemaList.Add(ssi); } } catch { } schemaList.Sort(); return schemaList; } static internal List<SqlSchemaInfo> GetSchemaInfo(System.Data.Odbc.OdbcConnection con, List<SqlSchemaInfo> schemaList) { try { DataTable tbl = con.GetSchema(System.Data.Odbc.OdbcMetaDataCollectionNames.Tables); foreach (DataRow row in tbl.Rows) { SqlSchemaInfo ssi = new SqlSchemaInfo(); ssi.Type = "TABLE"; ssi.Name = (string)row["table_name"]; schemaList.Add(ssi); } tbl = con.GetSchema(System.Data.Odbc.OdbcMetaDataCollectionNames.Views); foreach (DataRow row in tbl.Rows) { SqlSchemaInfo ssi = new SqlSchemaInfo(); ssi.Type = "VIEW"; ssi.Name = (string)row["table_name"]; schemaList.Add(ssi); } } catch { } schemaList.Sort(); return schemaList; } static internal string NormalizeSqlName(string name) { // Routine ensures valid sql name if (name == null || name.Length == 0) return ""; // split out the owner name (schema) string schema = null; int si = name.IndexOf('.'); if (si >= 0) { schema = name.Substring(0, si); name = name.Substring(si+1); } bool bLetterOrDigit = (Char.IsLetter(name, 0) || name[0] == '_'); // special rules for 1st character for (int i = 0; i < name.Length && bLetterOrDigit; i++) { if (name[i] == '.') { } // allow names to have a "." for owner qualified tables else if (!(Char.IsLetterOrDigit(name, i) || name[i] == '#' || name[i] == '_')) bLetterOrDigit = false; } if (!bLetterOrDigit) name = "\"" + name + "\""; if (schema == null) return name; return schema + "." + name; } static internal bool TestConnection(string dataProvider, string connection) { IDbConnection cnSQL=null; bool bResult = false; try { cnSQL = RdlEngineConfig.GetConnection(dataProvider, connection); cnSQL.Open(); bResult = true; // we opened the connection } catch (Exception e) { MessageBox.Show(e.InnerException == null? e.Message: e.InnerException.Message, Strings.DesignerUtility_Show_OpenConnectionError); } finally { if (cnSQL != null) { cnSQL.Close(); cnSQL.Dispose(); } } return bResult; } static internal bool IsNumeric(Type t) { string st = t.ToString(); switch (st) { case "System.Int16": case "System.Int32": case "System.Int64": case "System.Single": case "System.Double": case "System.Decimal": return true; default: return false; } } /// <summary> /// Validates a size parameter /// </summary> /// <param name="t"></param> /// <param name="bZero">true if 0 is valid size</param> /// <param name="bMinus">true if minus is allowed</param> /// <returns>Throws exception with the invalid message</returns> internal static void ValidateSize(string t, bool bZero, bool bMinus) { t = t.Trim(); if (t.Length == 0) // not specified is ok? return; // Ensure we have valid units if (t.IndexOf("in") < 0 && t.IndexOf("cm") < 0 && t.IndexOf("mm") < 0 && t.IndexOf("pt") < 0 && t.IndexOf("pc") < 0) { throw new Exception(Strings.DesignerUtility_Error_SizeUnitInvalid); } int space = t.LastIndexOf(' '); string n = ""; // number string string u; // unit string if (space != -1) // any spaces { n = t.Substring(0, space).Trim(); // number string u = t.Substring(space).Trim(); // unit string } else if (t.Length >= 3) { n = t.Substring(0, t.Length - 2).Trim(); u = t.Substring(t.Length - 2).Trim(); } if (n.Length == 0 || !Regex.IsMatch(n, @"\A[ ]*[-]?[0-9]*[.]?[0-9]*[ ]*\Z")) { throw new Exception(Strings.DesignerUtility_Error_NumberFormatinvalid); } float v = DesignXmlDraw.GetSize(t); if (!bZero) { if (v < .1) throw new Exception(Strings.DesignerUtility_Error_SizeZero); } else if (v < 0 && !bMinus) throw new Exception(Strings.DesignerUtility_Error_SizeLessZero); } static internal string MakeValidSize(string t, bool bZero) { return MakeValidSize(t, bZero, false); } /// <summary> /// Ensures that a user provided string results in a valid size /// </summary> /// <param name="t"></param> /// <returns></returns> static internal string MakeValidSize(string t, bool bZero, bool bNegative) { // Ensure we have valid units if (t.IndexOf("in") < 0 && t.IndexOf("cm") < 0 && t.IndexOf("mm") < 0 && t.IndexOf("pt") < 0 && t.IndexOf("pc") < 0) { t += "in"; } float v = DesignXmlDraw.GetSize(t); if (!bZero) { if (v < .1) t = ".1pt"; } if (!bNegative) { if (v < 0) t = "0in"; } return t; } static private void AddParameters(IDbCommand cmSQL, IList parameters) { if (parameters == null || parameters.Count <= 0) return; foreach(ReportParm rp in parameters) { string paramName; // force the name to start with @ if (rp.Name[0] == '@') paramName = rp.Name; else paramName = "@" + rp.Name; IDbDataParameter dp = cmSQL.CreateParameter(); dp.ParameterName = paramName; if (rp.DefaultValue == null || rp.DefaultValue.Count == 0) { object pvalue=null; // put some dummy values in it; some drivers (e.g. mysql odbc) don't like null values switch (rp.DataType.ToLower()) { case "datetime": pvalue = new DateTime(1900, 1, 1); break; case "double": pvalue = new double(); break; case "boolean": pvalue = new Boolean(); break; case "string": default: pvalue = (object) ""; break; } dp.Value = pvalue; } else { string val = (string) rp.DefaultValue[0]; dp.Value = val; } cmSQL.Parameters.Add(dp); } } // From Paul Welter's site: http://weblogs.asp.net/pwelter34/archive/2006/02/08/437677.aspx /// <summary> /// Creates a relative path from one file or folder to another. /// </summary> /// <param name="fromDirectory">Contains the directory that defines the start of the relative path.</param> /// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param> /// <returns>The relative path from the start directory to the end path.</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> public static string RelativePathTo(string fromDirectory, string toPath) { if (fromDirectory == null) throw new ArgumentNullException("fromDirectory"); if (toPath == null) throw new ArgumentNullException("fromDirectory"); if (System.IO.Path.IsPathRooted(fromDirectory) && System.IO.Path.IsPathRooted(toPath)) { if (string.Compare(System.IO.Path.GetPathRoot(fromDirectory), System.IO.Path.GetPathRoot(toPath), true) != 0) { throw new ArgumentException( string.Format("The paths '{0} and '{1}' have different path roots.", fromDirectory, toPath)); } } StringCollection relativePath = new StringCollection(); string[] fromDirectories = fromDirectory.Split(System.IO.Path.DirectorySeparatorChar); string[] toDirectories = toPath.Split(System.IO.Path.DirectorySeparatorChar); int length = Math.Min(fromDirectories.Length, toDirectories.Length); int lastCommonRoot = -1; // find common root for (int x = 0; x < length; x++) { if (string.Compare(fromDirectories[x], toDirectories[x], true) != 0) break; lastCommonRoot = x; } if (lastCommonRoot == -1) { throw new ArgumentException( string.Format("The paths '{0} and '{1}' do not have a common prefix path.", fromDirectory, toPath)); } // add relative folders in from path for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++) if (fromDirectories[x].Length > 0) relativePath.Add(".."); // add to folders to path for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++) relativePath.Add(toDirectories[x]); // create relative path string[] relativeParts = new string[relativePath.Count]; relativePath.CopyTo(relativeParts, 0); string newPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), relativeParts); return newPath; } } internal class SqlColumn { string _Name; Type _DataType; override public string ToString() { return _Name; } internal string Name { get {return _Name;} set {_Name = value;} } internal Type DataType { get {return _DataType;} set {_DataType = value;} } } internal class SqlSchemaInfo : IComparable<SqlSchemaInfo> { string _Name; string _Type; internal string Name { get {return _Name;} set {_Name = value;} } internal string Type { get {return _Type;} set {_Type = value;} } #region IComparable<SqlSchemaInfo> Members int IComparable<SqlSchemaInfo>.CompareTo(SqlSchemaInfo other) { return (this._Type == other._Type)? string.Compare(this.Name, other.Name): string.Compare(this.Type, other.Type); } #endregion } internal class ReportParm { string _Name; string _Prompt; string _DataType; bool _bDefault=true; // use default value if true otherwise DataSetName List<string> _DefaultValue; // list of strings string _DefaultDSRDataSetName; // DefaultValues DataSetReference DataSetName string _DefaultDSRValueField; // DefaultValues DataSetReference ValueField bool _bValid=true; // use valid value if true otherwise DataSetName List<ParameterValueItem> _ValidValues; // list of ParameterValueItem string _ValidValuesDSRDataSetName; // ValidValues DataSetReference DataSetName string _ValidValuesDSRValueField; // ValidValues DataSetReference ValueField string _ValidValuesDSRLabelField; // ValidValues DataSetReference LabelField bool _AllowNull; bool _AllowBlank; bool _MultiValue; internal ReportParm(string name) { _Name = name; _DataType = "String"; } internal string Name { get {return _Name;} set {_Name = value;} } internal string Prompt { get {return _Prompt;} set {_Prompt = value;} } internal string DataType { get {return _DataType;} set {_DataType = value;} } internal bool Valid { get {return _bValid;} set {_bValid = value;} } internal List<ParameterValueItem> ValidValues { get {return _ValidValues;} set {_ValidValues = value;} } internal string ValidValuesDisplay { get { if (_ValidValues == null || _ValidValues.Count == 0) return ""; StringBuilder sb = new StringBuilder(); bool bFirst = true; foreach (ParameterValueItem pvi in _ValidValues) { if (bFirst) bFirst = false; else sb.Append(", "); if (pvi.Label != null) sb.AppendFormat("{0}={1}", pvi.Value, pvi.Label); else sb.Append(pvi.Value); } return sb.ToString(); } } internal bool Default { get {return _bDefault;} set {_bDefault = value;} } internal List<string> DefaultValue { get {return _DefaultValue;} set {_DefaultValue = value;} } internal string DefaultValueDisplay { get { if (_DefaultValue == null || _DefaultValue.Count == 0) return ""; StringBuilder sb = new StringBuilder(); bool bFirst = true; foreach (string dv in _DefaultValue) { if (bFirst) bFirst = false; else sb.Append(", "); sb.Append(dv); } return sb.ToString(); } } internal bool AllowNull { get {return _AllowNull;} set {_AllowNull = value;} } internal bool AllowBlank { get {return _AllowBlank;} set {_AllowBlank = value;} } internal bool MultiValue { get { return _MultiValue; } set { _MultiValue = value; } } internal string DefaultDSRDataSetName { get {return _DefaultDSRDataSetName;} set {_DefaultDSRDataSetName=value;} } internal string DefaultDSRValueField { get {return _DefaultDSRValueField;} set {_DefaultDSRValueField=value;} } internal string ValidValuesDSRDataSetName { get {return _ValidValuesDSRDataSetName;} set {_ValidValuesDSRDataSetName=value;} } internal string ValidValuesDSRValueField { get {return _ValidValuesDSRValueField;} set {_ValidValuesDSRValueField=value;} } internal string ValidValuesDSRLabelField { get {return _ValidValuesDSRLabelField;} set {_ValidValuesDSRLabelField=value;} } override public string ToString() { return _Name; } } internal class ParameterValueItem { internal string Value; internal string Label; } internal class StaticLists { /// <summary> /// Names of colors to put into lists /// </summary> static public readonly string[] ColorListColorSort = new string[] { "Black", "White", "DimGray", "Gray", "DarkGray", "Silver", "LightGray", "Gainsboro", "WhiteSmoke", "Maroon", "DarkRed", "Red", "Brown", "Firebrick", "IndianRed", "Snow", "LightCoral", "RoseyBrown", "MistyRose", "Salmon", "Tomato", "DarkSalmon", "Coral", "OrangeRed", "LightSalmon", "Sienna", "SeaShell", "Chocalate", "SaddleBrown", "SandyBrown", "PeachPuff", "Peru", "Linen", "Bisque", "DarkOrange", "BurlyWood", "Tan", "AntiqueWhite", "NavajoWhite", "BlanchedAlmond", "PapayaWhip", "Moccasin", "Orange", "Wheat", "OldLace", "DarkGoldenrod", "Goldenrod", "Cornsilk", "Gold", "Khaki", "LemonChiffon", "PaleGoldenrod", "DarkKhaki", "Beige", "LightGoldenrodYellow", "Olive", "Yellow", "LightYellow", "Ivory", "OliveDrab", "YellowGreen", "DarkOliveGreen", "GreenYellow", "Chartreuse", "LawnGreen", "DarkSeaGreen", "LightGreen", "ForestGreen", "LimeGreen", "PaleGreen", "DarkGreen", "Green", "Lime", "HoneyDew", "SeaGreen", "MediumSeaGreen", "SpringGreen", "MintCream", "MediumSpringGreen", "MediumAquamarine", "Aquamarine", "Turquoise", "LightSeaGreen", "MediumTurquoise", "DarkSlateGray", "PaleTurQuoise", "Teal", "DarkCyan","Cyan", "Aqua", "LightCyan", "Azure", "DarkTurquoise", "CadetBlue", "PowderBlue", "LightBlue", "DeepSkyBlue", "SkyBlue", "LightSkyBlue", "SteelBlue", "AliceBlue", "DodgerBlue", "SlateGray", "LightSlateGray", "LightSteelBlue", "CornflowerBlue", "RoyalBlue", "MidnightBlue", "Lavender", "Navy", "DarkBlue", "MediumBlue", "Blue", "GhostWhite", "SlateBlue", "DarkSlateBlue", "MediumSlateBlue", "MediumPurple", "BlueViolet", "Indigo", "DarkOrchid", "DarkViolet", "MediumOrchid", "Thistle", "Plum", "Violet", "Purple", "DarkMagenta", "Fuchsia", "Magenta", "Orchid", "MediumVioletRed", "DeepPink", "HotPink", "LavenderBlush", "PaleVioletRed", "Crimson", "Pink", "LightPink", "Floralwhite" }; static public readonly string[] ColorList = new string[] { "Aliceblue", "Antiquewhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "Blanchedalmond", "Blue", "Blueviolet", "Brown", "Burlywood", "Cadetblue", "Chartreuse", "Chocolate", "Coral", "Cornflowerblue", "Cornsilk", "Crimson", "Cyan", "Darkblue", "Darkcyan", "Darkgoldenrod", "Darkgray", "Darkgreen", "Darkkhaki", "Darkmagenta", "Darkolivegreen", "Darkorange", "Darkorchid", "Darkred", "Darksalmon", "Darkseagreen", "Darkslateblue", "Darkslategray", "Darkturquoise", "Darkviolet", "Deeppink", "Deepskyblue", "Dimgray", "Dodgerblue", "Firebrick", "Floralwhite", "Forestgreen", "Fuchsia", "Gainsboro", "Ghostwhite", "Gold", "Goldenrod", "Gray", "Green", "Greenyellow", "Honeydew", "Hotpink", "Indianred", "Indigo", "Ivory", "Khaki", "Lavender", "Lavenderblush", "Lawngreen", "Lemonchiffon", "Lightblue", "Lightcoral", "Lightcyan", "Lightgoldenrodyellow", "Lightgreen", "Lightgrey", "Lightpink", "Lightsalmon", "Lightseagreen", "Lightskyblue", "Lightslategrey", "Lightsteelblue", "Lightyellow", "Lime", "Limegreen", "Linen", "Magenta", "Maroon", "Mediumaquamarine", "Mediumblue", "Mediumorchid", "Mediumpurple", "Mediumseagreen", "Mediumslateblue", "Mediumspringgreen", "Mediumturquoise", "Mediumvioletred", "Midnightblue", "Mintcream", "Mistyrose", "Moccasin", "Navajowhite", "Navy", "Oldlace", "Olive", "Olivedrab", "Orange", "Orangered", "Orchid", "Palegoldenrod", "Palegreen", "Paleturquoise", "Palevioletred", "Papayawhip", "Peachpuff", "Peru", "Pink", "Plum", "Powderblue", "Purple", "Red", "Rosybrown", "Royalblue", "Saddlebrown", "Salmon", "Sandybrown", "Seagreen", "Seashell", "Sienna", "Silver", "Skyblue", "Slateblue", "Slategray", "Snow", "Springgreen", "Steelblue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "Whitesmoke", "Yellow", "Yellowgreen"}; /// <summary> /// Names of globals to put into expressions /// </summary> static public readonly string[] GlobalList = new string[] { "=Globals!PageNumber", "=Globals!TotalPages", "=Globals!ExecutionTime", "=Globals!ReportFolder", "=Globals!ReportName"}; /// <summary> /// Names of user info to put into expressions GJL AJM 12082008 /// </summary> static public readonly string[] UserList = new string[] { "=User!UserID", "=User!Language"}; static public readonly string[] OperatorList = new string[] { " & ", " + "," - "," * "," / "," mod ", " and ", " or ", " = ", " != ", " > ", " >= ", " < ", " <= " }; /// <summary> /// Names of functions with pseudo arguments /// </summary> static public readonly string[] FunctionList = new string[] { "Iif(boolean, trueExpr, falseExpr)", "Choose(number, choice1 [,choice2]...)", "Switch(boolean1, value1[, boolean2, value2]...[elseValue])", "Format(expr, formatExpr)"}; static public readonly string[] AggrFunctionList = new string[] {"Sum(number [, scope])", "Aggregate(number [, scope])", "Avg(number [, scope])", "Min(expr [, scope])", "Max(expr [, scope])", "First(expr [, scope])", "Last(expr [, scope])", "Next(expr [, scope])", "Previous(expr [, scope])", "Level([scope])", "Count(expr [, scope])", "Countrows(expr [, scope])", "Countdistinct(expr [, scope])", "RowNumber()", "Runningvalue(expr, sum [, scope])", "Runningvalue(expr, avg [, scope])", "Runningvalue(expr, count [, scope])", "Runningvalue(expr, max [, scope])", "Runningvalue(expr, min [, scope])", "Runningvalue(expr, stdev [, scope])", "Runningvalue(expr, stdevp [, scope])", "Runningvalue(expr, var [, scope])", "Runningvalue(expr, varp [, scope])", "Stdev(expr [, scope])", "Stdevp(expr [, scope])", "Var(expr [, scope])", "Varp(expr [, scope])"}; /// <summary> /// Zoom values /// </summary> static public readonly string[] ZoomList = new string[] { "Actual Size", "Fit Page", "Fit Width", "800%", "400%", "200%", "150%", "125%", "100%", "75%", "50%", "25%"}; /// <summary> /// List of format values /// </summary> static public readonly string[] FormatList = new string[] { "", "#,##0", "#,##0.00", "0", "0.00", "", "MM/dd/yyyy", "dddd, MMMM dd, yyyy", "dddd, MMMM dd, yyyy HH:mm", "dddd, MMMM dd, yyyy HH:mm:ss", "MM/dd/yyyy HH:mm", "MM/dd/yyyy HH:mm:ss", "MMMM dd", "Ddd, dd MMM yyyy HH\':\'mm\'\"ss \'GMT\'", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss GMT", "HH:mm", "HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "html"}; /// <summary> /// list of gradient types /// </summary> static public readonly string[] GradientList = new string[] { "None", "LeftRight", "TopBottom", "Center", "DiagonalLeft", "DiagonalRight", "HorizontalCenter", "VerticalCenter"}; } }
// 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.Net.Security; using System.Net.Test.Common; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Functional.Tests { public class HttpClientHandler_ServerCertificates_Test { [OuterLoop] // TODO: Issue #11345 [Fact] public async Task NoCallback_ValidCertificate_CallbackNotCalled() { var handler = new HttpClientHandler(); using (var client = new HttpClient(handler)) { Assert.Null(handler.ServerCertificateCustomValidationCallback); Assert.False(handler.CheckCertificateRevocationList); using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } Assert.Throws<InvalidOperationException>(() => handler.ServerCertificateCustomValidationCallback = null); Assert.Throws<InvalidOperationException>(() => handler.CheckCertificateRevocationList = false); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))] [ActiveIssue(12015, PlatformID.AnyUnix)] public void UseCallback_HaveNoCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_ProxyAuthenticationRequiredStatusCode() { int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync( out port, requireAuth: true, expectCreds: false); Uri proxyUrl = new Uri($"http://localhost:{port}"); var handler = new HttpClientHandler(); handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null); handler.ServerCertificateCustomValidationCallback = delegate { return true; }; using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.PostAsync( Configuration.Http.SecureRemoteEchoServer, new StringContent("This is a test")); Task.WaitAll(proxyTask, responseTask); Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))] public async Task UseCallback_NotSecureConnection_CallbackNotCalled() { var handler = new HttpClientHandler(); using (var client = new HttpClient(handler)) { bool callbackCalled = false; handler.ServerCertificateCustomValidationCallback = delegate { callbackCalled = true; return true; }; using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } Assert.False(callbackCalled); } } public static IEnumerable<object[]> UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls() { foreach (bool checkRevocation in new[] { true, false }) { yield return new object[] { Configuration.Http.SecureRemoteEchoServer, checkRevocation }; yield return new object[] { Configuration.Http.RedirectUriForDestinationUri( secure:true, statusCode:302, destinationUri:Configuration.Http.SecureRemoteEchoServer, hops:1), checkRevocation }; } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))] [MemberData(nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls))] public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation) { var handler = new HttpClientHandler(); using (var client = new HttpClient(handler)) { bool callbackCalled = false; handler.CheckCertificateRevocationList = checkRevocation; handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => { callbackCalled = true; Assert.NotNull(request); Assert.Equal(SslPolicyErrors.None, errors); Assert.True(chain.ChainElements.Count > 0); Assert.NotEmpty(cert.Subject); Assert.Equal(checkRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, chain.ChainPolicy.RevocationMode); return true; }; using (HttpResponseMessage response = await client.GetAsync(url)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } Assert.True(callbackCalled); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))] public async Task UseCallback_CallbackReturnsFailure_ThrowsException() { var handler = new HttpClientHandler(); using (var client = new HttpClient(handler)) { handler.ServerCertificateCustomValidationCallback = delegate { return false; }; await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))] public async Task UseCallback_CallbackThrowsException_ExceptionPropagates() { var handler = new HttpClientHandler(); using (var client = new HttpClient(handler)) { var e = new DivideByZeroException(); handler.ServerCertificateCustomValidationCallback = delegate { throw e; }; Assert.Same(e, await Assert.ThrowsAsync<DivideByZeroException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer))); } } public readonly static object[][] CertificateValidationServers = { new object[] { Configuration.Http.ExpiredCertRemoteServer }, new object[] { Configuration.Http.SelfSignedCertRemoteServer }, new object[] { Configuration.Http.WrongHostNameCertRemoteServer }, }; [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(CertificateValidationServers))] public async Task NoCallback_BadCertificate_ThrowsException(string url) { using (var client = new HttpClient()) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)); } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds() { using (var client = new HttpClient()) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RevokedCertRemoteServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))] public async Task NoCallback_RevokedCertificate_RevocationChecking_Fails() { var handler = new HttpClientHandler() { CheckCertificateRevocationList = true }; using (var client = new HttpClient(handler)) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.RevokedCertRemoteServer)); } } public readonly static object[][] CertificateValidationServersAndExpectedPolicies = { new object[] { Configuration.Http.ExpiredCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors }, new object[] { Configuration.Http.SelfSignedCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors }, new object[] { Configuration.Http.WrongHostNameCertRemoteServer , SslPolicyErrors.RemoteCertificateNameMismatch}, }; [OuterLoop] // TODO: Issue #11345 [ActiveIssue(7812, PlatformID.Windows)] [ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))] [MemberData(nameof(CertificateValidationServersAndExpectedPolicies))] public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors) { var handler = new HttpClientHandler(); using (var client = new HttpClient(handler)) { bool callbackCalled = false; handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => { callbackCalled = true; Assert.NotNull(request); Assert.NotNull(cert); Assert.NotNull(chain); Assert.Equal(expectedErrors, errors); return true; }; using (HttpResponseMessage response = await client.GetAsync(url)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } Assert.True(callbackCalled); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))] public async Task SSLBackendNotSupported_Callback_ThrowsPlatformNotSupportedException() { using (var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } })) { await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))] public async Task SSLBackendNotSupported_Revocation_ThrowsPlatformNotSupportedException() { using (var client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true })) { await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)); } } [OuterLoop] // TODO: Issue #11345 [PlatformSpecific(PlatformID.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix [Fact] public async Task PostAsync_Post_ChannelBinding_ConfiguredCorrectly() { var content = new ChannelBindingAwareContent("Test contest"); using (var client = new HttpClient()) using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, content)) { // Validate status. Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Validate the ChannelBinding object exists. ChannelBinding channelBinding = content.ChannelBinding; Assert.NotNull(channelBinding); // Validate the ChannelBinding's validity. if (BackendSupportsCustomCertificateHandling) { Assert.False(channelBinding.IsInvalid, "Expected valid binding"); Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle()); // Validate the ChannelBinding's description. string channelBindingDescription = channelBinding.ToString(); Assert.NotNull(channelBindingDescription); Assert.NotEmpty(channelBindingDescription); Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}"); for (int i = 0; i < channelBindingDescription.Length; i++) { char c = channelBindingDescription[i]; if (i % 3 == 2) { Assert.Equal(' ', c); } else { Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}"); } } } else { // Backend doesn't support getting the details to create the CBT. Assert.True(channelBinding.IsInvalid, "Expected invalid binding"); Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle()); Assert.Null(channelBinding.ToString()); } } } private static bool BackendSupportsCustomCertificateHandling => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (CurlSslVersionDescription()?.StartsWith("OpenSSL") ?? false); private static bool BackendDoesNotSupportCustomCertificateHandling => !BackendSupportsCustomCertificateHandling; [DllImport("System.Net.Http.Native", EntryPoint = "HttpNative_GetSslVersionDescription")] private static extern string CurlSslVersionDescription(); } }
using Aardvark.Base.Sorting; using System; using System.Collections.Generic; using System.Linq; namespace Aardvark.Base { /// <summary> /// This interface enforces a common API for random number generators. /// </summary> public interface IRandomUniform { #region Info and Seeding /// <summary> /// Returns the number of random bits that the generator /// delivers. This many bits are actually random in the /// doubles returned by <see cref="UniformDouble()"/>. /// </summary> int RandomBits { get; } /// <summary> /// Returns true if the doubles generated by this random /// generator contain 52 random mantissa bits. /// </summary> bool GeneratesFullDoubles { get; } /// <summary> /// Reinitializes the random generator with the specified seed. /// </summary> void ReSeed(int seed); #endregion #region Random Integers /// <summary> /// Returns a uniformly distributed integer in the interval /// [0, 2^31-1]. /// </summary> int UniformInt(); /// <summary> /// Returns a uniformly distributed integer in the interval /// [0, 2^32-1]. /// </summary> uint UniformUInt(); /// <summary> /// Returns a uniformly distributed integer in the interval /// [0, 2^63-1]. /// </summary> long UniformLong(); /// <summary> /// Returns a uniformly distributed integer in the interval /// [0, 2^64-1]. /// </summary> ulong UniformULong(); #endregion #region Random Floating Point Values /// <summary> /// Returns a uniformly distributed float in the half-open interval /// [0.0f, 1.0f). /// </summary> float UniformFloat(); /// <summary> /// Returns a uniformly distributed float in the closed interval /// [0.0f, 1.0f]. /// </summary> float UniformFloatClosed(); /// <summary> /// Returns a uniformly distributed float in the open interval /// (0.0f, 1.0f). /// </summary> float UniformFloatOpen(); /// <summary> /// Returns a uniformly distributed double in the half-open interval /// [0.0, 1.0). Note, that only RandomBits bits are guaranteed to be /// random. /// </summary> double UniformDouble(); /// <summary> /// Returns a uniformly distributed double in the closed interval /// [0.0, 1.0]. Note, that only RandomBits bits are guaranteed to be /// random. /// </summary> double UniformDoubleClosed(); /// <summary> /// Returns a uniformly distributed double in the open interval /// (0.0, 1.0). Note, that only RandomBits bits are guaranteed to be /// random. /// </summary> double UniformDoubleOpen(); #endregion } public static class IRandomUniformExtensions { #region Random Bits /// <summary> /// Supply random bits one at a time. The currently unused bits are /// maintained in the supplied reference parameter. Before the first /// call randomBits must be 0. /// </summary> public static bool RandomBit( this IRandomUniform rnd, ref int randomBits) { if (randomBits <= 1) { randomBits = rnd.UniformInt(); bool bit = (randomBits & 1) != 0; randomBits = 0x40000000 | (randomBits >> 1); return bit; } else { bool bit = (randomBits & 1) != 0; randomBits >>= 1; return bit; } } #endregion #region Random Integers /// <summary> /// Returns a uniformly distributed int in the interval [0, count-1]. /// In order to avoid excessive aliasing, two random numbers are used /// when count is greater or equal 2^24 and the random generator /// delivers 32 random bits or less. The method thus works fairly /// decently for all integers. /// </summary> public static int UniformInt(this IRandomUniform rnd, int size) { if (rnd.GeneratesFullDoubles || size < 16777216) return (int)(rnd.UniformDouble() * size); else return (int)(rnd.UniformDoubleFull() * size); } /// <summary> /// Returns a uniformly distributed long in the interval [0, size-1]. /// NOTE: If count has more than about 48 bits, aliasing leads to /// noticeable (greater 5%) shifts in the probabilities (i.e. one /// long has a probability of x and the other a probability of /// x * (2^(52-b)-1)/(2^(52-b)), where b is log(size)/log(2)). /// </summary> public static long UniformLong(this IRandomUniform rnd, long size) { if (rnd.GeneratesFullDoubles || size < 16777216) return (long)(rnd.UniformDouble() * size); else return (long)(rnd.UniformDoubleFull() * size); } /// <summary> /// Returns a uniform int which is guaranteed not to be zero. /// </summary> public static int UniformIntNonZero(this IRandomUniform rnd) { int r; do { r = rnd.UniformInt(); } while (r == 0); return r; } /// <summary> /// Returns a uniform long which is guaranteed not to be zero. /// </summary> public static long UniformLongNonZero(this IRandomUniform rnd) { long r; do { r = rnd.UniformLong(); } while (r == 0); return r; } #endregion #region Random Floating Point Values /// <summary> /// Returns a uniformly distributed double in the half-open interval /// [0.0, 1.0). Note, that two random values are used to make all 53 /// bits random. If you use this repeatedly, consider using a 64-bit /// random generator, which can provide such doubles directly using /// UniformDouble(). /// </summary> public static double UniformDoubleFull(this IRandomUniform rnd) { if (rnd.GeneratesFullDoubles) return rnd.UniformDouble(); long r = ((~0xfL & (long)rnd.UniformInt()) << 22) | ((long)rnd.UniformInt() >> 5); return r * (1.0 / 9007199254740992.0); } /// <summary> /// Returns a uniformly distributed double in the closed interval /// [0.0, 1.0]. Note, that two random values are used to make all 53 /// bits random. /// </summary> public static double UniformDoubleFullClosed(this IRandomUniform rnd) { if (rnd.GeneratesFullDoubles) return rnd.UniformDoubleClosed(); long r = ((~0xfL & (long)rnd.UniformInt()) << 22) | ((long)rnd.UniformInt() >> 5); return r * (1.0 / 9007199254740991.0); } /// <summary> /// Returns a uniformly distributed double in the open interval /// (0.0, 1.0). Note, that two random values are used to make all 53 /// bits random. /// </summary> public static double UniformDoubleFullOpen(this IRandomUniform rnd) { if (rnd.GeneratesFullDoubles) return rnd.UniformDoubleOpen(); long r; do { r = ((~0xfL & (long)rnd.UniformInt()) << 22) | ((long)rnd.UniformInt() >> 5); } while (r == 0); return r * (1.0 / 9007199254740992.0); } #endregion #region Creating Randomly Filled Arrays /// <summary> /// Create a random array of floats in the half-open interval /// [0.0, 1.0) of the specified length. /// </summary> public static float[] CreateUniformFloatArray( this IRandomUniform rnd, long length) { var array = new float[length]; rnd.FillUniform(array); return array; } /// <summary> /// Create a random array of doubles in the half-open interval /// [0.0, 1.0) of the specified length. /// </summary> public static double[] CreateUniformDoubleArray( this IRandomUniform rnd, long length) { var array = new double[length]; rnd.FillUniform(array); return array; } /// <summary> /// Create a random array of full doubles in the half-open interval /// [0.0, 1.0) of the specified length. /// </summary> public static double[] CreateUniformDoubleFullArray( this IRandomUniform rnd, long length) { var array = new double[length]; rnd.FillUniformFull(array); return array; } /// <summary> /// Fills the specified array with random ints in the interval /// [0, 2^31-1]. /// </summary> public static void FillUniform(this IRandomUniform rnd, int[] array) { long count = array.LongLength; for (long i = 0; i < count; i++) array[i] = rnd.UniformInt(); } /// <summary> /// Fills the specified array with random floats in the half-open /// interval [0.0f, 1.0f). /// </summary> public static void FillUniform(this IRandomUniform rnd, float[] array) { long count = array.LongLength; for (long i = 0; i < count; i++) array[i] = rnd.UniformFloat(); } /// <summary> /// Fills the specified array with random doubles in the half-open /// interval [0.0, 1.0). /// </summary> public static void FillUniform( this IRandomUniform rnd, double[] array) { long count = array.LongLength; for (long i = 0; i < count; i++) array[i] = rnd.UniformDouble(); } /// <summary> /// Fills the specified array with fully random doubles (53 random /// bits) in the half-open interval [0.0, 1.0). /// </summary> public static void FillUniformFull( this IRandomUniform rnd, double[] array) { long count = array.LongLength; if (rnd.GeneratesFullDoubles) { for (long i = 0; i < count; i++) array[i] = rnd.UniformDoubleFull(); } else { for (long i = 0; i < count; i++) array[i] = rnd.UniformDouble(); } } /// <summary> /// Creates an array that contains a random permutation of the /// ints in the interval [0, count-1]. /// </summary> public static int[] CreatePermutationArray( this IRandomUniform rnd, int count) { var p = new int[count].SetByIndex(i => i); rnd.Randomize(p); return p; } /// <summary> /// Creates an array that contains a random permutation of the /// numbers in the interval [0, count-1]. /// </summary> public static long[] CreatePermutationArrayLong( this IRandomUniform rnd, long count) { var p = new long[count].SetByIndexLong(i => i); rnd.Randomize(p); return p; } #endregion #region Creationg a Random Subset (while maintaing order) /// <summary> /// Returns a random subset of an array with a supplied number of /// elements (subsetCount). The elements in the subset are in the /// same order as in the original array. O(count). /// NOTE: this method needs to generate one random number for each /// element of the original array. If subsetCount is significantly /// smaller than count, it is more efficient to use /// <see cref="CreateSmallRandomSubsetIndexArray"/> or /// <see cref="CreateSmallRandomSubsetIndexArrayLong"/> or /// <see cref="CreateSmallRandomOrderedSubsetIndexArray"/> or /// <see cref="CreateSmallRandomOrderedSubsetIndexArrayLong"/>. /// </summary> public static T[] CreateRandomSubsetOfSize<T>( this T[] array, long subsetCount, IRandomUniform rnd = null) { if (rnd == null) rnd = new RandomSystem(); long count = array.LongLength; if (!(subsetCount >= 0 && subsetCount <= count)) throw new ArgumentOutOfRangeException(nameof(subsetCount)); var subset = new T[subsetCount]; long si = 0; for (int ai = 0; ai < count && si < subsetCount; ai++) { var p = (double)(subsetCount - si) / (double)(count - ai); if (rnd.UniformDouble() <= p) subset[si++] = array[ai]; } return subset; } /// <summary> /// Returns a random subset of the enumeration with a supplied number of /// elements (subsetCount). The elements in the subset are in the /// same order as in the input. O(count). /// NOTE: The number of elements of the Enumerable need to be calculated, in case of true enumerations /// the implementation of .Count() results in a second evaluation of the enumerable. /// </summary> public static T[] CreateRandomSubsetOfSize<T>( this IEnumerable<T> input, long subsetCount, IRandomUniform rnd = null) { if (rnd == null) rnd = new RandomSystem(); long count = input.Count(); if (!(subsetCount >= 0 && subsetCount <= count)) throw new ArgumentOutOfRangeException(nameof(subsetCount)); var subset = new T[subsetCount]; long si = 0, ai = 0; foreach (var a in input) { if (ai < count && si < subsetCount) { var p = (double)(subsetCount - si) / (double)(count - ai++); if (rnd.UniformDouble() <= p) subset[si++] = a; } else break; } return subset; } /// <summary> /// Creates an unordered array of subsetCount long indices that /// constitute a subset of all longs in the range [0, count-1]. /// O(subsetCount) for subsetCount &lt;&lt; count. /// NOTE: It is assumed that subsetCount is significantly smaller /// than count. If this is not the case, use /// CreateRandomSubsetOfSize instead. /// WARNING: As subsetCount approaches count execution time /// increases significantly. /// </summary> public static long[] CreateSmallRandomSubsetIndexArrayLong( this IRandomUniform rnd, long subsetCount, long count) { if (!(subsetCount >= 0 && subsetCount <= count)) throw new ArgumentOutOfRangeException(nameof(subsetCount)); var subsetIndices = new LongSet(subsetCount); for (int i = 0; i < subsetCount; i++) { long index; do { index = rnd.UniformLong(count); } while (!subsetIndices.TryAdd(index)); } return subsetIndices.ToArray(); } /// <summary> /// Creates an ordered array of subsetCount long indices that /// constitute a subset of all longs in the range [0, count-1]. /// O(subsetCount * log(subsetCount)) for subsetCount &lt;&lt; count. /// NOTE: It is assumed that subsetCount is significantly smaller /// than count. If this is not the case, use /// CreateRandomSubsetOfSize instead. /// WARNING: As subsetCount approaches count execution time /// increases significantly. /// </summary> public static long[] CreateSmallRandomOrderedSubsetIndexArrayLong( this IRandomUniform rnd, long subsetCount, long count) { var subsetIndexArray = rnd.CreateSmallRandomSubsetIndexArrayLong(subsetCount, count); subsetIndexArray.QuickSortAscending(); return subsetIndexArray; } /// <summary> /// Creates an unordered array of subsetCount int indices that /// constitute a subset of all ints in the range [0, count-1]. /// O(subsetCount) for subsetCount &lt;&lt; count. /// NOTE: It is assumed that subsetCount is significantly smaller /// than count. If this is not the case, use /// CreateRandomSubsetOfSize instead. /// WARNING: As subsetCount approaches count execution time /// increases significantly. /// </summary> public static int[] CreateSmallRandomSubsetIndexArray( this IRandomUniform rnd, int subsetCount, int count) { if (!(subsetCount >= 0 && subsetCount <= count)) throw new ArgumentOutOfRangeException(nameof(subsetCount)); var subsetIndices = new IntSet(subsetCount); for (int i = 0; i < subsetCount; i++) { int index; do { index = rnd.UniformInt(count); } while (!subsetIndices.TryAdd(index)); } return subsetIndices.ToArray(); } /// <summary> /// Creates an ordered array of subsetCount int indices that /// constitute a subset of all ints in the range [0, count-1]. /// O(subsetCount * log(subsetCount)) for subsetCount &lt;&lt; count. /// NOTE: It is assumed that subsetCount is significantly smaller /// than count. If this is not the case, use /// CreateRandomSubsetOfSize instead. /// WARNING: As subsetCount approaches count execution time /// increases significantly. /// </summary> public static int[] CreateSmallRandomOrderedSubsetIndexArray( this IRandomUniform rnd, int subsetCount, int count) { var subsetIndexArray = rnd.CreateSmallRandomSubsetIndexArray(subsetCount, count); subsetIndexArray.QuickSortAscending(); return subsetIndexArray; } #endregion #region Randomizing Existing Arrays /// <summary> /// Randomly permute the first count elements of the /// supplied array. This does work with counts of up /// to about 2^50. /// </summary> public static void Randomize<T>( this IRandomUniform rnd, T[] array, long count) { if (count <= (long)int.MaxValue) { int intCount = (int)count; for (int i = 0; i < intCount; i++) array.Swap(i, rnd.UniformInt(intCount)); } else { for (long i = 0; i < count; i++) array.Swap(i, rnd.UniformLong(count)); } } /// <summary> /// Randomly permute the elements of the supplied array. This does /// work with arrays up to a length of about 2^50. /// </summary> public static void Randomize<T>( this IRandomUniform rnd, T[] array) { rnd.Randomize(array, array.LongLength); } /// <summary> /// Randomly permute the elements of the supplied list. /// </summary> public static void Randomize<T>( this IRandomUniform rnd, List<T> list) { int count = list.Count; for (int i = 0; i < count; i++) list.Swap(i, rnd.UniformInt(count)); } /// <summary> /// Randomly permute the specified number of elements in the supplied /// array starting at the specified index. /// </summary> public static void Randomize<T>( this IRandomUniform rnd, T[] array, int start, int count) { for (int i = start, e = start + count; i < e; i++) array.Swap(i, start + rnd.UniformInt(count)); } /// <summary> /// Randomly permute the specified number of elements in the supplied /// array starting at the specified index. /// </summary> public static void Randomize<T>( this IRandomUniform rnd, T[] array, long start, long count) { for (long i = start, e = start + count; i < e; i++) array.Swap(i, start + rnd.UniformLong(count)); } /// <summary> /// Randomly permute the specified number of elements in the supplied /// list starting at the specified index. /// </summary> public static void Randomize<T>( this IRandomUniform rnd, List<T> list, int start, int count) { for (int i = start; i < start + count; i++) list.Swap(i, start + rnd.UniformInt(count)); } #endregion #region Random Distributions /// <summary> /// Generates normal distributed random variable with given mean and standard deviation. /// Uses the Box-Muller Transformation to transform two uniform distributed random variables to one normal distributed value. /// NOTE: If multiple normal distributed random values are required, consider using <see cref="RandomGaussian"/>. /// </summary> public static double Gaussian(this IRandomUniform rnd, double mean = 0.0, double stdDev = 1.0) { // Box-Muller Transformation var u1 = 1.0 - rnd.UniformDouble(); // uniform (0,1] -> log requires > 0 var u2 = rnd.UniformDouble(); // uniform [0,1) var randStdNormal = Fun.Sqrt(-2.0 * Fun.Log(u1)) * Fun.Sin(Constant.PiTimesTwo * u2); return mean + stdDev * randStdNormal; } #endregion } public static class IRandomEnumerableExtensions { #region Random Order /// <summary> /// Enumerates elements in random order. /// </summary> public static IEnumerable<T> RandomOrder<T>(this IEnumerable<T> self, IRandomUniform rnd = null) { var tmp = self.ToArray(); if (rnd == null) rnd = new RandomSystem(); var perm = rnd.CreatePermutationArray(tmp.Length); return perm.Select(index => tmp[index]); } #endregion } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class PostFilteringTargetWrapperTests : NLogTestBase { [Fact] public void PostFilteringTargetWrapperUsingDefaultFilterTest() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), // when there is an error, emit everything new FilteringRule { Exists = "level >= LogLevel.Error", Filter = "true", }, }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new [] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), }; wrapper.WriteAsyncLogEvents(events); // make sure all Info events went through Assert.Equal(3, target.Events.Count); Assert.Same(events[1].LogEvent, target.Events[0]); Assert.Same(events[2].LogEvent, target.Events[1]); Assert.Same(events[5].LogEvent, target.Events[2]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperUsingDefaultNonFilterTest() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), // when there is an error, emit everything new FilteringRule("level >= LogLevel.Error", "true"), }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Warn, "Logger1", "Hello").WithContinuation(exceptions.Add), }; string result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace); Assert.True(result.IndexOf("Running on 7 events") != -1); Assert.True(result.IndexOf("Rule matched: (level >= Warn)") != -1); Assert.True(result.IndexOf("Filter to apply: (level >= Debug)") != -1); Assert.True(result.IndexOf("After filtering: 6 events.") != -1); Assert.True(result.IndexOf("Sending to MyTarget") != -1); // make sure all Debug,Info,Warn events went through Assert.Equal(6, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[5].LogEvent, target.Events[4]); Assert.Same(events[6].LogEvent, target.Events[5]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperUsingDefaultNonFilterTest2() { // in this case both rules would match, but first one is picked var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // when there is an error, emit everything new FilteringRule("level >= LogLevel.Error", "true"), // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new [] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add), }; var result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace); Assert.True(result.IndexOf("Running on 7 events") != -1); Assert.True(result.IndexOf("Rule matched: (level >= Error)") != -1); Assert.True(result.IndexOf("Filter to apply: True") != -1); Assert.True(result.IndexOf("After filtering: 7 events.") != -1); Assert.True(result.IndexOf("Sending to MyTarget") != -1); // make sure all events went through Assert.Equal(7, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[4].LogEvent, target.Events[4]); Assert.Same(events[5].LogEvent, target.Events[5]); Assert.Same(events[6].LogEvent, target.Events[6]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperOnlyDefaultFilter() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, DefaultFilter = "level >= LogLevel.Info", // by default log info and above }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); wrapper.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add)); Assert.Single(target.Events); wrapper.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add)); Assert.Single(target.Events); } [Fact] public void PostFilteringTargetWrapperNoFiltersDefined() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add), }; wrapper.WriteAsyncLogEvents(events); // make sure all events went through Assert.Equal(7, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[4].LogEvent, target.Events[4]); Assert.Same(events[5].LogEvent, target.Events[5]); Assert.Same(events[6].LogEvent, target.Events[6]); Assert.Equal(events.Length, exceptions.Count); } public class MyTarget : Target { public MyTarget() { Events = new List<LogEventInfo>(); } public MyTarget(string name) : this() { Name = name; } public List<LogEventInfo> Events { get; set; } protected override void Write(LogEventInfo logEvent) { Events.Add(logEvent); } } } }
using Microsoft.Extensions.Logging; using NBitcoin; using Stratis.Bitcoin.Configuration.Logging; using Stratis.Patricia; using Stratis.SmartContracts.CLR.Compilation; using Stratis.SmartContracts.CLR.Loader; using Stratis.SmartContracts.CLR.ResultProcessors; using Stratis.SmartContracts.CLR.Serialization; using Stratis.SmartContracts.CLR.Validation; using Stratis.SmartContracts.Core; using Stratis.SmartContracts.Core.State; using Stratis.SmartContracts.Networks; using Stratis.SmartContracts.RuntimeObserver; using Xunit; namespace Stratis.SmartContracts.CLR.Tests { public sealed class ContractExecutorTests { private const ulong BlockHeight = 0; private static readonly uint160 CoinbaseAddress = 0; private static readonly uint160 ToAddress = 1; private static readonly uint160 SenderAddress = 2; private static readonly Money MempoolFee = new Money(1_000_000); private readonly IKeyEncodingStrategy keyEncodingStrategy; private readonly ILoggerFactory loggerFactory; private readonly Network network; private readonly IContractRefundProcessor refundProcessor; private readonly IStateRepositoryRoot state; private readonly IContractTransferProcessor transferProcessor; private readonly SmartContractValidator validator; private IInternalExecutorFactory internalTxExecutorFactory; private IVirtualMachine vm; private readonly ICallDataSerializer callDataSerializer; private readonly StateFactory stateFactory; private readonly IAddressGenerator addressGenerator; private readonly ILoader assemblyLoader; private readonly IContractModuleDefinitionReader moduleDefinitionReader; private readonly IContractPrimitiveSerializer contractPrimitiveSerializer; private readonly IStateProcessor stateProcessor; private readonly ISmartContractStateFactory smartContractStateFactory; private readonly ISerializer serializer; public ContractExecutorTests() { this.keyEncodingStrategy = BasicKeyEncodingStrategy.Default; this.loggerFactory = new ExtendedLoggerFactory(); this.loggerFactory.AddConsoleWithFilters(); this.network = new SmartContractsRegTest(); this.refundProcessor = new ContractRefundProcessor(this.loggerFactory); this.state = new StateRepositoryRoot(new NoDeleteSource<byte[], byte[]>(new MemoryDictionarySource())); this.transferProcessor = new ContractTransferProcessor(this.loggerFactory, this.network); this.validator = new SmartContractValidator(); this.addressGenerator = new AddressGenerator(); this.assemblyLoader = new ContractAssemblyLoader(); this.moduleDefinitionReader = new ContractModuleDefinitionReader(); this.contractPrimitiveSerializer = new ContractPrimitiveSerializer(this.network); this.serializer = new Serializer(this.contractPrimitiveSerializer); this.vm = new ReflectionVirtualMachine(this.validator, this.loggerFactory, this.assemblyLoader, this.moduleDefinitionReader); this.stateProcessor = new StateProcessor(this.vm, this.addressGenerator); this.internalTxExecutorFactory = new InternalExecutorFactory(this.loggerFactory, this.stateProcessor); this.smartContractStateFactory = new SmartContractStateFactory(this.contractPrimitiveSerializer, this.internalTxExecutorFactory, this.serializer); this.callDataSerializer = new CallDataSerializer(this.contractPrimitiveSerializer); this.stateFactory = new StateFactory(this.smartContractStateFactory); } [Fact] public void SmartContractExecutor_CallContract_Fails_ReturnFundsToSender() { //Get the contract execution code------------------------ ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/ThrowExceptionContract.cs"); Assert.True(compilationResult.Success); byte[] contractExecutionCode = compilationResult.Compilation; //------------------------------------------------------- //Call smart contract and add to transaction------------- var contractTxData = new ContractTxData(1, 1, (Gas)500_000, ToAddress, "ThrowException"); var transactionCall = new Transaction(); TxOut callTxOut = transactionCall.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); callTxOut.Value = 100; //------------------------------------------------------- //Deserialize the contract from the transaction---------- //and get the module definition //------------------------------------------------------- this.state.SetCode(new uint160(1), contractExecutionCode); this.state.SetContractType(new uint160(1), "ThrowExceptionContract"); IContractTransactionContext transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, SenderAddress, transactionCall); var executor = new ContractExecutor( this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); IContractExecutionResult result = executor.Execute(transactionContext); Assert.True(result.Revert); Assert.NotNull(result.InternalTransaction); Assert.Single(result.InternalTransaction.Inputs); Assert.Single(result.InternalTransaction.Outputs); var actualSender = new uint160(result.InternalTransaction.Outputs[0].ScriptPubKey.GetDestination(this.network).ToBytes()); Assert.Equal(SenderAddress, actualSender); Assert.Equal(100, result.InternalTransaction.Outputs[0].Value); } [Fact] public void SmartContractExecutor_CallContract_DoesNotExist_Refund() { var contractTxData = new ContractTxData(1, 1, (Gas) 10000, ToAddress, "TestMethod"); var transaction = new Transaction(); TxOut txOut = transaction.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); txOut.Value = 100; IContractTransactionContext transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, new uint160(2), transaction); var executor = new ContractExecutor( this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); IContractExecutionResult result = executor.Execute(transactionContext); Assert.True(result.Revert); } [Fact] public void SME_CreateContract_ConstructorFails_Refund() { ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/ContractConstructorInvalid.cs"); Assert.True(compilationResult.Success); byte[] contractCode = compilationResult.Compilation; var contractTxData = new ContractTxData(0, (Gas) 1, (Gas)500_000, contractCode); var tx = new Transaction(); tx.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); IContractTransactionContext transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, new uint160(2), tx); var executor = new ContractExecutor( this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); IContractExecutionResult result = executor.Execute(transactionContext); Assert.NotNull(result.ErrorMessage); // Number here shouldn't be hardcoded - note this is really only to let us know of consensus failure Assert.Equal(GasPriceList.CreateCost + 18, result.GasConsumed); } [Fact] public void SME_CreateContract_MethodParameters_InvalidParameterCount() { ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/ContractInvalidParameterCount.cs"); Assert.True(compilationResult.Success); byte[] contractCode = compilationResult.Compilation; object[] methodParameters = { 5 }; var contractTxData = new ContractTxData(0, (Gas)1, (Gas)500_000, contractCode, methodParameters); var tx = new Transaction(); tx.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); IContractTransactionContext transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, new uint160(2), tx); var executor = new ContractExecutor( this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); IContractExecutionResult result = executor.Execute(transactionContext); Assert.NotNull(result.ErrorMessage); Assert.Equal(GasPriceList.CreateCost, result.GasConsumed); } [Fact] public void SME_CreateContract_MethodParameters_ParameterTypeMismatch() { ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/ContractMethodParameterTypeMismatch.cs"); Assert.True(compilationResult.Success); byte[] contractCode = compilationResult.Compilation; object[] methodParameters = { true }; var contractTxData = new ContractTxData(0, (Gas)1, (Gas)500_000, contractCode, methodParameters); var tx = new Transaction(); tx.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); IContractTransactionContext transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, new uint160(2), tx); var executor = new ContractExecutor( this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); IContractExecutionResult result = executor.Execute(transactionContext); Assert.NotNull(result.ErrorMessage); Assert.Equal(GasPriceList.CreateCost, result.GasConsumed); } [Fact] public void Execute_InterContractCall_Internal_InfiniteLoop_Fails() { // Create contract 1 //Get the contract execution code------------------------ ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/InfiniteLoop.cs"); Assert.True(compilationResult.Success); byte[] contractExecutionCode = compilationResult.Compilation; //------------------------------------------------------- // Add contract creation code to transaction------------- var contractTxData = new ContractTxData(1, (Gas)1, (Gas)500_000, contractExecutionCode); var transaction = new Transaction(); TxOut txOut = transaction.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); txOut.Value = 100; //------------------------------------------------------- //Deserialize the contract from the transaction---------- //and get the module definition IContractTransactionContext transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, SenderAddress, transaction); var executor = new ContractExecutor( this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); IContractExecutionResult result = executor.Execute(transactionContext); uint160 address1 = result.NewContractAddress; //------------------------------------------------------- // Create contract 2 //Get the contract execution code------------------------ compilationResult = ContractCompiler.CompileFile("SmartContracts/CallInfiniteLoopContract.cs"); Assert.True(compilationResult.Success); contractExecutionCode = compilationResult.Compilation; //------------------------------------------------------- //Call smart contract and add to transaction------------- contractTxData = new ContractTxData(1, (Gas)1, (Gas)500_000, contractExecutionCode); transaction = new Transaction(); txOut = transaction.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); txOut.Value = 100; //------------------------------------------------------- //Deserialize the contract from the transaction---------- //and get the module definition //------------------------------------------------------- transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, SenderAddress, transaction); result = executor.Execute(transactionContext); uint160 address2 = result.NewContractAddress; // Invoke infinite loop var gasLimit = (Gas)500_000; object[] parameters = { address1.ToAddress() }; contractTxData = new ContractTxData(1, (Gas)1, gasLimit, address2, "CallInfiniteLoop", parameters); transaction = new Transaction(); txOut = transaction.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); txOut.Value = 100; transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, SenderAddress, transaction); var callExecutor = new ContractExecutor( this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); // Because our contract contains an infinite loop, we want to kill our test after // some amount of time without achieving a result. 3 seconds is an arbitrarily high enough timeout // for the method body to have finished execution while minimising the amount of time we spend // running tests // If you're running with the debugger on this will obviously be a source of failures result = TimeoutHelper.RunCodeWithTimeout(3, () => callExecutor.Execute(transactionContext)); // Actual call was successful, but internal call failed due to gas - returned false. Assert.False(result.Revert); Assert.False((bool) result.Return); } [Fact] public void Execute_NestedLoop_ExecutionSucceeds() { AssertSuccessfulContractMethodExecution(nameof(NestedLoop), nameof(NestedLoop.GetNumbers), new object[] { (int)6 }, "1; 1,2; 1,2,3; 1,2,3,4; 1,2,3,4,5; 1,2,3,4,5,6; "); } [Fact] public void Execute_MultipleIfElseBlocks_ExecutionSucceeds() { AssertSuccessfulContractMethodExecution(nameof(MultipleIfElseBlocks), nameof(MultipleIfElseBlocks.PersistNormalizeValue), new object[] { "z" }); } private void AssertSuccessfulContractMethodExecution(string contractName, string methodName, object[] methodParameters = null, string expectedReturn = null) { var transactionValue = (Money)100; var executor = new ContractExecutor( this.callDataSerializer, this.state, this.refundProcessor, this.transferProcessor, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer); ContractCompilationResult compilationResult = ContractCompiler.CompileFile($"SmartContracts/{contractName}.cs"); Assert.True(compilationResult.Success); byte[] contractExecutionCode = compilationResult.Compilation; var contractTxData = new ContractTxData(1, (Gas)1, (Gas)500_000, contractExecutionCode); var transaction = new Transaction(); TxOut txOut = transaction.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); txOut.Value = transactionValue; var transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, SenderAddress, transaction); IContractExecutionResult result = executor.Execute(transactionContext); uint160 contractAddress = result.NewContractAddress; contractTxData = new ContractTxData(1, (Gas)1, (Gas)500_000, contractAddress, methodName, methodParameters); transaction = new Transaction(); txOut = transaction.AddOutput(0, new Script(this.callDataSerializer.Serialize(contractTxData))); txOut.Value = transactionValue; transactionContext = new ContractTransactionContext(BlockHeight, CoinbaseAddress, MempoolFee, SenderAddress, transaction); result = executor.Execute(transactionContext); Assert.NotNull(result); Assert.Null(result.ErrorMessage); if (expectedReturn != null) { Assert.NotNull(result.Return); Assert.Equal(expectedReturn, (string)result.Return); } } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace BusinessApps.RemoteCalendarAccessWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// 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. extern alias SRE; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Path = SRE::System.IO.Path; using BitConverter = SRE::System.BitConverter; namespace System.Diagnostics { public class StackTraceSymbols : IDisposable { private readonly Dictionary<IntPtr, Tuple<MetadataReaderProvider, MetadataReader>> _readerCache; /// <summary> /// Create an instance of this class. /// </summary> public StackTraceSymbols() { _readerCache = new Dictionary<IntPtr, Tuple<MetadataReaderProvider, MetadataReader>>(); } /// <summary> /// Clean up any cached providers. /// </summary> void IDisposable.Dispose() { foreach (Tuple<MetadataReaderProvider, MetadataReader> tuple in _readerCache.Values) { tuple.Item1.Dispose(); } _readerCache.Clear(); } /// <summary> /// Returns the source file and line number information for the method. /// </summary> /// <param name="assemblyPath">file path of the assembly or null</param> /// <param name="loadedPeAddress">loaded PE image address or zero</param> /// <param name="loadedPeSize">loaded PE image size</param> /// <param name="inMemoryPdbAddress">in memory PDB address or zero</param> /// <param name="inMemoryPdbSize">in memory PDB size</param> /// <param name="methodToken">method token</param> /// <param name="ilOffset">il offset of the stack frame</param> /// <param name="sourceFile">source file return</param> /// <param name="sourceLine">line number return</param> /// <param name="sourceColumn">column return</param> public void GetSourceLineInfo(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize, IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset, out string sourceFile, out int sourceLine, out int sourceColumn) { sourceFile = null; sourceLine = 0; sourceColumn = 0; MetadataReader reader = GetReader(assemblyPath, loadedPeAddress, loadedPeSize, inMemoryPdbAddress, inMemoryPdbSize); if (reader != null) { Handle handle = MetadataTokens.Handle(methodToken); if (handle.Kind == HandleKind.MethodDefinition) { MethodDebugInformationHandle methodDebugHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle(); MethodDebugInformation methodInfo = reader.GetMethodDebugInformation(methodDebugHandle); if (!methodInfo.SequencePointsBlob.IsNil) { SequencePointCollection sequencePoints = methodInfo.GetSequencePoints(); SequencePoint? bestPointSoFar = null; foreach (SequencePoint point in sequencePoints) { if (point.Offset > ilOffset) break; if (point.StartLine != SequencePoint.HiddenLine) bestPointSoFar = point; } if (bestPointSoFar.HasValue) { sourceLine = bestPointSoFar.Value.StartLine; sourceColumn = bestPointSoFar.Value.StartColumn; sourceFile = reader.GetString(reader.GetDocument(bestPointSoFar.Value.Document).Name); } } } } } /// <summary> /// Returns the portable PDB reader for the assembly path /// </summary> /// <param name="assemblyPath">file path of the assembly or null</param> /// <param name="loadedPeAddress">loaded PE image address or zero</param> /// <param name="loadedPeSize">loaded PE image size</param> /// <param name="inMemoryPdbAddress">in memory PDB address or zero</param> /// <param name="inMemoryPdbSize">in memory PDB size</param> /// <param name="reader">returns the reader</param> /// <returns>reader</returns> private MetadataReader GetReader(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize, IntPtr inMemoryPdbAddress, int inMemoryPdbSize) { if (loadedPeAddress != IntPtr.Zero) { Tuple<MetadataReaderProvider, MetadataReader> tuple; if (_readerCache.TryGetValue(loadedPeAddress, out tuple)) { return tuple.Item2; } } MetadataReaderProvider provider = null; MetadataReader reader = null; if (assemblyPath != null) { uint stamp; int age; Guid guid; string pdbName = GetPdbPathFromPeStream(assemblyPath, loadedPeAddress, loadedPeSize, out age, out guid, out stamp); if (pdbName != null && File.Exists(pdbName)) { Stream pdbStream = File.OpenRead(pdbName); provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream); MetadataReader rdr = provider.GetMetadataReader(); // Validate that the PDB matches the assembly version if (age == 1 && IdEquals(rdr.DebugMetadataHeader.Id, guid, stamp)) { reader = rdr; } else { provider.Dispose(); provider = null; } } } else if (inMemoryPdbAddress != IntPtr.Zero && inMemoryPdbSize > 0) { unsafe { provider = MetadataReaderProvider.FromPortablePdbImage((byte*)inMemoryPdbAddress.ToPointer(), inMemoryPdbSize); reader = provider.GetMetadataReader(); } } if (reader != null && loadedPeAddress != IntPtr.Zero) { _readerCache.Add(loadedPeAddress, Tuple.Create(provider, reader)); } return reader; } /// <summary> /// Read the pdb file name and assembly version information from the PE file. /// </summary> /// <param name="assemblyPath">PE file path</param> /// <param name="loadedPeAddress">loaded PE image address or zero</param> /// <param name="loadedPeSize">loaded PE image size</param> /// <param name="age">age</param> /// <param name="guid">assembly guid</param> /// <param name="stamp">time stamp</param> /// <returns>pdb name or null</returns> /// <remarks> /// loadedPeAddress and loadedPeSize will be used here when/if the PEReader /// support runtime loaded images instead of just file images. /// </remarks> private static unsafe string GetPdbPathFromPeStream(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize, out int age, out Guid guid, out uint stamp) { if (File.Exists(assemblyPath)) { Stream peStream = File.OpenRead(assemblyPath); using (PEReader peReader = new PEReader(peStream)) { foreach (DebugDirectoryEntry entry in peReader.ReadDebugDirectory()) { if (entry.Type == DebugDirectoryEntryType.CodeView) { CodeViewDebugDirectoryData codeViewData = peReader.ReadCodeViewDebugDirectoryData(entry); stamp = entry.Stamp; age = codeViewData.Age; guid = codeViewData.Guid; string peDirectory = Path.GetDirectoryName(assemblyPath); return Path.Combine(peDirectory, Path.GetFileName(codeViewData.Path)); } } } } stamp = 0; age = 0; guid = new Guid(); return null; } /// <summary> /// Returns true if the portable pdb id matches the guid and stamp. /// </summary> private static bool IdEquals(ImmutableArray<byte> left, Guid rightGuid, uint rightStamp) { if (left.Length != 20) { // invalid id return false; } byte[] guidBytes = rightGuid.ToByteArray(); for (int i = 0; i < guidBytes.Length; i++) { if (guidBytes[i] != left[i]) { return false; } } byte[] stampBytes = BitConverter.GetBytes(rightStamp); for (int i = 0; i < stampBytes.Length; i++) { if (stampBytes[i] != left[guidBytes.Length + i]) { return false; } } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Threading; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.ObjectPool; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Mvc.IntegrationTests { public static class ModelBindingTestHelper { public static ModelBindingTestContext GetTestContext( Action<HttpRequest> updateRequest = null, Action<MvcOptions> updateOptions = null, ControllerActionDescriptor actionDescriptor = null, IModelMetadataProvider metadataProvider = null, MvcOptions mvcOptions = null) { var httpContext = GetHttpContext(metadataProvider, updateRequest, updateOptions, mvcOptions); var services = httpContext.RequestServices; metadataProvider = metadataProvider ?? services.GetRequiredService<IModelMetadataProvider>(); var options = services.GetRequiredService<IOptions<MvcOptions>>(); var context = new ModelBindingTestContext { ActionDescriptor = actionDescriptor ?? new ControllerActionDescriptor(), HttpContext = httpContext, MetadataProvider = metadataProvider, MvcOptions = options.Value, RouteData = new RouteData(), ValueProviderFactories = new List<IValueProviderFactory>(options.Value.ValueProviderFactories), }; return context; } public static ParameterBinder GetParameterBinder( MvcOptions options = null, IModelBinderProvider binderProvider = null) { if (options == null) { var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider(); return GetParameterBinder(metadataProvider, binderProvider); } else { var metadataProvider = TestModelMetadataProvider.CreateProvider(options.ModelMetadataDetailsProviders); return GetParameterBinder(metadataProvider, binderProvider, options); } } public static ParameterBinder GetParameterBinder(ModelBindingTestContext testContext) { return GetParameterBinder(testContext.HttpContext.RequestServices); } public static ParameterBinder GetParameterBinder(IServiceProvider serviceProvider) { var metadataProvider = serviceProvider.GetRequiredService<IModelMetadataProvider>(); var options = serviceProvider.GetRequiredService<IOptions<MvcOptions>>(); return new ParameterBinder( metadataProvider, new ModelBinderFactory(metadataProvider, options, serviceProvider), new DefaultObjectValidator( metadataProvider, new[] { new CompositeModelValidatorProvider(GetModelValidatorProviders(options)) }, options.Value), options, NullLoggerFactory.Instance); } public static ParameterBinder GetParameterBinder( IModelMetadataProvider metadataProvider, IModelBinderProvider binderProvider = null, MvcOptions mvcOptions = null, ObjectModelValidator validator = null) { var services = GetServices(metadataProvider, mvcOptions: mvcOptions); var options = services.GetRequiredService<IOptions<MvcOptions>>(); if (binderProvider != null) { options.Value.ModelBinderProviders.Insert(0, binderProvider); } validator ??= new DefaultObjectValidator( metadataProvider, new[] { new CompositeModelValidatorProvider(GetModelValidatorProviders(options)) }, options.Value); return new ParameterBinder( metadataProvider, new ModelBinderFactory(metadataProvider, options, services), validator, options, NullLoggerFactory.Instance); } public static IModelBinderFactory GetModelBinderFactory( IModelMetadataProvider metadataProvider, IServiceProvider services = null) { if (services == null) { services = GetServices(metadataProvider); } var options = services.GetRequiredService<IOptions<MvcOptions>>(); return new ModelBinderFactory(metadataProvider, options, services); } public static IObjectModelValidator GetObjectValidator( IModelMetadataProvider metadataProvider, IOptions<MvcOptions> options = null) { return new DefaultObjectValidator( metadataProvider, GetModelValidatorProviders(options), options?.Value ?? new MvcOptions()); } private static IList<IModelValidatorProvider> GetModelValidatorProviders(IOptions<MvcOptions> options) { if (options == null) { return TestModelValidatorProvider.CreateDefaultProvider().ValidatorProviders; } else { return options.Value.ModelValidatorProviders; } } private static HttpContext GetHttpContext( IModelMetadataProvider metadataProvider, Action<HttpRequest> updateRequest = null, Action<MvcOptions> updateOptions = null, MvcOptions mvcOptions = null) { var httpContext = new DefaultHttpContext(); httpContext.Features.Set<IHttpRequestLifetimeFeature>(new CancellableRequestLifetimeFeature()); updateRequest?.Invoke(httpContext.Request); httpContext.RequestServices = GetServices(metadataProvider, updateOptions, mvcOptions); return httpContext; } public static IServiceProvider GetServices( IModelMetadataProvider metadataProvider, Action<MvcOptions> updateOptions = null, MvcOptions mvcOptions = null) { var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton(new ApplicationPartManager()); if (metadataProvider != null) { serviceCollection.AddSingleton(metadataProvider); } else if (updateOptions != null || mvcOptions != null) { serviceCollection.AddSingleton(services => { var optionsAccessor = services.GetRequiredService<IOptions<MvcOptions>>(); return TestModelMetadataProvider.CreateProvider(optionsAccessor.Value.ModelMetadataDetailsProviders); }); } else { serviceCollection.AddSingleton<IModelMetadataProvider>(services => { return TestModelMetadataProvider.CreateDefaultProvider(); }); } if (mvcOptions != null) { serviceCollection.AddSingleton(Options.Create(mvcOptions)); } serviceCollection.AddMvc() .AddNewtonsoftJson(); serviceCollection .AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance) .AddTransient<ILogger<DefaultAuthorizationService>, Logger<DefaultAuthorizationService>>(); if (updateOptions != null) { serviceCollection.Configure(updateOptions); } return serviceCollection.BuildServiceProvider(); } private class CancellableRequestLifetimeFeature : IHttpRequestLifetimeFeature { private readonly CancellationTokenSource _cts = new CancellationTokenSource(); public CancellationToken RequestAborted { get => _cts.Token; set => throw new NotImplementedException(); } public void Abort() { _cts.Cancel(); } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using ASC.Collections; using ASC.Common.Data; using ASC.Common.Data.Sql; using ASC.Common.Data.Sql.Expressions; using ASC.Core.Tenants; using ASC.Core.Users; using ASC.ElasticSearch; using ASC.Projects.Core.DataInterfaces; using ASC.Projects.Core.Domain; using ASC.Web.Projects.Core.Search; using Newtonsoft.Json.Linq; namespace ASC.Projects.Data.DAO { internal class CachedProjectDao : ProjectDao { private readonly HttpRequestDictionary<Project> projectCache = new HttpRequestDictionary<Project>("project"); public CachedProjectDao(int tenantId) : base(tenantId) { } public override void Delete(int projectId, out List<int> messages, out List<int> tasks) { ResetCache(projectId); base.Delete(projectId, out messages, out tasks); } public override void RemoveFromTeam(int projectId, Guid participantId) { ResetCache(projectId); base.RemoveFromTeam(projectId, participantId); } public override Project Update(Project project) { if (project != null) { ResetCache(project.ID); } return base.Update(project); } public override Project GetById(int projectId) { return projectCache.Get(projectId.ToString(CultureInfo.InvariantCulture), () => GetBaseById(projectId)); } private Project GetBaseById(int projectId) { return base.GetById(projectId); } public override void AddToTeam(int projectId, Guid participantId) { ResetCache(projectId); base.AddToTeam(projectId, participantId); } private void ResetCache(int projectId) { projectCache.Reset(projectId.ToString(CultureInfo.InvariantCulture)); } } class ProjectDao : BaseDao, IProjectDao { public static readonly string[] ProjectColumns = new[] { "id", "title", "description", "status", "responsible_id", "private", "create_by", "create_on", "last_modified_by", "last_modified_on" }; private readonly HttpRequestDictionary<TeamCacheItem> teamCache = new HttpRequestDictionary<TeamCacheItem>("ProjectDao-TeamCacheItem"); private readonly HttpRequestDictionary<List<Guid>> followCache = new HttpRequestDictionary<List<Guid>>("ProjectDao-FollowCache"); private readonly Converter<object[], Project> converter; public ProjectDao(int tenantId) : base(tenantId) { converter = ToProject; } public List<Project> GetAll(ProjectStatus? status, int max) { var query = Query(ProjectsTable) .Select(ProjectColumns) .SetMaxResults(max) .OrderBy("title", true); if (status != null) query.Where("status", status); return Db.ExecuteList(query).ConvertAll(converter); } public List<Project> GetLast(ProjectStatus? status, int offset, int max) { var query = Query(ProjectsTable) .SetFirstResult(offset) .Select(ProjectColumns) .SetMaxResults(max) .OrderBy("create_on", false); if (status != null) query.Where("status", status); return Db.ExecuteList(query).ConvertAll(converter); } public List<Project> GetOpenProjectsWithTasks(Guid participantId) { var query = new SqlQuery(ProjectsTable + " p") .Select(ProjectColumns.Select(c => "p." + c).ToArray()) .InnerJoin(TasksTable + " t", Exp.EqColumns("t.tenant_id", "p.tenant_id") & Exp.EqColumns("t.project_id", "p.id")) .Where("p.tenant_id", Tenant) .Where("p.status", ProjectStatus.Open) .OrderBy("p.title", true) .GroupBy("p.id"); if (!participantId.Equals(Guid.Empty)) { query.InnerJoin(ParticipantTable + " ppp", Exp.EqColumns("ppp.tenant", "p.tenant_id") & Exp.EqColumns("ppp.project_id", "p.id") & Exp.Eq("ppp.removed", false)) .Where("ppp.participant_id", participantId); } return Db.ExecuteList(query).ConvertAll(converter); } public DateTime GetMaxLastModified() { var query = Query(ProjectsTable).SelectMax("last_modified_on"); return TenantUtil.DateTimeFromUtc(Db.ExecuteScalar<DateTime>(query)); } public void UpdateLastModified(int projectId) { Db.ExecuteNonQuery( Update(ProjectsTable) .Set("last_modified_on", DateTime.UtcNow) .Set("last_modified_by", CurrentUserID) .Where("id", projectId)); } public List<Project> GetByParticipiant(Guid participantId, ProjectStatus status) { var query = Query(ProjectsTable) .Select(ProjectColumns) .InnerJoin(ParticipantTable, Exp.EqColumns("id", "project_id") & Exp.Eq("removed", false) & Exp.EqColumns("tenant_id", "tenant")) .Where("status", status) .Where("participant_id", participantId.ToString()) .OrderBy("title", true); return Db.ExecuteList(query).ConvertAll(converter); } public List<Project> GetByFilter(TaskFilter filter, bool isAdmin, bool checkAccess) { var teamQuery = new SqlQuery(ParticipantTable + " pp") .SelectCount() .InnerJoin("core_user cup", Exp.EqColumns("cup.tenant", "pp.tenant") & Exp.EqColumns("cup.id", "pp.participant_id")) .Where(Exp.EqColumns("pp.tenant", "p.tenant_id")) .Where(Exp.EqColumns("pp.project_id", "p.id")) .Where("pp.removed", false) .Where("cup.status", EmployeeStatus.Active); var query = new SqlQuery(ProjectsTable + " p") .Select(ProjectColumns.Select(c => "p." + c).ToArray()) .Select(new SqlQuery(MilestonesTable + " m").SelectCount().Where(Exp.EqColumns("m.tenant_id", "p.tenant_id") & Exp.EqColumns("m.project_id", "p.id")).Where(Exp.Eq("m.status", MilestoneStatus.Open))) .Select(new SqlQuery(TasksTable + " t").SelectCount().Where(Exp.EqColumns("t.tenant_id", "p.tenant_id") & Exp.EqColumns("t.project_id", "p.id")).Where(!Exp.Eq("t.status", TaskStatus.Closed))) .Select(new SqlQuery(TasksTable + " t").SelectCount().Where(Exp.EqColumns("t.tenant_id", "p.tenant_id") & Exp.EqColumns("t.project_id", "p.id"))) .Select(teamQuery) .Select("p.private") .Where("p.tenant_id", Tenant); if (filter.Max > 0 && filter.Max < 150000) { query.SetFirstResult((int)filter.Offset); query.SetMaxResults((int)filter.Max * 2); } query.OrderBy("(case p.status when 2 then 1 when 1 then 2 else 0 end)", true); if (!string.IsNullOrEmpty(filter.SortBy)) { var sortColumns = filter.SortColumns["Project"]; sortColumns.Remove(filter.SortBy); query.OrderBy("p." + filter.SortBy, filter.SortOrder); foreach (var sort in sortColumns.Keys) { query.OrderBy("p." + sort, sortColumns[sort]); } } query = CreateQueryFilter(query, filter, isAdmin, checkAccess); return Db.ExecuteList(query).ConvertAll(ToProjectFull); } public int GetByFilterCount(TaskFilter filter, bool isAdmin, bool checkAccess) { var query = new SqlQuery(ProjectsTable + " p") .Select("p.id") .Where("p.tenant_id", Tenant); query = CreateQueryFilter(query, filter, isAdmin, checkAccess); var queryCount = new SqlQuery().SelectCount().From(query, "t1"); return Db.ExecuteScalar<int>(queryCount); } private SqlQuery CreateQueryFilter(SqlQuery query, TaskFilter filter, bool isAdmin, bool checkAccess) { if (filter.TagId != 0) { if (filter.TagId == -1) { query.LeftOuterJoin(ProjectTagTable + " ptag", Exp.EqColumns("ptag.project_id", "p.id")); query.Where("ptag.tag_id", null); } else { query.InnerJoin(ProjectTagTable + " ptag", Exp.EqColumns("ptag.project_id", "p.id")); query.Where("ptag.tag_id", filter.TagId); } } if (filter.HasUserId || (filter.ParticipantId.HasValue && !filter.ParticipantId.Equals(Guid.Empty))) { var existParticipant = new SqlQuery(ParticipantTable + " ppp").Select("ppp.participant_id").Where(Exp.EqColumns("p.id", "ppp.project_id") & Exp.Eq("ppp.removed", false) & Exp.Eq("ppp.tenant", Tenant)); if (filter.DepartmentId != Guid.Empty) { existParticipant.InnerJoin("core_usergroup cug", Exp.Eq("cug.removed", false) & Exp.EqColumns("cug.userid", "ppp.participant_id") & Exp.EqColumns("cug.tenant", "ppp.tenant")); existParticipant.Where("cug.groupid", filter.DepartmentId); } if (filter.ParticipantId.HasValue && !filter.ParticipantId.Equals(Guid.Empty)) { existParticipant.Where(Exp.Eq("ppp.participant_id", filter.ParticipantId.ToString())); } query.Where(Exp.Exists(existParticipant)); } if (filter.UserId != Guid.Empty) { query.Where("responsible_id", filter.UserId); } if (filter.Follow) { query.InnerJoin(FollowingProjectTable + " pfpp", Exp.EqColumns("p.id", "pfpp.project_id")); query.Where(Exp.Eq("pfpp.participant_id", CurrentUserID)); } if (filter.ProjectStatuses.Any()) { query.Where(Exp.In("p.status", filter.ProjectStatuses)); } if (!string.IsNullOrEmpty(filter.SearchText)) { List<int> projIds; if (FactoryIndexer<ProjectsWrapper>.TrySelectIds(s => s.MatchAll(filter.SearchText), out projIds)) { query.Where(Exp.In("p.id", projIds)); } else { query.Where(Exp.Like("p.title", filter.SearchText, SqlLike.AnyWhere)); } } query.GroupBy("p.id"); if (checkAccess) { query.Where(Exp.Eq("p.private", false)); } else if (!isAdmin) { var isInTeam = new SqlQuery(ParticipantTable).Select("security").Where(Exp.EqColumns("p.id", "project_id") & Exp.Eq("removed", false) & Exp.Eq("participant_id", CurrentUserID) & Exp.EqColumns("tenant", "p.tenant_id")); query.Where(Exp.Eq("p.private", false) | Exp.Eq("p.responsible_id", CurrentUserID) | (Exp.Eq("p.private", true) & Exp.Exists(isInTeam))); } return query; } public List<Project> GetFollowing(Guid participantId) { var query = Query(ProjectsTable) .Select(ProjectColumns) .InnerJoin(FollowingProjectTable, Exp.EqColumns("id", "project_id")) .Where("participant_id", participantId.ToString()) .Where("status", ProjectStatus.Open) .OrderBy("create_on", true); return Db.ExecuteList(query).ConvertAll(converter); } public bool IsFollow(int projectId, Guid participantId) { var users = followCache[projectId.ToString(CultureInfo.InvariantCulture)]; if (users == null) { var q = new SqlQuery(FollowingProjectTable).Select("participant_id").Where("project_id", projectId); users = Db.ExecuteList(q).ConvertAll(r => new Guid((string)r[0])); followCache.Add(projectId.ToString(CultureInfo.InvariantCulture), users); } return users.Contains(participantId); } public virtual Project GetById(int projectId) { return Db.ExecuteList(Query(ProjectsTable).Select(ProjectColumns).Where("id", projectId)) .ConvertAll(converter) .SingleOrDefault(); } public List<Project> GetById(List<int> projectIDs) { return Db.ExecuteList(Query(ProjectsTable).Select(ProjectColumns).Where(Exp.In("id", projectIDs))) .ConvertAll(converter); } public bool IsExists(int projectId) { var count = Db.ExecuteScalar<int>(Query(ProjectsTable).SelectCount().Where("id", projectId)); return 0 < count; } public List<Project> GetByContactID(int contactId) { var projectIds = Db .ExecuteList(Query("crm_projects").Select("project_id").Where("contact_id", contactId)) .ConvertAll(r => Convert.ToInt32(r[0])); if (!projectIds.Any()) return new List<Project>(0); var milestoneCountQuery = new SqlQuery(MilestonesTable + " m").SelectCount() .Where(Exp.EqColumns("m.project_id", "p.id")) .Where(Exp.Eq("m.status", MilestoneStatus.Open)) .Where(Exp.EqColumns("m.tenant_id", "p.tenant_id")); var taskCountQuery = new SqlQuery(TasksTable + " t").SelectCount() .Where(Exp.EqColumns("t.project_id", "p.id")) .Where(!Exp.Eq("t.status", TaskStatus.Closed)) .Where(Exp.EqColumns("t.tenant_id", "p.tenant_id")); var participantCountQuery = new SqlQuery(ParticipantTable + " pp").SelectCount() .Where(Exp.EqColumns("pp.project_id", "p.id") & Exp.Eq("pp.removed", false)) .Where(Exp.EqColumns("pp.tenant", "p.tenant_id")); var query = new SqlQuery(ProjectsTable + " p") .Select(ProjectColumns.Select(c => "p." + c).ToArray()) .Select(milestoneCountQuery) .Select(taskCountQuery) .Select(participantCountQuery) .Where(Exp.In("p.id", projectIds.ToList())) .Where("p.tenant_id", Tenant); return Db.ExecuteList(query) .Select(r => { var prj = ToProject(r); prj.TaskCount = Convert.ToInt32(r[11]); prj.MilestoneCount = Convert.ToInt32(r[10]); prj.ParticipantCount = Convert.ToInt32(r[12]); return prj; } ).ToList(); } public void AddProjectContact(int projectID, int contactID) { using (var crmDb = DbManager.FromHttpContext("crm")) { crmDb.ExecuteNonQuery(Insert("crm_projects").InColumnValue("project_id", projectID).InColumnValue("contact_id", contactID)); } } public void DeleteProjectContact(int projectID, int contactID) { using (var crmDb = DbManager.FromHttpContext("crm")) { crmDb.ExecuteNonQuery(Delete("crm_projects").Where("project_id", projectID).Where("contact_id", contactID)); } } public int Count() { return Db.ExecuteScalar<int>(Query(ProjectsTable).SelectCount()); } public List<int> GetTaskCount(List<int> projectId, TaskStatus? taskStatus, bool isAdmin) { var query = new SqlQuery(TasksTable + " t") .Select("t.project_id").SelectCount() .Where(Exp.In("t.project_id", projectId)) .Where("t.tenant_id", Tenant) .GroupBy("t.project_id"); if (taskStatus.HasValue) { if (taskStatus.Value == TaskStatus.Open) query.Where(!Exp.Eq("t.status", TaskStatus.Closed)); else query.Where("t.status", TaskStatus.Closed); } if (!isAdmin) { query.InnerJoin(ProjectsTable + " p", Exp.EqColumns("t.project_id", "p.id") & Exp.EqColumns("t.tenant_id", "p.tenant_id")) .LeftOuterJoin(TasksResponsibleTable + " ptr", Exp.EqColumns("t.tenant_id", "ptr.tenant_id") & Exp.EqColumns("t.id", "ptr.task_id") & Exp.Eq("ptr.responsible_id", CurrentUserID)) .LeftOuterJoin(ParticipantTable + " ppp", Exp.EqColumns("p.id", "ppp.project_id") & Exp.EqColumns("p.tenant_id", "ppp.tenant") & Exp.Eq("ppp.removed", false) & Exp.Eq("ppp.participant_id", CurrentUserID)) .Where(Exp.Eq("p.private", false) | !Exp.Eq("ptr.responsible_id", null) | (Exp.Eq("p.private", true) & !Exp.Eq("ppp.security", null) & !Exp.Eq("ppp.security & " + (int)ProjectTeamSecurity.Tasks, (int)ProjectTeamSecurity.Tasks))); } var result = Db.ExecuteList(query); return projectId.ConvertAll( pid => { var res = result.Find(r => Convert.ToInt32(r[0]) == pid); return res == null ? 0 : Convert.ToInt32(res[1]); } ); } public int GetMessageCount(int projectId) { var query = Query(MessagesTable) .SelectCount() .Where("project_id", projectId); return Db.ExecuteScalar<int>(query); } public int GetTotalTimeCount(int projectId) { var query = Query(TimeTrackingTable) .SelectCount() .Where("project_id", projectId); return Db.ExecuteScalar<int>(query); } public int GetMilestoneCount(int projectId, params MilestoneStatus[] statuses) { var query = Query(MilestonesTable) .SelectCount() .Where("project_id", projectId); if (statuses.Any()) { query.Where(Exp.In("status", statuses)); } return Db.ExecuteScalar<int>(query); } public Project Create(Project project) { var insert = Insert(ProjectsTable, false) .InColumns("id", "title", "description", "status", "responsible_id", "private", "create_by", "create_on", "last_modified_on") .Values( project.ID, project.Title, project.Description, project.Status, project.Responsible.ToString(), project.Private, project.CreateBy.ToString(), TenantUtil.DateTimeToUtc(project.CreateOn), TenantUtil.DateTimeToUtc(project.LastModifiedOn)) .Identity(1, 0, true); project.ID = Db.ExecuteScalar<int>(insert); return project; } public virtual Project Update(Project project) { var update = Update(ProjectsTable) .Set("title", project.Title) .Set("description", project.Description) .Set("status", project.Status) .Set("status_changed", project.StatusChangedOn) .Set("responsible_id", project.Responsible.ToString()) .Set("private", project.Private) .Set("last_modified_by", project.LastModifiedBy.ToString()) .Set("last_modified_on", TenantUtil.DateTimeToUtc(project.LastModifiedOn)) .Where("id", project.ID); Db.ExecuteNonQuery(update); return project; } public virtual void Delete(int projectId, out List<int> messages, out List<int> tasks) { using (var tx = Db.BeginTransaction()) { messages = Db.ExecuteList(Query(MessagesTable) .Select("id") .Where("project_id", projectId)).ConvertAll(r => Convert.ToInt32(r[0])); var milestones = Db.ExecuteList(Query(MilestonesTable) .Select("id") .Where("project_id", projectId)).ConvertAll(r => Convert.ToInt32(r[0])); tasks = Db.ExecuteList(Query(TasksTable) .Select("id") .Where("project_id", projectId)).ConvertAll(r => Convert.ToInt32(r[0])); if (messages.Any()) { Db.ExecuteNonQuery(Delete(CommentsTable).Where(Exp.In("target_uniq_id", messages.Select(r => "Message_" + r).ToList()))); Db.ExecuteNonQuery(Delete(MessagesTable).Where("project_id", projectId)); } if (milestones.Any()) { Db.ExecuteNonQuery(Delete(CommentsTable).Where(Exp.In("target_uniq_id", milestones.Select(r => "Milestone_" + r).ToList()))); Db.ExecuteNonQuery(Delete(MilestonesTable).Where("project_id", projectId)); } if (tasks.Any()) { Db.ExecuteNonQuery(Delete(CommentsTable).Where(Exp.In("target_uniq_id", tasks.Select(r => "Task_" + r).ToList()))); Db.ExecuteNonQuery(Delete(TasksOrderTable).Where("project_id", projectId)); Db.ExecuteNonQuery(Delete(TasksResponsibleTable).Where(Exp.In("task_id", tasks))); Db.ExecuteNonQuery(Delete(SubtasksTable).Where(Exp.In("task_id", tasks))); Db.ExecuteNonQuery(Delete(TasksTable).Where("project_id", projectId)); } Db.ExecuteNonQuery(new SqlDelete(ParticipantTable).Where("project_id", projectId).Where("tenant", Tenant)); Db.ExecuteNonQuery(new SqlDelete(FollowingProjectTable).Where("project_id", projectId)); Db.ExecuteNonQuery(new SqlDelete(ProjectTagTable).Where("project_id", projectId)); Db.ExecuteNonQuery(Delete(TimeTrackingTable).Where("project_id", projectId)); Db.ExecuteNonQuery(Delete(ProjectsTable).Where("id", projectId)); tx.Commit(); } Db.ExecuteNonQuery(Delete(TagsTable).Where(!Exp.In("id", new SqlQuery("projects_project_tag").Select("tag_id")))); } public virtual void AddToTeam(int projectId, Guid participantId) { Db.ExecuteNonQuery( new SqlInsert(ParticipantTable, true) .InColumnValue("project_id", projectId) .InColumnValue("participant_id", participantId.ToString()) .InColumnValue("created", DateTime.UtcNow) .InColumnValue("updated", DateTime.UtcNow) .InColumnValue("removed", false) .InColumnValue("tenant", Tenant)); UpdateLastModified(projectId); var key = string.Format("{0}|{1}", projectId, participantId); var item = teamCache.Get(key, () => new TeamCacheItem(true, ProjectTeamSecurity.None)); if (item != null) item.InTeam = true; } public virtual void RemoveFromTeam(int projectId, Guid participantId) { Db.ExecuteNonQuery( new SqlUpdate(ParticipantTable) .Set("removed", true) .Set("updated", DateTime.UtcNow) .Where("tenant", Tenant) .Where("project_id", projectId) .Where("participant_id", participantId.ToString())); UpdateLastModified(projectId); var key = string.Format("{0}|{1}", projectId, participantId); var item = teamCache.Get(key, () => new TeamCacheItem(true, ProjectTeamSecurity.None)); if (item != null) item.InTeam = false; } public bool IsInTeam(int projectId, Guid participantId) { return GetTeamItemFromCacheOrLoad(projectId, participantId).InTeam; } public List<Participant> GetTeam(Project project, bool withExcluded = false) { if (project == null) return new List<Participant>(); var query = new SqlQuery(ParticipantTable + " pp") .InnerJoin(ProjectsTable + " pt", Exp.EqColumns("pp.tenant", "pt.tenant_id") & Exp.EqColumns("pp.project_id", "pt.id")) .Select("pp.participant_id, pp.security, pp.project_id") .Select(Exp.EqColumns("pp.project_id", "pt.id")) .Select("pp.removed") .Where("pp.tenant", Tenant) .Where("pp.project_id", project.ID); if (!withExcluded) { query.Where("pp.removed", false); } return Db.ExecuteList(query).ConvertAll(ToParticipant); } public List<Participant> GetTeam(IEnumerable<Project> projects) { return Db.ExecuteList( new SqlQuery(ParticipantTable + " pp") .InnerJoin(ProjectsTable + " pt", Exp.EqColumns("pp.tenant", "pt.tenant_id") & Exp.EqColumns("pp.project_id", "pt.id")) .Select("distinct pp.participant_id, pp.security, pp.project_id") .Select(Exp.EqColumns("pp.project_id", "pt.id")) .Select("pp.removed") .Where("pp.tenant", Tenant) .Where(Exp.In("pp.project_id", projects.Select(r => r.ID).ToArray())) .Where("pp.removed", false)) .ConvertAll(ToParticipant); } public List<ParticipantFull> GetTeamUpdates(DateTime from, DateTime to) { var query = new SqlQuery(ProjectsTable + " p") .Select(ProjectColumns.Select(x => "p." + x).ToArray()) .Select("pp.participant_id", "pp.removed", "pp.created", "pp.updated") .LeftOuterJoin("projects_project_participant pp", Exp.EqColumns("pp.project_id", "p.id")) .Where(Exp.Between("pp.created", from, to) | Exp.Between("pp.updated", from, to)); return Db.ExecuteList(query).ConvertAll(ToParticipantFull); } public DateTime GetTeamMaxLastModified() { var query = new SqlQuery(ParticipantTable).SelectMax("updated").Where("tenant", Tenant); return TenantUtil.DateTimeFromUtc(Db.ExecuteScalar<DateTime>(query)); } public void SetTeamSecurity(int projectId, Guid participantId, ProjectTeamSecurity teamSecurity) { Db.ExecuteNonQuery( new SqlUpdate(ParticipantTable) .Set("updated", DateTime.UtcNow) .Set("security", (int)teamSecurity) .Where("tenant", Tenant) .Where("project_id", projectId) .Where("participant_id", participantId.ToString())); var key = string.Format("{0}|{1}", projectId, participantId); var item = teamCache.Get(key); if (item != null) teamCache[key].Security = teamSecurity; } public ProjectTeamSecurity GetTeamSecurity(int projectId, Guid participantId) { return GetTeamItemFromCacheOrLoad(projectId, participantId).Security; } private TeamCacheItem GetTeamItemFromCacheOrLoad(int projectId, Guid participantId) { var key = string.Format("{0}|{1}", projectId, participantId); var item = teamCache.Get(key); if (item != null) return item; item = teamCache.Get(string.Format("{0}|{1}", 0, participantId)); if (item != null) return new TeamCacheItem(false, ProjectTeamSecurity.None); var projectList = Db.ExecuteList( new SqlQuery(ParticipantTable) .Select("project_id", "security") .Where("tenant", Tenant) .Where("participant_id", participantId.ToString()) .Where("removed", false)); var teamCacheItem = new TeamCacheItem(true, ProjectTeamSecurity.None); teamCache.Add(string.Format("{0}|{1}", 0, participantId), teamCacheItem); foreach (var prj in projectList) { teamCacheItem = new TeamCacheItem(true, (ProjectTeamSecurity)Convert.ToInt32(prj[1])); key = string.Format("{0}|{1}", prj[0], participantId); teamCache.Add(key, teamCacheItem); } var currentProject = projectList.Find(r => Convert.ToInt32(r[0]) == projectId); teamCacheItem = new TeamCacheItem(currentProject != null, currentProject != null ? (ProjectTeamSecurity)Convert.ToInt32(currentProject[1]) : ProjectTeamSecurity.None); key = string.Format("{0}|{1}", projectId, participantId); teamCache.Add(key, teamCacheItem); return teamCacheItem; } public void SetTaskOrder(int projectID, string order) { using (var tr = Db.BeginTransaction()) { var query = Insert(TasksOrderTable) .InColumnValue("project_id", projectID) .InColumnValue("task_order", order); Db.ExecuteNonQuery(query); try { var orderJson = JObject.Parse(order); var newTaskOrder = orderJson["tasks"].Select(r => r.Value<int>()).ToList(); for (var i = 0; i < newTaskOrder.Count; i++) { Db.ExecuteNonQuery(Update(TasksTable) .Where("project_id", projectID) .Where("id", newTaskOrder[i]) .Set("sort_order", i)); } } finally { tr.Commit(); } } } public string GetTaskOrder(int projectID) { var query = Query(TasksOrderTable) .Select("task_order") .Where("project_id", projectID); return Db.ExecuteList(query, r => Convert.ToString(r[0])).FirstOrDefault(); } public static ParticipantFull ToParticipantFull(object[] x) { int offset = ProjectColumns.Count(); return new ParticipantFull(new Guid((string)x[0 + offset])) { Project = ToProject(x), Removed = Convert.ToBoolean(x[1 + offset]), Created = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(x[2 + offset])), Updated = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(x[3 + offset])) }; } public static Project ToProject(object[] r) { return new Project { ID = Convert.ToInt32(r[0]), Title = (string)r[1], Description = (string)r[2], Status = (ProjectStatus)Convert.ToInt32(r[3]), Responsible = ToGuid(r[4]), Private = Convert.ToBoolean(r[5]), CreateBy = ToGuid(r[6]), CreateOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[7])), LastModifiedBy = ToGuid(r[8]), LastModifiedOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[9])), }; } public static Project ToProjectFull(object[] r) { var project = ToProject(r); project.TaskCount = Convert.ToInt32(r[11]); project.TaskCountTotal = Convert.ToInt32(r[12]); project.MilestoneCount = Convert.ToInt32(r[10]); project.ParticipantCount = Convert.ToInt32(r[13]); return project; } public static Participant ToParticipant(object[] r) { return new Participant(new Guid((string)r[0])) { ProjectTeamSecurity = (ProjectTeamSecurity)Convert.ToInt32(r[1]), ProjectID = Convert.ToInt32(r[2]), IsManager = Convert.ToBoolean(r[3]), IsRemovedFromTeam = Convert.ToBoolean(r[4]) }; } private class TeamCacheItem { public bool InTeam { get; set; } public ProjectTeamSecurity Security { get; set; } public TeamCacheItem(bool inteam, ProjectTeamSecurity security) { InTeam = inteam; Security = security; } } public IEnumerable<Project> GetProjects(Exp where) { return Db.ExecuteList(Query(ProjectsTable + " p").Select(ProjectColumns).Where(where)).ConvertAll(converter); } } }
using UnityEngine; //using Windows.Kinect; using System.Collections; using System.Collections.Generic; /// <summary> /// KinectGestures is utility class that processes programmatic Kinect gestures /// </summary> public class KinectGestures { /// <summary> /// This interface needs to be implemented by all Kinect gesture listeners /// </summary> public interface GestureListenerInterface { /// <summary> /// Invoked when a new user is detected. Here you can start gesture tracking by invoking KinectManager.DetectGesture()-function. /// </summary> /// <param name="userId">User ID</param> /// <param name="userIndex">User index</param> void UserDetected(long userId, int userIndex); /// <summary> /// Invoked when a user gets lost. All tracked gestures for this user are cleared automatically. /// </summary> /// <param name="userId">User ID</param> /// <param name="userIndex">User index</param> void UserLost(long userId, int userIndex); /// <summary> /// Invoked when a gesture is in progress. /// </summary> /// <param name="userId">User ID</param> /// <param name="userIndex">User index</param> /// <param name="gesture">Gesture type</param> /// <param name="progress">Gesture progress [0..1]</param> /// <param name="joint">Joint type</param> /// <param name="screenPos">Normalized viewport position</param> void GestureInProgress(long userId, int userIndex, Gestures gesture, float progress, KinectInterop.JointType joint, Vector3 screenPos); /// <summary> /// Invoked if a gesture is completed. /// </summary> /// <returns><c>true</c>, if the gesture detection must be restarted, <c>false</c> otherwise.</returns> /// <param name="userId">User ID</param> /// <param name="userIndex">User index</param> /// <param name="gesture">Gesture type</param> /// <param name="joint">Joint type</param> /// <param name="screenPos">Normalized viewport position</param> bool GestureCompleted(long userId, int userIndex, Gestures gesture, KinectInterop.JointType joint, Vector3 screenPos); /// <summary> /// Invoked if a gesture is cancelled. /// </summary> /// <returns><c>true</c>, if the gesture detection must be retarted, <c>false</c> otherwise.</returns> /// <param name="userId">User ID</param> /// <param name="userIndex">User index</param> /// <param name="gesture">Gesture type</param> /// <param name="joint">Joint type</param> bool GestureCancelled(long userId, int userIndex, Gestures gesture, KinectInterop.JointType joint); } /// <summary> /// The gesture types. /// </summary> public enum Gestures { None = 0, RaiseRightHand, RaiseLeftHand, Psi, Tpose, Stop, Wave, // Click, SwipeLeft, SwipeRight, SwipeUp, SwipeDown, // RightHandCursor, // LeftHandCursor, ZoomOut, ZoomIn, Wheel, Jump, Squat, Push, Pull, LeanLeft, LeanRight, KickLeft, KickRight } /// <summary> /// Gesture data structure. /// </summary> public struct GestureData { public long userId; public Gestures gesture; public int state; public float timestamp; public int joint; public Vector3 jointPos; public Vector3 screenPos; public float tagFloat; public Vector3 tagVector; public Vector3 tagVector2; public float progress; public bool complete; public bool cancelled; public List<Gestures> checkForGestures; public float startTrackingAtTime; } // Gesture related constants, variables and functions private static int leftHandIndex; private static int rightHandIndex; private static int leftElbowIndex; private static int rightElbowIndex; private static int leftShoulderIndex; private static int rightShoulderIndex; private static int hipCenterIndex; private static int shoulderCenterIndex; private static int leftHipIndex; private static int rightHipIndex; private static int leftAnkleIndex; private static int rightAnkleIndex; /// <summary> /// Gets the list of gesture joint indexes. /// </summary> /// <returns>The needed joint indexes.</returns> /// <param name="manager">The KinectManager instance</param> public static int[] GetNeededJointIndexes(KinectManager manager) { leftHandIndex = manager.GetJointIndex(KinectInterop.JointType.HandLeft); rightHandIndex = manager.GetJointIndex(KinectInterop.JointType.HandRight); leftElbowIndex = manager.GetJointIndex(KinectInterop.JointType.ElbowLeft); rightElbowIndex = manager.GetJointIndex(KinectInterop.JointType.ElbowRight); leftShoulderIndex = manager.GetJointIndex(KinectInterop.JointType.ShoulderLeft); rightShoulderIndex = manager.GetJointIndex(KinectInterop.JointType.ShoulderRight); hipCenterIndex = manager.GetJointIndex(KinectInterop.JointType.SpineBase); shoulderCenterIndex = manager.GetJointIndex(KinectInterop.JointType.SpineShoulder); leftHipIndex = manager.GetJointIndex(KinectInterop.JointType.HipLeft); rightHipIndex = manager.GetJointIndex(KinectInterop.JointType.HipRight); leftAnkleIndex = manager.GetJointIndex(KinectInterop.JointType.AnkleLeft); rightAnkleIndex = manager.GetJointIndex(KinectInterop.JointType.AnkleRight); int[] neededJointIndexes = { leftHandIndex, rightHandIndex, leftElbowIndex, rightElbowIndex, leftShoulderIndex, rightShoulderIndex, hipCenterIndex, shoulderCenterIndex, leftHipIndex, rightHipIndex, leftAnkleIndex, rightAnkleIndex }; return neededJointIndexes; } private static void SetGestureJoint(ref GestureData gestureData, float timestamp, int joint, Vector3 jointPos) { gestureData.joint = joint; gestureData.jointPos = jointPos; gestureData.timestamp = timestamp; gestureData.state++; } private static void SetGestureCancelled(ref GestureData gestureData) { gestureData.state = 0; gestureData.progress = 0f; gestureData.cancelled = true; } private static void CheckPoseComplete(ref GestureData gestureData, float timestamp, Vector3 jointPos, bool isInPose, float durationToComplete) { if(isInPose) { float timeLeft = timestamp - gestureData.timestamp; gestureData.progress = durationToComplete > 0f ? Mathf.Clamp01(timeLeft / durationToComplete) : 1.0f; if(timeLeft >= durationToComplete) { gestureData.timestamp = timestamp; gestureData.jointPos = jointPos; gestureData.state++; gestureData.complete = true; } } else { SetGestureCancelled(ref gestureData); } } private static void SetScreenPos(long userId, ref GestureData gestureData, ref Vector3[] jointsPos, ref bool[] jointsTracked) { Vector3 handPos = jointsPos[rightHandIndex]; // Vector3 elbowPos = jointsPos[rightElbowIndex]; // Vector3 shoulderPos = jointsPos[rightShoulderIndex]; bool calculateCoords = false; if(gestureData.joint == rightHandIndex) { if(jointsTracked[rightHandIndex] /**&& jointsTracked[rightElbowIndex] && jointsTracked[rightShoulderIndex]*/) { calculateCoords = true; } } else if(gestureData.joint == leftHandIndex) { if(jointsTracked[leftHandIndex] /**&& jointsTracked[leftElbowIndex] && jointsTracked[leftShoulderIndex]*/) { handPos = jointsPos[leftHandIndex]; // elbowPos = jointsPos[leftElbowIndex]; // shoulderPos = jointsPos[leftShoulderIndex]; calculateCoords = true; } } if(calculateCoords) { // if(gestureData.tagFloat == 0f || gestureData.userId != userId) // { // // get length from shoulder to hand (screen range) // Vector3 shoulderToElbow = elbowPos - shoulderPos; // Vector3 elbowToHand = handPos - elbowPos; // gestureData.tagFloat = (shoulderToElbow.magnitude + elbowToHand.magnitude); // } if(jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftShoulderIndex] && jointsTracked[rightShoulderIndex]) { Vector3 shoulderToHips = jointsPos[shoulderCenterIndex] - jointsPos[hipCenterIndex]; Vector3 rightToLeft = jointsPos[rightShoulderIndex] - jointsPos[leftShoulderIndex]; gestureData.tagVector2.x = rightToLeft.x; // * 1.2f; gestureData.tagVector2.y = shoulderToHips.y; // * 1.2f; if(gestureData.joint == rightHandIndex) { gestureData.tagVector.x = jointsPos[rightShoulderIndex].x - gestureData.tagVector2.x / 2; gestureData.tagVector.y = jointsPos[hipCenterIndex].y; } else { gestureData.tagVector.x = jointsPos[leftShoulderIndex].x - gestureData.tagVector2.x / 2; gestureData.tagVector.y = jointsPos[hipCenterIndex].y; } } // Vector3 shoulderToHand = handPos - shoulderPos; // gestureData.screenPos.x = Mathf.Clamp01((gestureData.tagFloat / 2 + shoulderToHand.x) / gestureData.tagFloat); // gestureData.screenPos.y = Mathf.Clamp01((gestureData.tagFloat / 2 + shoulderToHand.y) / gestureData.tagFloat); if(gestureData.tagVector2.x != 0 && gestureData.tagVector2.y != 0) { Vector3 relHandPos = handPos - gestureData.tagVector; gestureData.screenPos.x = Mathf.Clamp01(relHandPos.x / gestureData.tagVector2.x); gestureData.screenPos.y = Mathf.Clamp01(relHandPos.y / gestureData.tagVector2.y); } //Debug.Log(string.Format("{0} - S: {1}, H: {2}, SH: {3}, L : {4}", gestureData.gesture, shoulderPos, handPos, shoulderToHand, gestureData.tagFloat)); } } private static void SetZoomFactor(long userId, ref GestureData gestureData, float initialZoom, ref Vector3[] jointsPos, ref bool[] jointsTracked) { Vector3 vectorZooming = jointsPos[rightHandIndex] - jointsPos[leftHandIndex]; if(gestureData.tagFloat == 0f || gestureData.userId != userId) { gestureData.tagFloat = 0.5f; // this is 100% } float distZooming = vectorZooming.magnitude; gestureData.screenPos.z = initialZoom + (distZooming / gestureData.tagFloat); } private static void SetWheelRotation(long userId, ref GestureData gestureData, Vector3 initialPos, Vector3 currentPos) { float angle = Vector3.Angle(initialPos, currentPos) * Mathf.Sign(currentPos.y - initialPos.y); gestureData.screenPos.z = angle; } // estimate the next state and completeness of the gesture /// <summary> /// estimate the state and progress of the given gesture. /// </summary> /// <param name="userId">User ID</param> /// <param name="gestureData">Gesture-data structure</param> /// <param name="timestamp">Current time</param> /// <param name="jointsPos">Joints-position array</param> /// <param name="jointsTracked">Joints-tracked array</param> public static void CheckForGesture(long userId, ref GestureData gestureData, float timestamp, ref Vector3[] jointsPos, ref bool[] jointsTracked) { if(gestureData.complete) return; float bandSize = (jointsPos[shoulderCenterIndex].y - jointsPos[hipCenterIndex].y); float gestureTop = jointsPos[shoulderCenterIndex].y + bandSize * 1.2f / 3f; float gestureBottom = jointsPos[shoulderCenterIndex].y - bandSize * 1.8f / 3f; float gestureRight = jointsPos[rightHipIndex].x; float gestureLeft = jointsPos[leftHipIndex].x; switch(gestureData.gesture) { // check for RaiseRightHand case Gestures.RaiseRightHand: switch(gestureData.state) { case 0: // gesture detection if(jointsTracked[rightHandIndex] && jointsTracked[leftHandIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.1f && (jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) < 0f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); } break; case 1: // gesture complete bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[leftHandIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.1f && (jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) < 0f; Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectInterop.Constants.PoseCompleteDuration); break; } break; // check for RaiseLeftHand case Gestures.RaiseLeftHand: switch(gestureData.state) { case 0: // gesture detection if(jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.1f && (jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) < 0f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); } break; case 1: // gesture complete bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.1f && (jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) < 0f; Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectInterop.Constants.PoseCompleteDuration); break; } break; // check for Psi case Gestures.Psi: switch(gestureData.state) { case 0: // gesture detection if(jointsTracked[rightHandIndex] && jointsTracked[leftHandIndex] && jointsTracked[shoulderCenterIndex] && (jointsPos[rightHandIndex].y - jointsPos[shoulderCenterIndex].y) > 0.1f && (jointsPos[leftHandIndex].y - jointsPos[shoulderCenterIndex].y) > 0.1f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); } break; case 1: // gesture complete bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[leftHandIndex] && jointsTracked[shoulderCenterIndex] && (jointsPos[rightHandIndex].y - jointsPos[shoulderCenterIndex].y) > 0.1f && (jointsPos[leftHandIndex].y - jointsPos[shoulderCenterIndex].y) > 0.1f; Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectInterop.Constants.PoseCompleteDuration); break; } break; // check for Tpose case Gestures.Tpose: switch(gestureData.state) { case 0: // gesture detection if(jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[rightShoulderIndex] && Mathf.Abs(jointsPos[rightElbowIndex].y - jointsPos[rightShoulderIndex].y) < 0.1f && // 0.07f Mathf.Abs(jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) < 0.1f && // 0.7f jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[leftShoulderIndex] && Mathf.Abs(jointsPos[leftElbowIndex].y - jointsPos[leftShoulderIndex].y) < 0.1f && Mathf.Abs(jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) < 0.1f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); } break; case 1: // gesture complete bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[rightShoulderIndex] && Mathf.Abs(jointsPos[rightElbowIndex].y - jointsPos[rightShoulderIndex].y) < 0.1f && // 0.7f Mathf.Abs(jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) < 0.1f && // 0.7f jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[leftShoulderIndex] && Mathf.Abs(jointsPos[leftElbowIndex].y - jointsPos[leftShoulderIndex].y) < 0.1f && Mathf.Abs(jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) < 0.1f; Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectInterop.Constants.PoseCompleteDuration); break; } break; // check for Stop case Gestures.Stop: switch(gestureData.state) { case 0: // gesture detection if(jointsTracked[rightHandIndex] && jointsTracked[rightHipIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightHipIndex].y) < 0.2f && (jointsPos[rightHandIndex].x - jointsPos[rightHipIndex].x) >= 0.4f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); } else if(jointsTracked[leftHandIndex] && jointsTracked[leftHipIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftHipIndex].y) < 0.2f && (jointsPos[leftHandIndex].x - jointsPos[leftHipIndex].x) <= -0.4f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); } break; case 1: // gesture complete bool isInPose = (gestureData.joint == rightHandIndex) ? (jointsTracked[rightHandIndex] && jointsTracked[rightHipIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightHipIndex].y) < 0.2f && (jointsPos[rightHandIndex].x - jointsPos[rightHipIndex].x) >= 0.4f) : (jointsTracked[leftHandIndex] && jointsTracked[leftHipIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftHipIndex].y) < 0.2f && (jointsPos[leftHandIndex].x - jointsPos[leftHipIndex].x) <= -0.4f); Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectInterop.Constants.PoseCompleteDuration); break; } break; // check for Wave case Gestures.Wave: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > 0.1f && (jointsPos[rightHandIndex].x - jointsPos[rightElbowIndex].x) > 0.05f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.progress = 0.3f; } else if(jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > 0.1f && (jointsPos[leftHandIndex].x - jointsPos[leftElbowIndex].x) < -0.05f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); gestureData.progress = 0.3f; } break; case 1: // gesture - phase 2 if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = gestureData.joint == rightHandIndex ? jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > 0.1f && (jointsPos[rightHandIndex].x - jointsPos[rightElbowIndex].x) < -0.05f : jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > 0.1f && (jointsPos[leftHandIndex].x - jointsPos[leftElbowIndex].x) > 0.05f; if(isInPose) { gestureData.timestamp = timestamp; gestureData.state++; gestureData.progress = 0.7f; } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; case 2: // gesture phase 3 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = gestureData.joint == rightHandIndex ? jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && (jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > 0.1f && (jointsPos[rightHandIndex].x - jointsPos[rightElbowIndex].x) > 0.05f : jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && (jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > 0.1f && (jointsPos[leftHandIndex].x - jointsPos[leftElbowIndex].x) < -0.05f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // // check for Click // case Gestures.Click: // switch(gestureData.state) // { // case 0: // gesture detection - phase 1 // if(jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && // (jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f) // { // SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); // gestureData.progress = 0.3f; // // // set screen position at the start, because this is the most accurate click position // SetScreenPos(userId, ref gestureData, ref jointsPos, ref jointsTracked); // } // else if(jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && // (jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f) // { // SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); // gestureData.progress = 0.3f; // // // set screen position at the start, because this is the most accurate click position // SetScreenPos(userId, ref gestureData, ref jointsPos, ref jointsTracked); // } // break; // // case 1: // gesture - phase 2 //// if((timestamp - gestureData.timestamp) < 1.0f) //// { //// bool isInPose = gestureData.joint == rightHandIndex ? //// jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && //// //(jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f && //// Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.08f && //// (jointsPos[rightHandIndex].z - gestureData.jointPos.z) < -0.05f : //// jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && //// //(jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f && //// Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.08f && //// (jointsPos[leftHandIndex].z - gestureData.jointPos.z) < -0.05f; //// //// if(isInPose) //// { //// gestureData.timestamp = timestamp; //// gestureData.jointPos = jointsPos[gestureData.joint]; //// gestureData.state++; //// gestureData.progress = 0.7f; //// } //// else //// { //// // check for stay-in-place //// Vector3 distVector = jointsPos[gestureData.joint] - gestureData.jointPos; //// isInPose = distVector.magnitude < 0.05f; //// //// Vector3 jointPos = jointsPos[gestureData.joint]; //// CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, Constants.ClickStayDuration); //// } //// } //// else // { // // check for stay-in-place // Vector3 distVector = jointsPos[gestureData.joint] - gestureData.jointPos; // bool isInPose = distVector.magnitude < 0.05f; // // Vector3 jointPos = jointsPos[gestureData.joint]; // CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectInterop.Constants.ClickStayDuration); //// SetGestureCancelled(gestureData); // } // break; // //// case 2: // gesture phase 3 = complete //// if((timestamp - gestureData.timestamp) < 1.0f) //// { //// bool isInPose = gestureData.joint == rightHandIndex ? //// jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && //// //(jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f && //// Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.08f && //// (jointsPos[rightHandIndex].z - gestureData.jointPos.z) > 0.05f : //// jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && //// //(jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f && //// Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.08f && //// (jointsPos[leftHandIndex].z - gestureData.jointPos.z) > 0.05f; //// //// if(isInPose) //// { //// Vector3 jointPos = jointsPos[gestureData.joint]; //// CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); //// } //// } //// else //// { //// // cancel the gesture //// SetGestureCancelled(ref gestureData); //// } //// break; // } // break; // check for SwipeLeft case Gestures.SwipeLeft: switch(gestureData.state) { case 0: // gesture detection - phase 1 // if(jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && // (jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > -0.05f && // (jointsPos[rightHandIndex].x - jointsPos[rightElbowIndex].x) > 0f) // { // SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); // gestureData.progress = 0.5f; // } if(jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && jointsPos[rightHandIndex].x <= gestureRight && jointsPos[rightHandIndex].x > gestureLeft) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.progress = 0.1f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { // bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && // Mathf.Abs(jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) < 0.1f && // Mathf.Abs(jointsPos[rightHandIndex].y - gestureData.jointPos.y) < 0.08f && // (jointsPos[rightHandIndex].x - gestureData.jointPos.x) < -0.15f; // // if(isInPose) // { // Vector3 jointPos = jointsPos[gestureData.joint]; // CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); // } bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && jointsPos[rightHandIndex].x <= gestureLeft; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } else if(jointsPos[rightHandIndex].x <= gestureRight) { float gestureSize = gestureRight - gestureLeft; gestureData.progress = gestureSize > 0.01f ? (gestureRight - jointsPos[rightHandIndex].x) / gestureSize : 0f; } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for SwipeRight case Gestures.SwipeRight: switch(gestureData.state) { case 0: // gesture detection - phase 1 // if(jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && // (jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > -0.05f && // (jointsPos[leftHandIndex].x - jointsPos[leftElbowIndex].x) < 0f) // { // SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); // gestureData.progress = 0.5f; // } if(jointsTracked[leftHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[leftHandIndex].x >= gestureLeft && jointsPos[leftHandIndex].x < gestureRight) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); gestureData.progress = 0.1f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { // bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && // Mathf.Abs(jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) < 0.1f && // Mathf.Abs(jointsPos[leftHandIndex].y - gestureData.jointPos.y) < 0.08f && // (jointsPos[leftHandIndex].x - gestureData.jointPos.x) > 0.15f; // // if(isInPose) // { // Vector3 jointPos = jointsPos[gestureData.joint]; // CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); // } bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[leftHandIndex].x >= gestureRight; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } else if(jointsPos[leftHandIndex].x >= gestureLeft) { float gestureSize = gestureRight - gestureLeft; gestureData.progress = gestureSize > 0.01f ? (jointsPos[leftHandIndex].x - gestureLeft) / gestureSize : 0f; } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for SwipeUp case Gestures.SwipeUp: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) < -0.0f && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.15f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.progress = 0.5f; } else if(jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) < -0.0f && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.15f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = gestureData.joint == rightHandIndex ? jointsTracked[rightHandIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.05f && Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) <= 0.1f : jointsTracked[leftHandIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.05f && Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) <= 0.1f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for SwipeDown case Gestures.SwipeDown: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[rightHandIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftShoulderIndex].y) >= 0.05f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.progress = 0.5f; } else if(jointsTracked[leftHandIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightShoulderIndex].y) >= 0.05f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = gestureData.joint == rightHandIndex ? jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) < -0.15f && Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) <= 0.1f : jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) < -0.15f && Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) <= 0.1f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // // check for RightHandCursor // case Gestures.RightHandCursor: // switch(gestureData.state) // { // case 0: // gesture detection - phase 1 (perpetual) // if(jointsTracked[rightHandIndex] && jointsTracked[rightHipIndex] && // //(jointsPos[rightHandIndex].y - jointsPos[rightHipIndex].y) > -0.1f) // (jointsPos[rightHandIndex].y - jointsPos[hipCenterIndex].y) >= 0f) // { // gestureData.joint = rightHandIndex; // gestureData.timestamp = timestamp; // gestureData.jointPos = jointsPos[rightHandIndex]; // // SetScreenPos(userId, ref gestureData, ref jointsPos, ref jointsTracked); // gestureData.progress = 0.7f; // } // else // { // // cancel the gesture // //SetGestureCancelled(ref gestureData); // gestureData.progress = 0f; // } // break; // // } // break; // // // check for LeftHandCursor // case Gestures.LeftHandCursor: // switch(gestureData.state) // { // case 0: // gesture detection - phase 1 (perpetual) // if(jointsTracked[leftHandIndex] && jointsTracked[leftHipIndex] && // //(jointsPos[leftHandIndex].y - jointsPos[leftHipIndex].y) > -0.1f) // (jointsPos[leftHandIndex].y - jointsPos[hipCenterIndex].y) >= 0f) // { // gestureData.joint = leftHandIndex; // gestureData.timestamp = timestamp; // gestureData.jointPos = jointsPos[leftHandIndex]; // // SetScreenPos(userId, ref gestureData, ref jointsPos, ref jointsTracked); // gestureData.progress = 0.7f; // } // else // { // // cancel the gesture // //SetGestureCancelled(ref gestureData); // gestureData.progress = 0f; // } // break; // // } // break; // check for ZoomOut case Gestures.ZoomOut: Vector3 vectorZoomOut = (Vector3)jointsPos[rightHandIndex] - jointsPos[leftHandIndex]; float distZoomOut = vectorZoomOut.magnitude; switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && distZoomOut < 0.3f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.tagVector = Vector3.right; gestureData.tagFloat = 0f; gestureData.progress = 0.3f; } break; case 1: // gesture phase 2 = zooming if((timestamp - gestureData.timestamp) < 1.0f) { float angleZoomOut = Vector3.Angle(gestureData.tagVector, vectorZoomOut) * Mathf.Sign(vectorZoomOut.y - gestureData.tagVector.y); bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && distZoomOut < 1.5f && Mathf.Abs(angleZoomOut) < 20f; if(isInPose) { SetZoomFactor(userId, ref gestureData, 1.0f, ref jointsPos, ref jointsTracked); gestureData.timestamp = timestamp; gestureData.progress = 0.7f; } // else // { // // cancel the gesture // SetGestureCancelled(ref gestureData); // } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for ZoomIn case Gestures.ZoomIn: Vector3 vectorZoomIn = (Vector3)jointsPos[rightHandIndex] - jointsPos[leftHandIndex]; float distZoomIn = vectorZoomIn.magnitude; switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && distZoomIn >= 0.7f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.tagVector = Vector3.right; gestureData.tagFloat = distZoomIn; gestureData.progress = 0.3f; } break; case 1: // gesture phase 2 = zooming if((timestamp - gestureData.timestamp) < 1.0f) { float angleZoomIn = Vector3.Angle(gestureData.tagVector, vectorZoomIn) * Mathf.Sign(vectorZoomIn.y - gestureData.tagVector.y); bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && distZoomIn >= 0.2f && Mathf.Abs(angleZoomIn) < 20f; if(isInPose) { SetZoomFactor(userId, ref gestureData, 0.0f, ref jointsPos, ref jointsTracked); gestureData.timestamp = timestamp; gestureData.progress = 0.7f; } // else // { // // cancel the gesture // SetGestureCancelled(ref gestureData); // } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for Wheel case Gestures.Wheel: Vector3 vectorWheel = (Vector3)jointsPos[rightHandIndex] - jointsPos[leftHandIndex]; float distWheel = vectorWheel.magnitude; // Debug.Log(string.Format("{0}. Dist: {1:F1}, Tag: {2:F1}, Diff: {3:F1}", gestureData.state, // distWheel, gestureData.tagFloat, Mathf.Abs(distWheel - gestureData.tagFloat))); switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && distWheel >= 0.3f && distWheel < 0.7f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.tagVector = Vector3.right; gestureData.tagFloat = distWheel; gestureData.progress = 0.3f; } break; case 1: // gesture phase 2 = zooming if((timestamp - gestureData.timestamp) < 1.5f) { float angle = Vector3.Angle(gestureData.tagVector, vectorWheel) * Mathf.Sign(vectorWheel.y - gestureData.tagVector.y); bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] && jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop && jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop && distWheel >= 0.3f && distWheel < 0.7f && Mathf.Abs(distWheel - gestureData.tagFloat) < 0.1f; if(isInPose) { //SetWheelRotation(userId, ref gestureData, gestureData.tagVector, vectorWheel); gestureData.screenPos.z = angle; // wheel angle gestureData.timestamp = timestamp; gestureData.tagFloat = distWheel; gestureData.progress = 0.7f; } // else // { // // cancel the gesture // SetGestureCancelled(ref gestureData); // } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for Jump case Gestures.Jump: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[hipCenterIndex] && (jointsPos[hipCenterIndex].y > 0.6f) && (jointsPos[hipCenterIndex].y < 1.2f)) { SetGestureJoint(ref gestureData, timestamp, hipCenterIndex, jointsPos[hipCenterIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = jointsTracked[hipCenterIndex] && (jointsPos[hipCenterIndex].y - gestureData.jointPos.y) > 0.15f && Mathf.Abs(jointsPos[hipCenterIndex].x - gestureData.jointPos.x) < 0.2f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for Squat case Gestures.Squat: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[hipCenterIndex] && (jointsPos[hipCenterIndex].y <= 0.7f)) { SetGestureJoint(ref gestureData, timestamp, hipCenterIndex, jointsPos[hipCenterIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = jointsTracked[hipCenterIndex] && (jointsPos[hipCenterIndex].y - gestureData.jointPos.y) < -0.15f && Mathf.Abs(jointsPos[hipCenterIndex].x - gestureData.jointPos.x) < 0.2f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for Push case Gestures.Push: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[rightHandIndex].x - jointsPos[rightShoulderIndex].x) < 0.2f && (jointsPos[rightHandIndex].z - jointsPos[leftElbowIndex].z) < -0.2f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.progress = 0.5f; } else if(jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[leftHandIndex].x - jointsPos[leftShoulderIndex].x) < 0.2f && (jointsPos[leftHandIndex].z - jointsPos[rightElbowIndex].z) < -0.2f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = gestureData.joint == rightHandIndex ? jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.2f && (jointsPos[rightHandIndex].z - gestureData.jointPos.z) < -0.2f : jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.2f && (jointsPos[leftHandIndex].z - gestureData.jointPos.z) < -0.2f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for Pull case Gestures.Pull: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[rightHandIndex].x - jointsPos[rightShoulderIndex].x) < 0.2f && (jointsPos[rightHandIndex].z - jointsPos[leftElbowIndex].z) < -0.3f) { SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]); gestureData.progress = 0.5f; } else if(jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[leftHandIndex].x - jointsPos[leftShoulderIndex].x) < 0.2f && (jointsPos[leftHandIndex].z - jointsPos[rightElbowIndex].z) < -0.3f) { SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = gestureData.joint == rightHandIndex ? jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] && (jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.2f && (jointsPos[rightHandIndex].z - gestureData.jointPos.z) > 0.25f : jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] && (jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f && Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.2f && (jointsPos[leftHandIndex].z - gestureData.jointPos.z) > 0.25f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for LeanLeft case Gestures.LeanLeft: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[leftShoulderIndex] && jointsTracked[rightShoulderIndex] && jointsTracked[leftHipIndex] && (jointsPos[rightShoulderIndex].z - jointsPos[leftHipIndex].z) < 0f && (jointsPos[rightShoulderIndex].z - jointsPos[leftShoulderIndex].z) > -0.15f) { SetGestureJoint(ref gestureData, timestamp, rightShoulderIndex, jointsPos[rightShoulderIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = jointsTracked[leftShoulderIndex] && jointsTracked[rightShoulderIndex] && jointsTracked[leftHipIndex] && (jointsPos[rightShoulderIndex].z - jointsPos[leftShoulderIndex].z) < -0.2f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for LeanRight case Gestures.LeanRight: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[leftShoulderIndex] && jointsTracked[rightShoulderIndex] && jointsTracked[rightHipIndex] && (jointsPos[leftShoulderIndex].z - jointsPos[rightHipIndex].z) < 0f && (jointsPos[leftShoulderIndex].z - jointsPos[rightShoulderIndex].z) > -0.15f) { SetGestureJoint(ref gestureData, timestamp, leftShoulderIndex, jointsPos[leftShoulderIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = jointsTracked[leftShoulderIndex] && jointsTracked[rightShoulderIndex] && jointsTracked[rightHipIndex] && (jointsPos[leftShoulderIndex].z - jointsPos[rightShoulderIndex].z) < -0.2f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for KickLeft case Gestures.KickLeft: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[leftAnkleIndex] && jointsTracked[rightAnkleIndex] && jointsTracked[leftHipIndex] && (jointsPos[leftAnkleIndex].z - jointsPos[leftHipIndex].z) < 0f && (jointsPos[leftAnkleIndex].z - jointsPos[rightAnkleIndex].z) > -0.2f) { SetGestureJoint(ref gestureData, timestamp, leftAnkleIndex, jointsPos[leftAnkleIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = jointsTracked[leftAnkleIndex] && jointsTracked[rightAnkleIndex] && jointsTracked[leftHipIndex] && (jointsPos[leftAnkleIndex].z - jointsPos[rightAnkleIndex].z) < -0.4f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // check for KickRight case Gestures.KickRight: switch(gestureData.state) { case 0: // gesture detection - phase 1 if(jointsTracked[leftAnkleIndex] && jointsTracked[rightAnkleIndex] && jointsTracked[rightHipIndex] && (jointsPos[rightAnkleIndex].z - jointsPos[rightHipIndex].z) < 0f && (jointsPos[rightAnkleIndex].z - jointsPos[leftAnkleIndex].z) > -0.2f) { SetGestureJoint(ref gestureData, timestamp, rightAnkleIndex, jointsPos[rightAnkleIndex]); gestureData.progress = 0.5f; } break; case 1: // gesture phase 2 = complete if((timestamp - gestureData.timestamp) < 1.5f) { bool isInPose = jointsTracked[leftAnkleIndex] && jointsTracked[rightAnkleIndex] && jointsTracked[rightHipIndex] && (jointsPos[rightAnkleIndex].z - jointsPos[leftAnkleIndex].z) < -0.4f; if(isInPose) { Vector3 jointPos = jointsPos[gestureData.joint]; CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f); } } else { // cancel the gesture SetGestureCancelled(ref gestureData); } break; } break; // here come more gesture-cases } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="OrderReportModel.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2015 // </copyright> // <summary> // Defines the order report model class. // </summary> // -------------------------------------------------------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // 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. // ------------------------------------------------------------------------------------------- namespace Sitecore.Ecommerce.Report { using System; using System.Collections.Generic; using System.Linq; using Common; using Configurations; using Diagnostics; using OrderManagement.Orders; using Stimulsoft.Base.Design; /// <summary> /// Defines the order report model class. /// </summary> public class OrderReportModel { /// <summary> /// The company master data. /// </summary> private CompanyMasterData companyMasterData; /// <summary> /// Gets or sets the order. /// </summary> /// <value> /// The order. /// </value> [StiBrowsable(false)] [CanBeNull] public virtual Order Order { get; set; } /// <summary> /// Gets or sets the company master data. /// </summary> /// <value> /// The company master data. /// </value> [StiBrowsable(false)] [CanBeNull] public virtual CompanyMasterData CompanyMasterData { get { return this.companyMasterData ?? (this.companyMasterData = new CompanyMasterData()); } set { this.companyMasterData = value; } } /// <summary> /// Gets the language code. /// </summary> /// <value> /// The language code. /// </value> public virtual string LanguageCode { get { if (this.Order != null && (this.Order.BuyerCustomerParty != null) && (this.Order.BuyerCustomerParty.Party != null)) { return this.Order.BuyerCustomerParty.Party.LanguageCode; } return string.Empty; } } /// <summary> /// Gets the order id. /// </summary> /// <value>The order id.</value> [NotNull] public virtual string OrderId { get { if (this.Order != null) { return this.Order.OrderId; } return string.Empty; } } /// <summary> /// Gets the issue date. /// </summary> /// <value>The issue date.</value> public virtual DateTime IssueDate { get { if (this.Order != null) { return this.Order.IssueDate; } return DateTime.MinValue; } } /// <summary> /// Gets the name of the company. /// </summary> /// <value>The name of the company.</value> [NotNull] public virtual string CompanyName { get { if (this.CompanyMasterData != null) { return this.CompanyMasterData.CompanyName; } return string.Empty; } } /// <summary> /// Gets the company address. /// </summary> /// <value>The company address.</value> [NotNull] public virtual string CompanyAddress { get { if (this.CompanyMasterData != null) { return this.CompanyMasterData.Address; } return string.Empty; } } /// <summary> /// Gets the company city. /// </summary> /// <value>The company city.</value> [NotNull] public virtual string CompanyCity { get { if (this.CompanyMasterData != null) { return this.CompanyMasterData.City; } return string.Empty; } } /// <summary> /// Gets the company zip. /// </summary> /// <value>The company zip.</value> [NotNull] public virtual string CompanyZip { get { if (this.CompanyMasterData != null) { return this.CompanyMasterData.Zip; } return string.Empty; } } /// <summary> /// Gets the company country. /// </summary> /// <value>The company country.</value> [NotNull] public virtual string CompanyCountry { get { if (this.CompanyMasterData != null) { return this.CompanyMasterData.Country; } return string.Empty; } } /// <summary> /// Gets the company post box. /// </summary> /// <value>The company post box.</value> [NotNull] public virtual string CompanyPostBox { get { if (this.CompanyMasterData != null) { return this.CompanyMasterData.PostBox; } return string.Empty; } } /// <summary> /// Gets the company number. /// </summary> /// <value>The company number.</value> [NotNull] public virtual string CompanyNumber { get { if (this.CompanyMasterData != null) { return this.CompanyMasterData.CompanyNumber; } return string.Empty; } } /// <summary> /// Gets the company fax. /// </summary> /// <value>The company fax.</value> [NotNull] public virtual string CompanyFax { get { if (this.CompanyMasterData != null) { return this.CompanyMasterData.Fax; } return string.Empty; } } /// <summary> /// Gets the supplier party mail. /// </summary> /// <value>The supplier party mail.</value> [NotNull] public virtual string CompanyMail { get { if (this.CompanyMasterData != null) { return this.CompanyMasterData.Email; } return string.Empty; } } /// <summary> /// Gets the company website. /// </summary> /// <value>The company website.</value> [NotNull] public virtual string CompanyWebsite { get { if (this.CompanyMasterData != null) { return this.CompanyMasterData.Website; } return string.Empty; } } /// <summary> /// Gets the company logo URL. /// </summary> /// <value>The company logo URL.</value> [NotNull] public virtual string CompanyLogoUrl { get { if (this.CompanyMasterData != null) { return this.CompanyMasterData.LogoUrl; } return string.Empty; } } /// <summary> /// Gets the buyer party supplier assigned account id. /// </summary> /// <value>The buyer party supplier assigned account id.</value> [NotNull] public virtual string BuyerPartySupplierAssignedAccountId { get { if ((this.Order != null) && (this.Order.BuyerCustomerParty != null)) { return this.Order.BuyerCustomerParty.SupplierAssignedAccountID; } return string.Empty; } } /// <summary> /// Gets the name of the buyer party. /// </summary> /// <value>The name of the buyer party.</value> [NotNull] public virtual string BuyerPartyName { get { if ((this.Order != null) && (this.Order.BuyerCustomerParty != null) && (this.Order.BuyerCustomerParty.Party != null) && (this.Order.BuyerCustomerParty.Party.PartyName != null)) { return this.Order.BuyerCustomerParty.Party.PartyName; } return string.Empty; } } /// <summary> /// Gets the name of the buyer contact. /// </summary> /// <value> /// The name of the buyer contact. /// </value> [NotNull] public virtual string BuyerContactName { get { if ((this.Order != null) && (this.Order.BuyerCustomerParty != null) && (this.Order.BuyerCustomerParty.Party != null) && (this.Order.BuyerCustomerParty.Party.Contact != null) && (this.Order.BuyerCustomerParty.Party.Contact.Name != null)) { return this.Order.BuyerCustomerParty.Party.Contact.Name; } return string.Empty; } } /// <summary> /// Gets the name of the buyer party street. /// </summary> /// <value>The name of the buyer party street.</value> [NotNull] public virtual string BuyerPartyAddressLine { get { if ((this.Order != null) && (this.Order.BuyerCustomerParty != null) && (this.Order.BuyerCustomerParty.Party != null) && (this.Order.BuyerCustomerParty.Party.PostalAddress != null)) { return this.Order.BuyerCustomerParty.Party.PostalAddress.AddressLine; } return string.Empty; } } /// <summary> /// Gets the name of the buyer party street. /// </summary> /// <value> /// The name of the buyer party street. /// </value> [NotNull] public virtual string BuyerPartyStreetName { get { if ((this.Order != null) && (this.Order.BuyerCustomerParty != null) && (this.Order.BuyerCustomerParty.Party != null) && (this.Order.BuyerCustomerParty.Party.PostalAddress != null)) { return this.Order.BuyerCustomerParty.Party.PostalAddress.StreetName; } return string.Empty; } } /// <summary> /// Gets the name of the buyer party city. /// </summary> /// <value>The name of the buyer party city.</value> [NotNull] public virtual string BuyerPartyCityName { get { if ((this.Order != null) && (this.Order.BuyerCustomerParty != null) && (this.Order.BuyerCustomerParty.Party != null) && (this.Order.BuyerCustomerParty.Party.PostalAddress != null)) { return this.Order.BuyerCustomerParty.Party.PostalAddress.CityName; } return string.Empty; } } /// <summary> /// Gets the buyer party postal zone. /// </summary> /// <value>The buyer party postal zone.</value> [NotNull] public virtual string BuyerPartyPostalZone { get { if ((this.Order != null) && (this.Order.BuyerCustomerParty != null) && (this.Order.BuyerCustomerParty.Party != null) && (this.Order.BuyerCustomerParty.Party.PostalAddress != null)) { return this.Order.BuyerCustomerParty.Party.PostalAddress.PostalZone; } return string.Empty; } } /// <summary> /// Gets the buyer party country. /// </summary> /// <value>The buyer party country.</value> [NotNull] public virtual string BuyerPartyCountry { get { if ((this.Order != null) && (this.Order.BuyerCustomerParty != null) && (this.Order.BuyerCustomerParty.Party != null) && (this.Order.BuyerCustomerParty.Party.PostalAddress != null)) { return this.Order.BuyerCustomerParty.Party.PostalAddress.Country; } return string.Empty; } } /// <summary> /// Gets the buyer party telephone. /// </summary> /// <value>The buyer party telephone.</value> [NotNull] public virtual string BuyerPartyTelephone { get { if ((this.Order != null) && (this.Order.BuyerCustomerParty != null) && (this.Order.BuyerCustomerParty.Party != null) && (this.Order.BuyerCustomerParty.Party.Contact != null)) { return this.Order.BuyerCustomerParty.Party.Contact.Telephone; } return string.Empty; } } /// <summary> /// Gets the buyer party telephone. /// </summary> /// <value>The buyer party telephone.</value> [NotNull] public virtual string BuyerPartyTelefax { get { if ((this.Order != null) && (this.Order.BuyerCustomerParty != null) && (this.Order.BuyerCustomerParty.Party != null) && (this.Order.BuyerCustomerParty.Party.Contact != null)) { return this.Order.BuyerCustomerParty.Party.Contact.Telefax; } return string.Empty; } } /// <summary> /// Gets the buyer party mail. /// </summary> /// <value>The buyer party mail.</value> [NotNull] public virtual string BuyerPartyMail { get { if ((this.Order != null) && (this.Order.BuyerCustomerParty != null) && (this.Order.BuyerCustomerParty.Party != null) && (this.Order.BuyerCustomerParty.Party.Contact != null)) { return this.Order.BuyerCustomerParty.Party.Contact.ElectronicMail; } return string.Empty; } } /// <summary> /// Gets the buyer party note. /// </summary> /// <value>The buyer party note.</value> [NotNull] public virtual string BuyerPartyNote { get { if ((this.Order != null) && (this.Order.BuyerCustomerParty != null) && (this.Order.BuyerCustomerParty.Party != null) && (this.Order.BuyerCustomerParty.Party.Contact != null)) { return this.Order.BuyerCustomerParty.Party.Contact.Note; } return string.Empty; } } /// <summary> /// Gets the name of the delivery party. /// </summary> /// <value>The name of the delivery party.</value> [NotNull] public virtual string DeliveryPartyName { get { if ((this.Delivery != null) && (this.Delivery.DeliveryParty != null) && (this.Delivery.DeliveryParty.Contact != null)) { return this.Delivery.DeliveryParty.Contact.Name; } return string.Empty; } } /// <summary> /// Gets the name of the delivery party street. /// </summary> /// <value>The name of the delivery party street.</value> [NotNull] public virtual string DeliveryPartyAddressLine { get { if ((this.Delivery != null) && (this.Delivery.DeliveryParty != null) && (this.Delivery.DeliveryParty.PostalAddress != null)) { return this.Delivery.DeliveryParty.PostalAddress.AddressLine; } return string.Empty; } } /// <summary> /// Gets the name of the delivery party street. /// </summary> /// <value> /// The name of the delivery party street. /// </value> [NotNull] public virtual string DeliveryPartyStreetName { get { if ((this.Delivery != null) && (this.Delivery.DeliveryParty != null) && (this.Delivery.DeliveryParty.PostalAddress != null)) { return this.Delivery.DeliveryParty.PostalAddress.StreetName; } return string.Empty; } } /// <summary> /// Gets the name of the delivery party city. /// </summary> /// <value>The name of the delivery party city.</value> [NotNull] public virtual string DeliveryPartyCityName { get { if ((this.Delivery != null) && (this.Delivery.DeliveryParty != null) && (this.Delivery.DeliveryParty.PostalAddress != null)) { return this.Delivery.DeliveryParty.PostalAddress.CityName; } return string.Empty; } } /// <summary> /// Gets the delivery party postal zone. /// </summary> /// <value>The delivery party postal zone.</value> [NotNull] public virtual string DeliveryPartyPostalZone { get { if ((this.Delivery != null) && (this.Delivery.DeliveryParty != null) && (this.Delivery.DeliveryParty.PostalAddress != null)) { return this.Delivery.DeliveryParty.PostalAddress.PostalZone; } return string.Empty; } } /// <summary> /// Gets the delivery party country. /// </summary> /// <value>The delivery party country.</value> [NotNull] public virtual string DeliveryPartyCountry { get { if ((this.Delivery != null) && (this.Delivery.DeliveryParty != null) && (this.Delivery.DeliveryParty.PostalAddress != null)) { return this.Delivery.DeliveryParty.PostalAddress.Country; } return string.Empty; } } /// <summary> /// Gets the delivery party telephone. /// </summary> /// <value>The delivery party telephone.</value> [NotNull] public virtual string DeliveryPartyTelephone { get { if ((this.Delivery != null) && (this.Delivery.DeliveryParty != null) && (this.Delivery.DeliveryParty.Contact != null)) { return this.Delivery.DeliveryParty.Contact.Telephone; } return string.Empty; } } /// <summary> /// Gets the delivery party mail. /// </summary> /// <value>The delivery party mail.</value> [NotNull] public virtual string DeliveryPartyMail { get { if ((this.Delivery != null) && (this.Delivery.DeliveryParty != null) && (this.Delivery.DeliveryParty.Contact != null)) { return this.Delivery.DeliveryParty.Contact.ElectronicMail; } return string.Empty; } } /// <summary> /// Gets the delivery party note. /// </summary> /// <value>The delivery party note.</value> [NotNull] public virtual string DeliveryPartyNote { get { if ((this.Delivery != null) && (this.Delivery.DeliveryParty != null) && (this.Delivery.DeliveryParty.Contact != null)) { return this.Delivery.DeliveryParty.Contact.Note; } return string.Empty; } } /// <summary> /// Gets the order lines. /// </summary> /// <value>The order lines.</value> [NotNull] public virtual IEnumerable<OrderLineReportModel> OrderLines { get { if ((this.Order != null) && (this.Order.OrderLines != null)) { return this.Order.OrderLines.Select(orderLine => new OrderLineReportModel { OrderLine = orderLine }); } return Enumerable.Empty<OrderLineReportModel>(); } } /// <summary> /// Gets the anticipated monetary total tax exclusive amount. /// </summary> /// <value>The anticipated monetary total tax exclusive amount.</value> [NotNull] public virtual string AnticipatedMonetaryTotalTaxExclusiveAmount { get { if ((this.Order != null) && (this.Order.AnticipatedMonetaryTotal != null) && (this.Order.AnticipatedMonetaryTotal.TaxExclusiveAmount != null)) { return this.GetAmountRepresentation(this.Order.AnticipatedMonetaryTotal.TaxExclusiveAmount); } return string.Empty; } } /// <summary> /// Gets the anticipated monetary total tax inclusive amount. /// </summary> /// <value>The anticipated monetary total tax inclusive amount.</value> [NotNull] public virtual string AnticipatedMonetaryTotalTaxInclusiveAmount { get { if ((this.Order != null) && (this.Order.AnticipatedMonetaryTotal != null) && (this.Order.AnticipatedMonetaryTotal.TaxInclusiveAmount != null)) { return this.GetAmountRepresentation(this.Order.AnticipatedMonetaryTotal.TaxInclusiveAmount); } return string.Empty; } } /// <summary> /// Gets the aggregated allowance charges. /// </summary> /// <value>The aggregated allowance charges.</value> [NotNull] public virtual string AggregatedAllowanceCharges { get { if ((this.Order != null) && (this.Order.AllowanceCharge != null)) { Amount resultingAmount = null; foreach (AllowanceCharge allowanceCharge in this.Order.AllowanceCharge) { if (resultingAmount == null) { resultingAmount = allowanceCharge.Amount; } else { Assert.AreEqual(resultingAmount.CurrencyID, allowanceCharge.Amount.CurrencyID, "All allowance charge amounts must be of the same currency"); resultingAmount.Value += allowanceCharge.Amount.Value; } } if (resultingAmount != null) { return this.GetAmountRepresentation(resultingAmount); } } return string.Empty; } } /// <summary> /// Gets the aggregated tax percents. /// </summary> /// <value>The aggregated tax percents.</value> public virtual decimal AggregatedTaxPercents { get { if ((this.Order != null) && (this.Order.TaxTotal != null)) { return this.Order.TaxTotal.TaxSubtotal.Aggregate(0m, (result, taxSubtotal) => taxSubtotal.TaxCategory.Percent); } return 0; } } /// <summary> /// Gets the anticipated monetary total payable amount. /// </summary> public virtual string AnticipatedMonetaryTotalPayableAmount { get { if ((this.Order != null) && (this.Order.AnticipatedMonetaryTotal != null)) { return this.GetAmountRepresentation(this.Order.AnticipatedMonetaryTotal.PayableAmount); } return string.Empty; } } /// <summary> /// Gets the anticipated monetary total allowance total amount. /// </summary> /// <value>The anticipated monetary total allowance total amount.</value> [NotNull] public virtual string AnticipatedMonetaryTotalAllowanceTotalAmount { get { if ((this.Order != null) && (this.Order.AnticipatedMonetaryTotal != null)) { return this.GetAmountRepresentation(this.Order.AnticipatedMonetaryTotal.AllowanceTotalAmount); } return string.Empty; } } /// <summary> /// Gets the anticipated monetary total line extension amount. /// </summary> /// <value>The anticipated monetary total line extension amount.</value> [NotNull] public virtual string AnticipatedMonetaryTotalLineExtensionAmount { get { if ((this.Order != null) && (this.Order.AnticipatedMonetaryTotal != null)) { return this.GetAmountRepresentation(this.Order.AnticipatedMonetaryTotal.LineExtensionAmount); } return string.Empty; } } /// <summary> /// Gets the delivery tracking ID. /// </summary> /// <value>The delivery tracking ID.</value> [NotNull] public virtual string DeliveryTrackingID { get { if (this.Delivery != null) { return this.Delivery.TrackingID; } return string.Empty; } } /// <summary> /// Gets the delivery party website URI. /// </summary> /// <value>The delivery party website URI.</value> [NotNull] public virtual string DeliveryPartyWebsiteURI { get { if ((this.Delivery != null) && (this.Delivery.DeliveryParty != null)) { return this.Delivery.DeliveryParty.WebsiteURI; } return string.Empty; } } /// <summary> /// Gets the delivery. /// </summary> /// <value>The delivery.</value> [CanBeNull] protected virtual Delivery Delivery { get { if ((this.Order != null) && (this.Order.Delivery != null)) { return this.Order.Delivery.FirstOrDefault(); } return null; } } /// <summary> /// Gets the amount representation. /// </summary> /// <param name="amount">The amount.</param> /// <returns>The amount representation.</returns> [NotNull] protected virtual string GetAmountRepresentation([NotNull] Amount amount) { Assert.IsNotNull(amount, "amount"); return Ecommerce.Utils.MainUtil.FormatPrice(amount.Value, true, null, amount.CurrencyID); } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Logging; using Grpc.Core.Profiling; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Manages client side native call lifecycle. /// </summary> internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse>, IUnaryResponseClientCallback, IReceivedStatusOnClientCallback, IReceivedResponseHeadersCallback { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>(); readonly CallInvocationDetails<TRequest, TResponse> details; readonly INativeCall injectedNativeCall; // for testing bool registeredWithChannel; // Dispose of to de-register cancellation token registration IDisposable cancellationTokenRegistration; // Completion of a pending unary response if not null. TaskCompletionSource<TResponse> unaryResponseTcs; // Completion of a streaming response call if not null. TaskCompletionSource<object> streamingResponseCallFinishedTcs; // TODO(jtattermusch): this field could be lazy-initialized (only if someone requests the response headers). // Response headers set here once received. TaskCompletionSource<Metadata> responseHeadersTcs = new TaskCompletionSource<Metadata>(); // Set after status is received. Used for both unary and streaming response calls. ClientSideStatus? finishedStatus; public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails) : base(callDetails.RequestMarshaller.ContextualSerializer, callDetails.ResponseMarshaller.ContextualDeserializer) { this.details = callDetails.WithOptions(callDetails.Options.Normalize()); this.initialMetadataSent = true; // we always send metadata at the very beginning of the call. } /// <summary> /// This constructor should only be used for testing. /// </summary> public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails, INativeCall injectedNativeCall) : this(callDetails) { this.injectedNativeCall = injectedNativeCall; } // TODO: this method is not Async, so it shouldn't be in AsyncCall class, but // it is reusing fair amount of code in this class, so we are leaving it here. /// <summary> /// Blocking unary request - unary response call. /// </summary> public TResponse UnaryCall(TRequest msg) { var profiler = Profilers.ForCurrentThread(); using (profiler.NewScope("AsyncCall.UnaryCall")) using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.CreateSync()) { bool callStartedOk = false; try { unaryResponseTcs = new TaskCompletionSource<TResponse>(); lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(cq); halfcloseRequested = true; readingDone = true; } byte[] payload = UnsafeSerialize(msg); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { var ctx = details.Channel.Environment.BatchContextPool.Lease(); try { call.StartUnary(ctx, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); callStartedOk = true; var ev = cq.Pluck(ctx.Handle); bool success = (ev.success != 0); try { using (profiler.NewScope("AsyncCall.UnaryCall.HandleBatch")) { HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessage(), ctx.GetReceivedInitialMetadata()); } } catch (Exception e) { Logger.Error(e, "Exception occurred while invoking completion delegate."); } } finally { ctx.Recycle(); } } } finally { if (!callStartedOk) { lock (myLock) { OnFailedToStartCallLocked(); } } } // Once the blocking call returns, the result should be available synchronously. // Note that GetAwaiter().GetResult() doesn't wrap exceptions in AggregateException. return unaryResponseTcs.Task.GetAwaiter().GetResult(); } } /// <summary> /// Starts a unary request - unary response call. /// </summary> public Task<TResponse> UnaryCallAsync(TRequest msg) { lock (myLock) { bool callStartedOk = false; try { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); halfcloseRequested = true; readingDone = true; byte[] payload = UnsafeSerialize(msg); unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartUnary(UnaryResponseClientCallback, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); callStartedOk = true; } return unaryResponseTcs.Task; } finally { if (!callStartedOk) { OnFailedToStartCallLocked(); } } } } /// <summary> /// Starts a streamed request - unary response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public Task<TResponse> ClientStreamingCallAsync() { lock (myLock) { bool callStartedOk = false; try { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); readingDone = true; unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartClientStreaming(UnaryResponseClientCallback, metadataArray, details.Options.Flags); callStartedOk = true; } return unaryResponseTcs.Task; } finally { if (!callStartedOk) { OnFailedToStartCallLocked(); } } } } /// <summary> /// Starts a unary request - streamed response call. /// </summary> public void StartServerStreamingCall(TRequest msg) { lock (myLock) { bool callStartedOk = false; try { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); halfcloseRequested = true; byte[] payload = UnsafeSerialize(msg); streamingResponseCallFinishedTcs = new TaskCompletionSource<object>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartServerStreaming(ReceivedStatusOnClientCallback, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); callStartedOk = true; } call.StartReceiveInitialMetadata(ReceivedResponseHeadersCallback); } finally { if (!callStartedOk) { OnFailedToStartCallLocked(); } } } } /// <summary> /// Starts a streaming request - streaming response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public void StartDuplexStreamingCall() { lock (myLock) { bool callStartedOk = false; try { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); streamingResponseCallFinishedTcs = new TaskCompletionSource<object>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartDuplexStreaming(ReceivedStatusOnClientCallback, metadataArray, details.Options.Flags); callStartedOk = true; } call.StartReceiveInitialMetadata(ReceivedResponseHeadersCallback); } finally { if (!callStartedOk) { OnFailedToStartCallLocked(); } } } } /// <summary> /// Sends a streaming request. Only one pending send action is allowed at any given time. /// </summary> public Task SendMessageAsync(TRequest msg, WriteFlags writeFlags) { return SendMessageInternalAsync(msg, writeFlags); } /// <summary> /// Receives a streaming response. Only one pending read action is allowed at any given time. /// </summary> public Task<TResponse> ReadMessageAsync() { return ReadMessageInternalAsync(); } /// <summary> /// Sends halfclose, indicating client is done with streaming requests. /// Only one pending send action is allowed at any given time. /// </summary> public Task SendCloseFromClientAsync() { lock (myLock) { GrpcPreconditions.CheckState(started); var earlyResult = CheckSendPreconditionsClientSide(); if (earlyResult != null) { return earlyResult; } if (disposed || finished) { // In case the call has already been finished by the serverside, // the halfclose has already been done implicitly, so just return // completed task here. halfcloseRequested = true; return TaskUtils.CompletedTask; } call.StartSendCloseFromClient(SendCompletionCallback); halfcloseRequested = true; streamingWriteTcs = new TaskCompletionSource<object>(); return streamingWriteTcs.Task; } } /// <summary> /// Get the task that completes once if streaming response call finishes with ok status and throws RpcException with given status otherwise. /// </summary> public Task StreamingResponseCallFinishedTask { get { return streamingResponseCallFinishedTcs.Task; } } /// <summary> /// Get the task that completes once response headers are received. /// </summary> public Task<Metadata> ResponseHeadersAsync { get { return responseHeadersTcs.Task; } } /// <summary> /// Gets the resulting status if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Status GetStatus() { lock (myLock) { GrpcPreconditions.CheckState(finishedStatus.HasValue, "Status can only be accessed once the call has finished."); return finishedStatus.Value.Status; } } /// <summary> /// Gets the trailing metadata if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Metadata GetTrailers() { lock (myLock) { GrpcPreconditions.CheckState(finishedStatus.HasValue, "Trailers can only be accessed once the call has finished."); return finishedStatus.Value.Trailers; } } public CallInvocationDetails<TRequest, TResponse> Details { get { return this.details; } } protected override void OnAfterReleaseResourcesLocked() { if (registeredWithChannel) { details.Channel.RemoveCallReference(this); registeredWithChannel = false; } } protected override void OnAfterReleaseResourcesUnlocked() { // If cancellation callback is in progress, this can block // so we need to do this outside of call's lock to prevent // deadlock. // See https://github.com/grpc/grpc/issues/14777 // See https://github.com/dotnet/corefx/issues/14903 cancellationTokenRegistration?.Dispose(); } protected override bool IsClient { get { return true; } } protected override Exception GetRpcExceptionClientOnly() { return new RpcException(finishedStatus.Value.Status, finishedStatus.Value.Trailers); } protected override Task CheckSendAllowedOrEarlyResult() { var earlyResult = CheckSendPreconditionsClientSide(); if (earlyResult != null) { return earlyResult; } if (finishedStatus.HasValue) { // throwing RpcException if we already received status on client // side makes the most sense. // Note that this throws even for StatusCode.OK. // Writing after the call has finished is not a programming error because server can close // the call anytime, so don't throw directly, but let the write task finish with an error. var tcs = new TaskCompletionSource<object>(); tcs.SetException(new RpcException(finishedStatus.Value.Status, finishedStatus.Value.Trailers)); return tcs.Task; } return null; } private Task CheckSendPreconditionsClientSide() { GrpcPreconditions.CheckState(!halfcloseRequested, "Request stream has already been completed."); GrpcPreconditions.CheckState(streamingWriteTcs == null, "Only one write can be pending at a time."); if (cancelRequested) { // Return a cancelled task. var tcs = new TaskCompletionSource<object>(); tcs.SetCanceled(); return tcs.Task; } return null; } private void Initialize(CompletionQueueSafeHandle cq) { var call = CreateNativeCall(cq); details.Channel.AddCallReference(this); registeredWithChannel = true; InitializeInternal(call); RegisterCancellationCallback(); } private void OnFailedToStartCallLocked() { ReleaseResources(); // We need to execute the hook that disposes the cancellation token // registration, but it cannot be done from under a lock. // To make things simple, we just schedule the unregistering // on a threadpool. // - Once the native call is disposed, the Cancel() calls are ignored anyway // - We don't care about the overhead as OnFailedToStartCallLocked() only happens // when something goes very bad when initializing a call and that should // never happen when gRPC is used correctly. ThreadPool.QueueUserWorkItem((state) => OnAfterReleaseResourcesUnlocked()); } private INativeCall CreateNativeCall(CompletionQueueSafeHandle cq) { if (injectedNativeCall != null) { return injectedNativeCall; // allows injecting a mock INativeCall in tests. } var parentCall = details.Options.PropagationToken.AsImplOrNull()?.ParentCall ?? CallSafeHandle.NullInstance; var credentials = details.Options.Credentials; using (var nativeCredentials = credentials != null ? credentials.ToNativeCredentials() : null) { var result = details.Channel.Handle.CreateCall( parentCall, ContextPropagationTokenImpl.DefaultMask, cq, details.Method, details.Host, Timespec.FromDateTime(details.Options.Deadline.Value), nativeCredentials); return result; } } // Make sure that once cancellationToken for this call is cancelled, Cancel() will be called. private void RegisterCancellationCallback() { var token = details.Options.CancellationToken; if (token.CanBeCanceled) { cancellationTokenRegistration = token.Register(() => this.Cancel()); } } /// <summary> /// Gets WriteFlags set in callDetails.Options.WriteOptions /// </summary> private WriteFlags GetWriteFlagsForCall() { var writeOptions = details.Options.WriteOptions; return writeOptions != null ? writeOptions.Flags : default(WriteFlags); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleReceivedResponseHeaders(bool success, Metadata responseHeaders) { // TODO(jtattermusch): handle success==false responseHeadersTcs.SetResult(responseHeaders); } /// <summary> /// Handler for unary response completion. /// </summary> private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders) { // NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT, // success will be always set to true. TaskCompletionSource<object> delayedStreamingWriteTcs = null; TResponse msg = default(TResponse); var deserializeException = TryDeserialize(receivedMessage, out msg); bool releasedResources; lock (myLock) { finished = true; if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK) { receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers); } finishedStatus = receivedStatus; if (isStreamingWriteCompletionDelayed) { delayedStreamingWriteTcs = streamingWriteTcs; streamingWriteTcs = null; } releasedResources = ReleaseResourcesIfPossible(); } if (releasedResources) { OnAfterReleaseResourcesUnlocked(); } responseHeadersTcs.SetResult(responseHeaders); if (delayedStreamingWriteTcs != null) { delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly()); } var status = receivedStatus.Status; if (status.StatusCode != StatusCode.OK) { unaryResponseTcs.SetException(new RpcException(status, receivedStatus.Trailers)); return; } unaryResponseTcs.SetResult(msg); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleFinished(bool success, ClientSideStatus receivedStatus) { // NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT, // success will be always set to true. TaskCompletionSource<object> delayedStreamingWriteTcs = null; bool releasedResources; lock (myLock) { finished = true; finishedStatus = receivedStatus; if (isStreamingWriteCompletionDelayed) { delayedStreamingWriteTcs = streamingWriteTcs; streamingWriteTcs = null; } releasedResources = ReleaseResourcesIfPossible(); } if (releasedResources) { OnAfterReleaseResourcesUnlocked(); } if (delayedStreamingWriteTcs != null) { delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly()); } var status = receivedStatus.Status; if (status.StatusCode != StatusCode.OK) { streamingResponseCallFinishedTcs.SetException(new RpcException(status, receivedStatus.Trailers)); return; } streamingResponseCallFinishedTcs.SetResult(null); } IUnaryResponseClientCallback UnaryResponseClientCallback => this; void IUnaryResponseClientCallback.OnUnaryResponseClient(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders) { HandleUnaryResponse(success, receivedStatus, receivedMessage, responseHeaders); } IReceivedStatusOnClientCallback ReceivedStatusOnClientCallback => this; void IReceivedStatusOnClientCallback.OnReceivedStatusOnClient(bool success, ClientSideStatus receivedStatus) { HandleFinished(success, receivedStatus); } IReceivedResponseHeadersCallback ReceivedResponseHeadersCallback => this; void IReceivedResponseHeadersCallback.OnReceivedResponseHeaders(bool success, Metadata responseHeaders) { HandleReceivedResponseHeaders(success, responseHeaders); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Diagnostics; using System.Collections; using System.Collections.Generic; namespace System.Collections.Concurrent { // Abstract base for a thread-safe dictionary mapping a set of keys (K) to values (V). // // To create an actual dictionary, subclass this type and override the protected Factory method // to instantiate values (V) for the "Add" case. // // The key must be of a type that implements IEquatable<K>. The unifier calls IEquality<K>.Equals() // and Object.GetHashCode() on the keys. // // Deadlock risks: // - Keys may be tested for equality and asked to compute their hashcode while the unifier // holds its lock. Thus these operations must be written carefully to avoid deadlocks and // reentrancy in to the table. // // - The Factory method will never be called inside the unifier lock. If two threads race to // enter a value for the same key, the Factory() may get invoked twice for the same key - one // of them will "win" the race and its result entered into the dictionary - other gets thrown away. // // Notes: // - This class is used to look up types when GetType() or typeof() is invoked. // That means that this class itself cannot do or call anything that does these // things. // // - For this reason, it chooses not to mimic the official ConcurrentDictionary class // (I don't even want to risk using delegates.) Even the LowLevel versions of these // general utility classes may not be low-level enough for this class's purpose. // // Thread safety guarantees: // // ConcurrentUnifier is fully thread-safe and requires no // additional locking to be done by callers. // // Performance characteristics: // // ConcurrentUnifier will not block a reader, even while // the table is being written. Only one writer is allowed at a time; // ConcurrentUnifier handles the synchronization that ensures this. // // Safety for concurrent readers is ensured as follows: // // Each hash bucket is maintained as a stack. Inserts are done under // a lock; the entry is filled out completely, then "published" by a // single write to the top of the bucket. This ensures that a reader // will see a valid snapshot of the bucket, once it has read the head. // // On resize, we allocate an entirely new table, rather than resizing // in place. We fill in the new table completely, under the lock, // then "publish" it with a single write. Any reader that races with // this will either see the old table or the new one; each will contain // the same data. // internal abstract class ConcurrentUnifier<K, V> where K : IEquatable<K> where V : class { protected ConcurrentUnifier() { _lock = new Lock(); _container = new Container(this); } // // Retrieve the *unique* value for a given key. If the key was previously not entered into the dictionary, // this method invokes the overridable Factory() method to create the new value. The Factory() method is // invoked outside of any locks. If two threads race to enter a value for the same key, the Factory() // may get invoked twice for the same key - one of them will "win" the race and its result entered into the // dictionary - other gets thrown away. // public V GetOrAdd(K key) { Debug.Assert(key != null); Debug.Assert(!_lock.IsAcquired, "GetOrAdd called while lock already acquired. A possible cause of this is an Equals or GetHashCode method that causes reentrancy in the table."); int hashCode = key.GetHashCode(); V value; bool found = _container.TryGetValue(key, hashCode, out value); #if DEBUG { V checkedValue; bool checkedFound; // In debug builds, always exercise a locked TryGet (this is a good way to detect deadlock/reentrancy through Equals/GetHashCode()). using (LockHolder.Hold(_lock)) { _container.VerifyUnifierConsistency(); int h = key.GetHashCode(); checkedFound = _container.TryGetValue(key, h, out checkedValue); } if (found) { // State of a key must never go from found to not found, and only one value may exist per key. Debug.Assert(checkedFound); if (default(V) == null) // No good way to do the "only one value" check for value types. Debug.Assert(object.ReferenceEquals(checkedValue, value)); } } #endif //DEBUG if (found) return value; value = this.Factory(key); using (LockHolder.Hold(_lock)) { V heyIWasHereFirst; if (_container.TryGetValue(key, hashCode, out heyIWasHereFirst)) return heyIWasHereFirst; if (!_container.HasCapacity) _container.Resize(); // This overwrites the _container field. _container.Add(key, hashCode, value); return value; } } protected abstract V Factory(K key); private volatile Container _container; private readonly Lock _lock; private sealed class Container { public Container(ConcurrentUnifier<K, V> owner) { // Note: This could be done by calling Resize()'s logic but we cannot safely do that as this code path is reached // during class construction time and Resize() pulls in enough stuff that we get cyclic cctor warnings from the build. _buckets = new int[_initialCapacity]; for (int i = 0; i < _initialCapacity; i++) _buckets[i] = -1; _entries = new Entry[_initialCapacity]; _nextFreeEntry = 0; _owner = owner; } private Container(ConcurrentUnifier<K, V> owner, int[] buckets, Entry[] entries, int nextFreeEntry) { _buckets = buckets; _entries = entries; _nextFreeEntry = nextFreeEntry; _owner = owner; } public bool TryGetValue(K key, int hashCode, out V value) { // Lock acquistion NOT required (but lock inacquisition NOT guaranteed either.) int bucket = ComputeBucket(hashCode, _buckets.Length); int i = Volatile.Read(ref _buckets[bucket]); while (i != -1) { if (key.Equals(_entries[i]._key)) { value = _entries[i]._value; return true; } i = _entries[i]._next; } value = default(V); return false; } public void Add(K key, int hashCode, V value) { Debug.Assert(_owner._lock.IsAcquired); int bucket = ComputeBucket(hashCode, _buckets.Length); int newEntryIdx = _nextFreeEntry; _entries[newEntryIdx]._key = key; _entries[newEntryIdx]._value = value; _entries[newEntryIdx]._hashCode = hashCode; _entries[newEntryIdx]._next = _buckets[bucket]; _nextFreeEntry++; // The line that atomically adds the new key/value pair. If the thread is killed before this line executes but after // we've incremented _nextFreeEntry, this entry is harmlessly leaked until the next resize. Volatile.Write(ref _buckets[bucket], newEntryIdx); VerifyUnifierConsistency(); } public bool HasCapacity { get { Debug.Assert(_owner._lock.IsAcquired); return _nextFreeEntry != _entries.Length; } } public void Resize() { Debug.Assert(_owner._lock.IsAcquired); int newSize = HashHelpers.GetPrime(_buckets.Length * 2); #if DEBUG newSize = _buckets.Length + 3; #endif if (newSize <= _nextFreeEntry) throw new OutOfMemoryException(); Entry[] newEntries = new Entry[newSize]; int[] newBuckets = new int[newSize]; for (int i = 0; i < newSize; i++) newBuckets[i] = -1; // Note that we walk the bucket chains rather than iterating over _entries. This is because we allow for the possibility // of abandoned entries (with undefined contents) if a thread is killed between allocating an entry and linking it onto the // bucket chain. int newNextFreeEntry = 0; for (int bucket = 0; bucket < _buckets.Length; bucket++) { for (int entry = _buckets[bucket]; entry != -1; entry = _entries[entry]._next) { newEntries[newNextFreeEntry]._key = _entries[entry]._key; newEntries[newNextFreeEntry]._value = _entries[entry]._value; newEntries[newNextFreeEntry]._hashCode = _entries[entry]._hashCode; int newBucket = ComputeBucket(newEntries[newNextFreeEntry]._hashCode, newSize); newEntries[newNextFreeEntry]._next = newBuckets[newBucket]; newBuckets[newBucket] = newNextFreeEntry; newNextFreeEntry++; } } // The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if // a thread died between the time between we allocated the entry and the time we link it into the bucket stack. Debug.Assert(newNextFreeEntry <= _nextFreeEntry); // The line that atomically installs the resize. If this thread is killed before this point, // the table remains full and the next guy attempting an add will have to redo the resize. _owner._container = new Container(_owner, newBuckets, newEntries, newNextFreeEntry); _owner._container.VerifyUnifierConsistency(); } private static int ComputeBucket(int hashCode, int numBuckets) { int bucket = (hashCode & 0x7fffffff) % numBuckets; return bucket; } [Conditional("DEBUG")] public void VerifyUnifierConsistency() { #if DEBUG // There's a point at which this check becomes gluttonous, even by checked build standards... if (_nextFreeEntry >= 5000 && (0 != (_nextFreeEntry % 100))) return; Debug.Assert(_owner._lock.IsAcquired); Debug.Assert(_nextFreeEntry >= 0 && _nextFreeEntry <= _entries.Length); int numEntriesEncountered = 0; for (int bucket = 0; bucket < _buckets.Length; bucket++) { int walk1 = _buckets[bucket]; int walk2 = _buckets[bucket]; // walk2 advances two elements at a time - if walk1 ever meets walk2, we've detected a cycle. while (walk1 != -1) { numEntriesEncountered++; Debug.Assert(walk1 >= 0 && walk1 < _nextFreeEntry); Debug.Assert(walk2 >= -1 && walk2 < _nextFreeEntry); Debug.Assert(_entries[walk1]._key != null); int hashCode = _entries[walk1]._key.GetHashCode(); Debug.Assert(hashCode == _entries[walk1]._hashCode); int storedBucket = ComputeBucket(_entries[walk1]._hashCode, _buckets.Length); Debug.Assert(storedBucket == bucket); walk1 = _entries[walk1]._next; if (walk2 != -1) walk2 = _entries[walk2]._next; if (walk2 != -1) walk2 = _entries[walk2]._next; if (walk1 == walk2 && walk2 != -1) Debug.Fail("Bucket " + bucket + " has a cycle in its linked list."); } } // The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if // a thread died between the time between we allocated the entry and the time we link it into the bucket stack. Debug.Assert(numEntriesEncountered <= _nextFreeEntry); #endif //DEBUG } private readonly int[] _buckets; private readonly Entry[] _entries; private int _nextFreeEntry; private readonly ConcurrentUnifier<K, V> _owner; private const int _initialCapacity = 5; } private struct Entry { public K _key; public V _value; public int _hashCode; public int _next; } } }
//------------------------------------------------------------------------------ // // <copyright file="HostVisual.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // Host visual. // //------------------------------------------------------------------------------ namespace System.Windows.Media { using System; using System.Windows.Threading; using System.Windows.Media; using System.Windows.Media.Composition; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using MS.Internal; using System.Resources; using System.Runtime.InteropServices; using MS.Win32; using System.Threading; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; /// <summary> /// Host visual. /// </summary> public class HostVisual : ContainerVisual { //---------------------------------------------------------------------- // // Constructors // //---------------------------------------------------------------------- #region Constructors /// <summary> /// /// </summary> public HostVisual() { } #endregion Constructors //---------------------------------------------------------------------- // // Protected Methods // //---------------------------------------------------------------------- #region Protected Methods /// <summary> /// HitTestCore /// </summary> protected override HitTestResult HitTestCore( PointHitTestParameters hitTestParameters) { // // HostVisual never reports itself as being hit. To change this // behavior clients should derive from HostVisual and override // HitTestCore methods. // return null; } /// <summary> /// HitTestCore /// </summary> protected override GeometryHitTestResult HitTestCore( GeometryHitTestParameters hitTestParameters) { // // HostVisual never reports itself as being hit. To change this // behavior clients should derive from HostVisual and override // HitTestCore methods. // return null; } #endregion Protected Methods //---------------------------------------------------------------------- // // Internal Methods // //---------------------------------------------------------------------- #region Internal Methods /// <summary> /// /// </summary> internal override Rect GetContentBounds() { return Rect.Empty; } /// <summary> /// /// </summary> internal override void RenderContent(RenderContext ctx, bool isOnChannel) { // // Make sure that the visual target is properly hosted. // EnsureHostedVisualConnected(ctx.Channel); } /// <summary> /// /// </summary> internal override void FreeContent(DUCE.Channel channel) { // // Disconnect hosted visual from this channel. // using (CompositionEngineLock.Acquire()) { DisconnectHostedVisual( channel, /* removeChannelFromCollection */ true); } base.FreeContent(channel); } /// <summary> /// /// </summary> internal void BeginHosting(VisualTarget target) { // // This method is executed on the visual target thread. // Debug.Assert(target != null); Debug.Assert(target.Dispatcher.Thread == Thread.CurrentThread); using (CompositionEngineLock.Acquire()) { // // Check if another target is already hosted by this // visual and throw exception if this is the case. // if (_target != null) { throw new InvalidOperationException( SR.Get(SRID.VisualTarget_AnotherTargetAlreadyConnected) ); } _target = target; // // If HostVisual and VisualTarget on same thread, then call Invalidate // directly. Otherwise post invalidate message to the host visual thread // indicating that content update is required. // if (this.CheckAccess()) { Invalidate(); } else { Dispatcher.BeginInvoke( DispatcherPriority.Normal, (DispatcherOperationCallback)delegate(object args) { Invalidate(); return null; }, null ); } } } /// <summary> /// /// </summary> internal void EndHosting() { // // This method is executed on the visual target thread. // using (CompositionEngineLock.Acquire()) { Debug.Assert(_target != null); Debug.Assert(_target.Dispatcher.Thread == Thread.CurrentThread); DisconnectHostedVisualOnAllChannels(); _target = null; } } /// <summary> /// Should be called from the VisualTarget thread /// when it is safe to access the composition node /// and out of band channel from the VisualTarget thread /// to allow for the handle duplication/channel commit /// </summary> internal object DoHandleDuplication(object channel) { DUCE.ResourceHandle targetsHandle = DUCE.ResourceHandle.Null; using (CompositionEngineLock.Acquire()) { targetsHandle = _target._contentRoot.DuplicateHandle(_target.OutOfBandChannel, (DUCE.Channel)channel); Debug.Assert(!targetsHandle.IsNull); _target.OutOfBandChannel.CloseBatch(); _target.OutOfBandChannel.Commit(); } return targetsHandle; } #endregion Internal Methods //---------------------------------------------------------------------- // // Private Methods // //---------------------------------------------------------------------- #region Private Methods /// <summary> /// Connects the hosted visual on a channel if necessary. /// </summary> private void EnsureHostedVisualConnected(DUCE.Channel channel) { // // Conditions for connecting VisualTarget to Host Visual:- // 1. The channel on which we are rendering should not be synchronous. This // scenario is not supported currently. // 2. VisualTarget should not be null. // 3. They should not be already connected. // if (!(channel.IsSynchronous) && _target != null && !_connectedChannels.Contains(channel)) { Debug.Assert(IsOnChannel(channel)); DUCE.ResourceHandle targetsHandle = DUCE.ResourceHandle.Null; bool doDuplication = true; // // If HostVisual and VisualTarget are on same thread, then we just addref // VisualTarget. Otherwise, if on different threads, then we duplicate // VisualTarget onto Hostvisual's channel. // if (_target.CheckAccess()) { Debug.Assert(_target._contentRoot.IsOnChannel(channel)); Debug.Assert(_target.OutOfBandChannel == MediaContext.CurrentMediaContext.OutOfBandChannel); bool created = _target._contentRoot.CreateOrAddRefOnChannel(this, channel, VisualTarget.s_contentRootType); Debug.Assert(!created); targetsHandle = _target._contentRoot.GetHandle(channel); } else { // // Duplicate the target's handle onto our channel. // // We must wait synchronously for the _targets Dispatcher to call // back and do handle duplication. We can't do handle duplication // on this thread because access to the _target CompositionNode // is not synchronized. If we duplicated here, we could potentially // corrupt the _target OutOfBandChannel or the CompositionNode // MultiChannelResource. We have to wait synchronously because // we need the resulting duplicated handle to hook up as a child // to this HostVisual. // object returnValue = _target.Dispatcher.Invoke( DispatcherPriority.Normal, TimeSpan.FromMilliseconds(1000), new DispatcherOperationCallback(DoHandleDuplication), channel ); // // Duplication and flush is complete, we can resume processing // Only if the Invoke succeeded will we have a handle returned. // if (returnValue != null) { targetsHandle = (DUCE.ResourceHandle)returnValue; } else { // The Invoke didn't complete doDuplication = false; } } if (doDuplication) { if (!targetsHandle.IsNull) { using (CompositionEngineLock.Acquire()) { DUCE.CompositionNode.InsertChildAt( _proxy.GetHandle(channel), targetsHandle, 0, channel); } _connectedChannels.Add(channel); // // Indicate that that content composition root has been // connected, this needs to be taken into account to // properly manage children of this visual. // SetFlags(channel, true, VisualProxyFlags.IsContentNodeConnected); } } else { // // We didn't get a handle, because _target belongs to a // different thread, and the Invoke operation failed. We can't do // anything except try again in the next render pass. We can't // call Invalidate during the render pass because it pushes up // flags that are being modified within the render pass, so get // the local Dispatcher to do it for us later. // Dispatcher.BeginInvoke( DispatcherPriority.Normal, (DispatcherOperationCallback)delegate(object args) { Invalidate(); return null; }, null ); } } } /// <summary> /// Disconnects the hosted visual on all channels we have /// connected it to. /// </summary> private void DisconnectHostedVisualOnAllChannels() { foreach (DUCE.Channel channel in _connectedChannels) { DisconnectHostedVisual( channel, /* removeChannelFromCollection */ false); } _connectedChannels.Clear(); } /// <summary> /// Disconnects the hosted visual on a channel. /// </summary> private void DisconnectHostedVisual( DUCE.Channel channel, bool removeChannelFromCollection) { if (_target != null && _connectedChannels.Contains(channel)) { DUCE.CompositionNode.RemoveChild( _proxy.GetHandle(channel), _target._contentRoot.GetHandle(channel), channel ); // // Release the targets handle. If we had duplicated the handle, // then this removes the duplicated handle, otherwise just decrease // the ref count for VisualTarget. // _target._contentRoot.ReleaseOnChannel(channel); SetFlags(channel, false, VisualProxyFlags.IsContentNodeConnected); if (removeChannelFromCollection) { _connectedChannels.Remove(channel); } } } /// <summary> /// Invalidate this visual. /// </summary> private void Invalidate() { SetFlagsOnAllChannels(true, VisualProxyFlags.IsContentDirty); PropagateChangedFlags(); } #endregion Private Methods //---------------------------------------------------------------------- // // Private Fields // //---------------------------------------------------------------------- #region Private Fields /// <summary> /// The hosted visual target. /// </summary> /// <remarks> /// This field is free-threaded and should be accessed from under a lock. /// </remarks> private VisualTarget _target; /// <summary> /// The channels we have marshalled the visual target composition root. /// </summary> /// <remarks> /// This field is free-threaded and should be accessed from under a lock. /// </remarks> private List<DUCE.Channel> _connectedChannels = new List<DUCE.Channel>(); #endregion Private Fields } }
using LiveSplit.Options; using System; using System.Linq; using System.Collections.Generic; namespace LiveSplit.Model.Comparisons { public class PercentileComparisonGenerator : IComparisonGenerator { public IRun Run { get; set; } public const string ComparisonName = "Balanced PB"; public const string ShortComparisonName = "Balanced"; public string Name { get { return ComparisonName; } } public const double Weight = 0.93333; public PercentileComparisonGenerator(IRun run) { Run = run; } protected double GetWeight(int index, int count) { return Math.Pow(Weight, count - index - 1); } protected double ReWeight(double a, double b, double c) { return (a - b) / c; } protected TimeSpan Calculate(double perc, TimeSpan Value1, double Key1, TimeSpan Value2, double Key2) { var percDn = (Key1 - perc) * Value2.Ticks / (Key1 - Key2); var percUp = (perc - Key2) * Value1.Ticks / (Key1 - Key2); return TimeSpan.FromTicks(Convert.ToInt64(percUp + percDn)); } public void Generate(TimingMethod method) { var allHistory = new List<List<IndexedTimeSpan>>(); foreach (var segment in Run) allHistory.Add(new List<IndexedTimeSpan>()); foreach (var attempt in Run.AttemptHistory) { var ind = attempt.Index; var historyStartingIndex = -1; foreach (var segment in Run) { var currentIndex = Run.IndexOf(segment); IIndexedTime history = segment.SegmentHistory.FirstOrDefault(x => x.Index == ind); if (history != null) { if (history.Time[method] != null) { allHistory[Run.IndexOf(segment)].Add(new IndexedTimeSpan(history.Time[method].Value, historyStartingIndex)); historyStartingIndex = currentIndex; } } else historyStartingIndex = currentIndex; } } var weightedLists = new List<List<KeyValuePair<double, TimeSpan>>>(); var overallStartingIndex = -1; foreach (var currentList in allHistory) { var nullSegment = false; var curIndex = allHistory.IndexOf(currentList); var curPBTime = Run[curIndex].PersonalBestSplitTime[method]; var previousPBTime = overallStartingIndex >= 0 ? Run[overallStartingIndex].PersonalBestSplitTime[method] : null; var finalList = new List<TimeSpan>(); var matchingSegmentHistory = currentList.Where(x => x.Index == overallStartingIndex); if (matchingSegmentHistory.Count() > 0) { finalList = matchingSegmentHistory.Select(x => x.Time).ToList(); overallStartingIndex = curIndex; } else if (curPBTime != null && previousPBTime != null) { finalList.Add(curPBTime.Value - previousPBTime.Value); overallStartingIndex = curIndex; } else { nullSegment = true; } if (!nullSegment) { var tempList = finalList.Select((x, i) => new KeyValuePair<double, TimeSpan>(GetWeight(i, finalList.Count), x)).ToList(); var weightedList = new List<KeyValuePair<double, TimeSpan>>(); if (tempList.Count > 1) { tempList = tempList.OrderBy(x => x.Value).ToList(); var totalWeight = tempList.Aggregate(0.0, (s, x) => (s + x.Key)); var smallestWeight = tempList[0].Key; var rangeWeight = totalWeight - smallestWeight; var aggWeight = 0.0; foreach (var value in tempList) { aggWeight += value.Key; weightedList.Add(new KeyValuePair<double, TimeSpan>(ReWeight(aggWeight, smallestWeight, rangeWeight), value.Value)); } weightedList = weightedList.OrderBy(x => x.Value).ToList(); } else weightedList.Add(new KeyValuePair<double, TimeSpan>(1.0, tempList[0].Value)); weightedLists.Add(weightedList); } else weightedLists.Add(null); } TimeSpan? goalTime = null; if (Run[Run.Count - 1].PersonalBestSplitTime[method].HasValue) goalTime = Run[Run.Count - 1].PersonalBestSplitTime[method].Value; var runSum = TimeSpan.Zero; var outputSplits = new List<TimeSpan>(); var percentile = 0.5; var percMax = 1.0; var percMin = 0.0; var loopProtection = 0; do { runSum = TimeSpan.Zero; outputSplits.Clear(); percentile = 0.5 * (percMax - percMin) + percMin; foreach (var weightedList in weightedLists) { if (weightedList != null) { var curValue = TimeSpan.Zero; if (weightedList.Count > 1) { for (var n = 0; n < weightedList.Count; n++) { if (weightedList[n].Key > percentile) { curValue = Calculate(percentile, weightedList[n].Value, weightedList[n].Key, weightedList[n - 1].Value, weightedList[n - 1].Key); break; } if (weightedList[n].Key == percentile) { curValue = weightedList[n].Value; break; } } } else { curValue = weightedList[0].Value; } outputSplits.Add(curValue); runSum += curValue; } else outputSplits.Add(TimeSpan.Zero); } if (runSum > goalTime) percMax = percentile; else percMin = percentile; loopProtection += 1; } while (!(runSum - goalTime).Equals(TimeSpan.Zero) && loopProtection < 50 && goalTime != null); TimeSpan totalTime = TimeSpan.Zero; TimeSpan? useTime = TimeSpan.Zero; for (var ind = 0; ind < Run.Count; ind++) { totalTime += outputSplits[ind]; if (outputSplits[ind] == TimeSpan.Zero) useTime = null; else useTime = totalTime; var time = new Time(Run[ind].Comparisons[Name]); time[method] = useTime; Run[ind].Comparisons[Name] = time; } } public void Generate(ISettings settings) { Generate(TimingMethod.RealTime); Generate(TimingMethod.GameTime); } class IndexedTimeSpan { public TimeSpan Time { get; set; } public int Index { get; set; } public IndexedTimeSpan(TimeSpan time, int index) { Time = time; Index = index; } } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// OrderFormat /// </summary> [DataContract] public partial class OrderFormat : IEquatable<OrderFormat>, IValidatableObject { /// <summary> /// The desired format. /// </summary> /// <value>The desired format.</value> [JsonConverter(typeof(StringEnumConverter))] public enum FormatEnum { /// <summary> /// Enum Text for value: text /// </summary> [EnumMember(Value = "text")] Text = 1, /// <summary> /// Enum Div for value: div /// </summary> [EnumMember(Value = "div")] Div = 2, /// <summary> /// Enum Table for value: table /// </summary> [EnumMember(Value = "table")] Table = 3, /// <summary> /// Enum Email for value: email /// </summary> [EnumMember(Value = "email")] Email = 4 } /// <summary> /// The desired format. /// </summary> /// <value>The desired format.</value> [DataMember(Name="format", EmitDefaultValue=false)] public FormatEnum? Format { get; set; } /// <summary> /// Initializes a new instance of the <see cref="OrderFormat" /> class. /// </summary> /// <param name="context">The context to generate the order view for..</param> /// <param name="dontLinkEmailToSearch">True to not link the email address to the order search.</param> /// <param name="emailAsLink">True to make the email address a clickable mailto link.</param> /// <param name="filterDistributionCenterOid">Specify a distribution center oid to filter the items displayed to that particular distribution center..</param> /// <param name="filterToItemsInContactOid">The container oid to filter items to..</param> /// <param name="format">The desired format..</param> /// <param name="hideBillToAddress">True to ide the bill to address.</param> /// <param name="hidePriceInformation">True to hide price information.</param> /// <param name="linkFileAttachments">True to link file attachments for download.</param> /// <param name="showContactInfo">True to show contact information.</param> /// <param name="showInMerchantCurrency">True to show the order in the merchant currency.</param> /// <param name="showInternalInformation">True to show internal information about the order.</param> /// <param name="showMerchantNotes">True to show merchant notes.</param> /// <param name="showNonSensitivePaymentInfo">True to show non-sensitive payment information.</param> /// <param name="showPaymentInfo">True to show payment information.</param> /// <param name="translate">True to translate the order into the native language of the customer.</param> public OrderFormat(string context = default(string), bool? dontLinkEmailToSearch = default(bool?), bool? emailAsLink = default(bool?), int? filterDistributionCenterOid = default(int?), int? filterToItemsInContactOid = default(int?), FormatEnum? format = default(FormatEnum?), bool? hideBillToAddress = default(bool?), bool? hidePriceInformation = default(bool?), bool? linkFileAttachments = default(bool?), bool? showContactInfo = default(bool?), bool? showInMerchantCurrency = default(bool?), bool? showInternalInformation = default(bool?), bool? showMerchantNotes = default(bool?), bool? showNonSensitivePaymentInfo = default(bool?), bool? showPaymentInfo = default(bool?), bool? translate = default(bool?)) { this.Context = context; this.DontLinkEmailToSearch = dontLinkEmailToSearch; this.EmailAsLink = emailAsLink; this.FilterDistributionCenterOid = filterDistributionCenterOid; this.FilterToItemsInContactOid = filterToItemsInContactOid; this.Format = format; this.HideBillToAddress = hideBillToAddress; this.HidePriceInformation = hidePriceInformation; this.LinkFileAttachments = linkFileAttachments; this.ShowContactInfo = showContactInfo; this.ShowInMerchantCurrency = showInMerchantCurrency; this.ShowInternalInformation = showInternalInformation; this.ShowMerchantNotes = showMerchantNotes; this.ShowNonSensitivePaymentInfo = showNonSensitivePaymentInfo; this.ShowPaymentInfo = showPaymentInfo; this.Translate = translate; } /// <summary> /// The context to generate the order view for. /// </summary> /// <value>The context to generate the order view for.</value> [DataMember(Name="context", EmitDefaultValue=false)] public string Context { get; set; } /// <summary> /// True to not link the email address to the order search /// </summary> /// <value>True to not link the email address to the order search</value> [DataMember(Name="dont_link_email_to_search", EmitDefaultValue=false)] public bool? DontLinkEmailToSearch { get; set; } /// <summary> /// True to make the email address a clickable mailto link /// </summary> /// <value>True to make the email address a clickable mailto link</value> [DataMember(Name="email_as_link", EmitDefaultValue=false)] public bool? EmailAsLink { get; set; } /// <summary> /// Specify a distribution center oid to filter the items displayed to that particular distribution center. /// </summary> /// <value>Specify a distribution center oid to filter the items displayed to that particular distribution center.</value> [DataMember(Name="filter_distribution_center_oid", EmitDefaultValue=false)] public int? FilterDistributionCenterOid { get; set; } /// <summary> /// The container oid to filter items to. /// </summary> /// <value>The container oid to filter items to.</value> [DataMember(Name="filter_to_items_in_contact_oid", EmitDefaultValue=false)] public int? FilterToItemsInContactOid { get; set; } /// <summary> /// True to ide the bill to address /// </summary> /// <value>True to ide the bill to address</value> [DataMember(Name="hide_bill_to_address", EmitDefaultValue=false)] public bool? HideBillToAddress { get; set; } /// <summary> /// True to hide price information /// </summary> /// <value>True to hide price information</value> [DataMember(Name="hide_price_information", EmitDefaultValue=false)] public bool? HidePriceInformation { get; set; } /// <summary> /// True to link file attachments for download /// </summary> /// <value>True to link file attachments for download</value> [DataMember(Name="link_file_attachments", EmitDefaultValue=false)] public bool? LinkFileAttachments { get; set; } /// <summary> /// True to show contact information /// </summary> /// <value>True to show contact information</value> [DataMember(Name="show_contact_info", EmitDefaultValue=false)] public bool? ShowContactInfo { get; set; } /// <summary> /// True to show the order in the merchant currency /// </summary> /// <value>True to show the order in the merchant currency</value> [DataMember(Name="show_in_merchant_currency", EmitDefaultValue=false)] public bool? ShowInMerchantCurrency { get; set; } /// <summary> /// True to show internal information about the order /// </summary> /// <value>True to show internal information about the order</value> [DataMember(Name="show_internal_information", EmitDefaultValue=false)] public bool? ShowInternalInformation { get; set; } /// <summary> /// True to show merchant notes /// </summary> /// <value>True to show merchant notes</value> [DataMember(Name="show_merchant_notes", EmitDefaultValue=false)] public bool? ShowMerchantNotes { get; set; } /// <summary> /// True to show non-sensitive payment information /// </summary> /// <value>True to show non-sensitive payment information</value> [DataMember(Name="show_non_sensitive_payment_info", EmitDefaultValue=false)] public bool? ShowNonSensitivePaymentInfo { get; set; } /// <summary> /// True to show payment information /// </summary> /// <value>True to show payment information</value> [DataMember(Name="show_payment_info", EmitDefaultValue=false)] public bool? ShowPaymentInfo { get; set; } /// <summary> /// True to translate the order into the native language of the customer /// </summary> /// <value>True to translate the order into the native language of the customer</value> [DataMember(Name="translate", EmitDefaultValue=false)] public bool? Translate { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class OrderFormat {\n"); sb.Append(" Context: ").Append(Context).Append("\n"); sb.Append(" DontLinkEmailToSearch: ").Append(DontLinkEmailToSearch).Append("\n"); sb.Append(" EmailAsLink: ").Append(EmailAsLink).Append("\n"); sb.Append(" FilterDistributionCenterOid: ").Append(FilterDistributionCenterOid).Append("\n"); sb.Append(" FilterToItemsInContactOid: ").Append(FilterToItemsInContactOid).Append("\n"); sb.Append(" Format: ").Append(Format).Append("\n"); sb.Append(" HideBillToAddress: ").Append(HideBillToAddress).Append("\n"); sb.Append(" HidePriceInformation: ").Append(HidePriceInformation).Append("\n"); sb.Append(" LinkFileAttachments: ").Append(LinkFileAttachments).Append("\n"); sb.Append(" ShowContactInfo: ").Append(ShowContactInfo).Append("\n"); sb.Append(" ShowInMerchantCurrency: ").Append(ShowInMerchantCurrency).Append("\n"); sb.Append(" ShowInternalInformation: ").Append(ShowInternalInformation).Append("\n"); sb.Append(" ShowMerchantNotes: ").Append(ShowMerchantNotes).Append("\n"); sb.Append(" ShowNonSensitivePaymentInfo: ").Append(ShowNonSensitivePaymentInfo).Append("\n"); sb.Append(" ShowPaymentInfo: ").Append(ShowPaymentInfo).Append("\n"); sb.Append(" Translate: ").Append(Translate).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as OrderFormat); } /// <summary> /// Returns true if OrderFormat instances are equal /// </summary> /// <param name="input">Instance of OrderFormat to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrderFormat input) { if (input == null) return false; return ( this.Context == input.Context || (this.Context != null && this.Context.Equals(input.Context)) ) && ( this.DontLinkEmailToSearch == input.DontLinkEmailToSearch || (this.DontLinkEmailToSearch != null && this.DontLinkEmailToSearch.Equals(input.DontLinkEmailToSearch)) ) && ( this.EmailAsLink == input.EmailAsLink || (this.EmailAsLink != null && this.EmailAsLink.Equals(input.EmailAsLink)) ) && ( this.FilterDistributionCenterOid == input.FilterDistributionCenterOid || (this.FilterDistributionCenterOid != null && this.FilterDistributionCenterOid.Equals(input.FilterDistributionCenterOid)) ) && ( this.FilterToItemsInContactOid == input.FilterToItemsInContactOid || (this.FilterToItemsInContactOid != null && this.FilterToItemsInContactOid.Equals(input.FilterToItemsInContactOid)) ) && ( this.Format == input.Format || (this.Format != null && this.Format.Equals(input.Format)) ) && ( this.HideBillToAddress == input.HideBillToAddress || (this.HideBillToAddress != null && this.HideBillToAddress.Equals(input.HideBillToAddress)) ) && ( this.HidePriceInformation == input.HidePriceInformation || (this.HidePriceInformation != null && this.HidePriceInformation.Equals(input.HidePriceInformation)) ) && ( this.LinkFileAttachments == input.LinkFileAttachments || (this.LinkFileAttachments != null && this.LinkFileAttachments.Equals(input.LinkFileAttachments)) ) && ( this.ShowContactInfo == input.ShowContactInfo || (this.ShowContactInfo != null && this.ShowContactInfo.Equals(input.ShowContactInfo)) ) && ( this.ShowInMerchantCurrency == input.ShowInMerchantCurrency || (this.ShowInMerchantCurrency != null && this.ShowInMerchantCurrency.Equals(input.ShowInMerchantCurrency)) ) && ( this.ShowInternalInformation == input.ShowInternalInformation || (this.ShowInternalInformation != null && this.ShowInternalInformation.Equals(input.ShowInternalInformation)) ) && ( this.ShowMerchantNotes == input.ShowMerchantNotes || (this.ShowMerchantNotes != null && this.ShowMerchantNotes.Equals(input.ShowMerchantNotes)) ) && ( this.ShowNonSensitivePaymentInfo == input.ShowNonSensitivePaymentInfo || (this.ShowNonSensitivePaymentInfo != null && this.ShowNonSensitivePaymentInfo.Equals(input.ShowNonSensitivePaymentInfo)) ) && ( this.ShowPaymentInfo == input.ShowPaymentInfo || (this.ShowPaymentInfo != null && this.ShowPaymentInfo.Equals(input.ShowPaymentInfo)) ) && ( this.Translate == input.Translate || (this.Translate != null && this.Translate.Equals(input.Translate)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Context != null) hashCode = hashCode * 59 + this.Context.GetHashCode(); if (this.DontLinkEmailToSearch != null) hashCode = hashCode * 59 + this.DontLinkEmailToSearch.GetHashCode(); if (this.EmailAsLink != null) hashCode = hashCode * 59 + this.EmailAsLink.GetHashCode(); if (this.FilterDistributionCenterOid != null) hashCode = hashCode * 59 + this.FilterDistributionCenterOid.GetHashCode(); if (this.FilterToItemsInContactOid != null) hashCode = hashCode * 59 + this.FilterToItemsInContactOid.GetHashCode(); if (this.Format != null) hashCode = hashCode * 59 + this.Format.GetHashCode(); if (this.HideBillToAddress != null) hashCode = hashCode * 59 + this.HideBillToAddress.GetHashCode(); if (this.HidePriceInformation != null) hashCode = hashCode * 59 + this.HidePriceInformation.GetHashCode(); if (this.LinkFileAttachments != null) hashCode = hashCode * 59 + this.LinkFileAttachments.GetHashCode(); if (this.ShowContactInfo != null) hashCode = hashCode * 59 + this.ShowContactInfo.GetHashCode(); if (this.ShowInMerchantCurrency != null) hashCode = hashCode * 59 + this.ShowInMerchantCurrency.GetHashCode(); if (this.ShowInternalInformation != null) hashCode = hashCode * 59 + this.ShowInternalInformation.GetHashCode(); if (this.ShowMerchantNotes != null) hashCode = hashCode * 59 + this.ShowMerchantNotes.GetHashCode(); if (this.ShowNonSensitivePaymentInfo != null) hashCode = hashCode * 59 + this.ShowNonSensitivePaymentInfo.GetHashCode(); if (this.ShowPaymentInfo != null) hashCode = hashCode * 59 + this.ShowPaymentInfo.GetHashCode(); if (this.Translate != null) hashCode = hashCode * 59 + this.Translate.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol.Models { using System.Linq; /// <summary> /// An Azure Batch task to add. /// </summary> public partial class TaskAddParameter { /// <summary> /// Initializes a new instance of the TaskAddParameter class. /// </summary> public TaskAddParameter() { } /// <summary> /// Initializes a new instance of the TaskAddParameter class. /// </summary> /// <param name="id">A string that uniquely identifies the task within /// the job.</param> /// <param name="commandLine">The command line of the task.</param> /// <param name="displayName">A display name for the task.</param> /// <param name="exitConditions">How the Batch service should respond /// when the task completes.</param> /// <param name="resourceFiles">A list of files that the Batch service /// will download to the compute node before running the command /// line.</param> /// <param name="environmentSettings">A list of environment variable /// settings for the task.</param> /// <param name="affinityInfo">A locality hint that can be used by the /// Batch service to select a compute node on which to start the new /// task.</param> /// <param name="constraints">The execution constraints that apply to /// this task.</param> /// <param name="userIdentity">The user identity under which the task /// runs.</param> /// <param name="multiInstanceSettings">An object that indicates that /// the task is a multi-instance task, and contains information about /// how to run the multi-instance task.</param> /// <param name="dependsOn">The tasks that this task depends /// on.</param> /// <param name="applicationPackageReferences">A list of application /// packages that the Batch service will deploy to the compute node /// before running the command line.</param> /// <param name="authenticationTokenSettings">The settings for an /// authentication token that the task can use to perform Batch service /// operations.</param> public TaskAddParameter(string id, string commandLine, string displayName = default(string), ExitConditions exitConditions = default(ExitConditions), System.Collections.Generic.IList<ResourceFile> resourceFiles = default(System.Collections.Generic.IList<ResourceFile>), System.Collections.Generic.IList<EnvironmentSetting> environmentSettings = default(System.Collections.Generic.IList<EnvironmentSetting>), AffinityInformation affinityInfo = default(AffinityInformation), TaskConstraints constraints = default(TaskConstraints), UserIdentity userIdentity = default(UserIdentity), MultiInstanceSettings multiInstanceSettings = default(MultiInstanceSettings), TaskDependencies dependsOn = default(TaskDependencies), System.Collections.Generic.IList<ApplicationPackageReference> applicationPackageReferences = default(System.Collections.Generic.IList<ApplicationPackageReference>), AuthenticationTokenSettings authenticationTokenSettings = default(AuthenticationTokenSettings)) { Id = id; DisplayName = displayName; CommandLine = commandLine; ExitConditions = exitConditions; ResourceFiles = resourceFiles; EnvironmentSettings = environmentSettings; AffinityInfo = affinityInfo; Constraints = constraints; UserIdentity = userIdentity; MultiInstanceSettings = multiInstanceSettings; DependsOn = dependsOn; ApplicationPackageReferences = applicationPackageReferences; AuthenticationTokenSettings = authenticationTokenSettings; } /// <summary> /// Gets or sets a string that uniquely identifies the task within the /// job. /// </summary> /// <remarks> /// The ID can contain any combination of alphanumeric characters /// including hyphens and underscores, and cannot contain more than 64 /// characters. The ID is case-preserving and case-insensitive (that /// is, you may not have two IDs within a job that differ only by /// case). /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Gets or sets a display name for the task. /// </summary> /// <remarks> /// The display name need not be unique and can contain any Unicode /// characters up to a maximum length of 1024. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "displayName")] public string DisplayName { get; set; } /// <summary> /// Gets or sets the command line of the task. /// </summary> /// <remarks> /// For multi-instance tasks, the command line is executed as the /// primary task, after the primary task and all subtasks have finished /// executing the coordination command line. The command line does not /// run under a shell, and therefore cannot take advantage of shell /// features such as environment variable expansion. If you want to /// take advantage of such features, you should invoke the shell in the /// command line, for example using "cmd /c MyCommand" in Windows or /// "/bin/sh -c MyCommand" in Linux. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "commandLine")] public string CommandLine { get; set; } /// <summary> /// Gets or sets how the Batch service should respond when the task /// completes. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "exitConditions")] public ExitConditions ExitConditions { get; set; } /// <summary> /// Gets or sets a list of files that the Batch service will download /// to the compute node before running the command line. /// </summary> /// <remarks> /// For multi-instance tasks, the resource files will only be /// downloaded to the compute node on which the primary task is /// executed. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "resourceFiles")] public System.Collections.Generic.IList<ResourceFile> ResourceFiles { get; set; } /// <summary> /// Gets or sets a list of environment variable settings for the task. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "environmentSettings")] public System.Collections.Generic.IList<EnvironmentSetting> EnvironmentSettings { get; set; } /// <summary> /// Gets or sets a locality hint that can be used by the Batch service /// to select a compute node on which to start the new task. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "affinityInfo")] public AffinityInformation AffinityInfo { get; set; } /// <summary> /// Gets or sets the execution constraints that apply to this task. /// </summary> /// <remarks> /// If you do not specify constraints, the maxTaskRetryCount is the /// maxTaskRetryCount specified for the job, and the maxWallClockTime /// and retentionTime are infinite. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "constraints")] public TaskConstraints Constraints { get; set; } /// <summary> /// Gets or sets the user identity under which the task runs. /// </summary> /// <remarks> /// If omitted, the task runs as a non-administrative user unique to /// the task. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "userIdentity")] public UserIdentity UserIdentity { get; set; } /// <summary> /// Gets or sets an object that indicates that the task is a /// multi-instance task, and contains information about how to run the /// multi-instance task. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "multiInstanceSettings")] public MultiInstanceSettings MultiInstanceSettings { get; set; } /// <summary> /// Gets or sets the tasks that this task depends on. /// </summary> /// <remarks> /// This task will not be scheduled until all tasks that it depends on /// have completed successfully. If any of those tasks fail and exhaust /// their retry counts, this task will never be scheduled. If the job /// does not have usesTaskDependencies set to true, and this element is /// present, the request fails with error code /// TaskDependenciesNotSpecifiedOnJob. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "dependsOn")] public TaskDependencies DependsOn { get; set; } /// <summary> /// Gets or sets a list of application packages that the Batch service /// will deploy to the compute node before running the command line. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "applicationPackageReferences")] public System.Collections.Generic.IList<ApplicationPackageReference> ApplicationPackageReferences { get; set; } /// <summary> /// Gets or sets the settings for an authentication token that the task /// can use to perform Batch service operations. /// </summary> /// <remarks> /// If this property is set, the Batch service provides the task with /// an authentication token which can be used to authenticate Batch /// service operations without requiring an account access key. The /// token is provided via the AZ_BATCH_AUTHENTICATION_TOKEN environment /// variable. The operations that the task can carry out using the /// token depend on the settings. For example, a task can request job /// permissions in order to add other tasks to the job, or check the /// status of the job or of other tasks under the job. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "authenticationTokenSettings")] public AuthenticationTokenSettings AuthenticationTokenSettings { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Id == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "Id"); } if (CommandLine == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "CommandLine"); } if (this.ResourceFiles != null) { foreach (var element in this.ResourceFiles) { if (element != null) { element.Validate(); } } } if (this.EnvironmentSettings != null) { foreach (var element1 in this.EnvironmentSettings) { if (element1 != null) { element1.Validate(); } } } if (this.AffinityInfo != null) { this.AffinityInfo.Validate(); } if (this.MultiInstanceSettings != null) { this.MultiInstanceSettings.Validate(); } if (this.ApplicationPackageReferences != null) { foreach (var element2 in this.ApplicationPackageReferences) { if (element2 != null) { element2.Validate(); } } } } } }
using System; using System.Data; using System.Data.Common; using System.Transactions; using System.Timers; using System.Threading; using Joy.Core; using System.Collections.Generic; namespace Joy.Data { public abstract class Db { public delegate void TableEnumerationHandler(DataRow row, string tableNameCol); public delegate void ColumnEnumerationHandler(DataRow row, string colNameCol); public DbConnection Connection { get { if (_connection != null) { return _connection; } else { return GetConnection(); } } set { _connection = value; } }protected DbConnection _connection; public virtual string DbInfo { get { return dbinfo; } set { dbinfo = value; } }protected string dbinfo; public virtual string ConnStr { get { if (string.IsNullOrEmpty(_connstr)) { throw new Exception("Error: Connection string missing"); } return _connstr; } set { _connstr = value; } }protected string _connstr; public Db() { ConnStr = ""; } public Db(string ConnectionString) { ConnStr = ConnectionString; } public DataSet GetDataSet(DataAdapter adapter) { int RowCount = 0; DataSet ds = new DataSet(); try { RowCount = adapter.Fill(ds); } catch (Exception e) { Exceptions.LogOnly(e); RowCount = 0; ds.ExtendedProperties["error"] = e; } return ds; } public DataTable PagedQuery( string primaryFieldName, int curtPage, int pageSize, string[] fieldClauses, string[] tableClauses, string whereClause, string[] orderClauses, string[] groupClauses ) { string primaryField = SqlHelper.MakeSafeFieldNameSql(primaryFieldName); string fieldClause = SqlHelper.MakeSafeFieldNameSql(fieldClauses); string tableClause = SqlHelper.MakeSafeFieldNameSql(tableClauses); string orderClause = SqlHelper.MakeSafeFieldNameSql(orderClauses); string groupClause = SqlHelper.MakeSafeFieldNameSql(groupClauses); return PagedQuery(primaryField, curtPage.ToString(), pageSize.ToString(), fieldClause, tableClause, whereClause, orderClause, groupClause); } public abstract void GetReady(DbConfig cfg); public abstract DataTable PagedQuery(string primaryField, string curtPage, string pageSize, string fieldClause, string tableClause, string whereClause, string orderClause, string groupClause); public DataTable GetDataTable(string Sql) { DataSet ds = GetDataSet(GetAdapter(Sql)); return GetDataTable(ds); } public DataTable GetDataTable(DataSet dataset) { if (dataset.Tables != null && dataset.Tables.Count > 0) { return dataset.Tables[0]; } return null; } public ExecuteResult Execute(string Sql, DbConnection Connection, Transaction Tst, string scopeIdentityTable = null) { int RowCount; if (Connection == null) { Connection = GetConnection(); } try { if (Connection.State == ConnectionState.Closed) { Connection.Open(); } if (Tst != null) { Connection.EnlistTransaction(Tst); } DbCommand cm = GetCommand(Sql, Connection); RowCount = cm.ExecuteNonQuery(); if (!string.IsNullOrEmpty(scopeIdentityTable)) { int id = ExecScalar<int>(string.Concat("select @@IDENTITY from ", scopeIdentityTable)); return new ExecuteResult(id); } else { return new ExecuteResult(RowCount); } } catch (TransactionException err) { if (Tst != null) { Tst.Rollback(err); } Exceptions.LogOnly(err); return new ExecuteResult(null, err); } catch (Exception err) { if (Tst != null) { Tst.Rollback(err); } Exceptions.LogOnly(err); return new ExecuteResult(null, err); } finally { Connection.Close(); } } public T ExecuteResult<T>(string Sql) { DataTable r = GetDataTable(Sql); if (r != null && r.Rows.Count > 0) { try { return (T)Convert.ChangeType(r.Rows[0][0], typeof(T)); } catch (Exception e) { ErrorHandler.Handle(e); return default(T); } } else { return default(T); } } public int ExecuteInsert(string table, string textField, string idField) { string gid = Guid.NewGuid().ToString(); string sqlInsert = string.Concat("insert into ", table, "(", textField, ") values('", gid, "')"); string sqlGetInserted = string.Concat("select ", idField, " from ", table, " where ", textField, " like '", gid, "'"); Execute(sqlInsert); return ExecScalar<int>(sqlGetInserted); } public int ExecuteNonQuery(string sql, params string[] args) { return Execute(string.Format(sql, args)); } public int Execute(string Sql, string scopeIdentityTable = null) { ExecuteResult r = Execute(Sql, null, null, scopeIdentityTable); return r.IntRlt; } public ExecuteResult ExecuteReader(string Sql, Func<IDataReader, object> callback, DbConnection Connection, Transaction Tst) { IDataReader reader = null; bool isGetRltDone = false; if (callback == null) { return new ExecuteResult { Exception = new ArgumentNullException("callback") }; } if (Connection == null) { Connection = GetConnection(); } try { if (Connection.State == ConnectionState.Closed) { Connection.Open(); } if (Tst != null) { Connection.EnlistTransaction(Tst); } DbCommand cm = GetCommand(Sql, Connection); ExecuteResult r = null; using (reader = cm.ExecuteReader(CommandBehavior.CloseConnection)) { isGetRltDone = true; r = new ExecuteResult { ObjRlt = callback(reader) }; }; return r; } catch (TransactionException err) { if (Tst != null) { Tst.Rollback(err); } Exceptions.LogOnly(err); return new ExecuteResult { Exception = err }; } catch (Exception err) { if (isGetRltDone) { throw; } else { if (Tst != null) { Tst.Rollback(err); } Exceptions.LogOnly(err); return new ExecuteResult { Exception = err }; } } finally { if (reader != null) { if (!reader.IsClosed) { reader.Close(); } reader.Dispose(); } if (Connection != null) { Connection.Close(); } } } public object ExecuteValue(string sql) { var table = GetDataTable(sql); if (table != null && table.Rows.Count > 0) { return table.Rows[0][0]; } return null; } public List<T> ExecuteList<T>(string Sql) where T : new() { ExecuteResult rlt = ExecuteReader(Sql, new Func<System.Data.IDataReader, object>(delegate(IDataReader reader) { return reader.Fill<T>(); })); if (rlt.IsNoException) { return rlt.ObjRlt as List<T>; } else { return null; } } public ExecuteResult ExecuteReader(string Sql, Func<IDataReader, object> callback) { return ExecuteReader(Sql, callback, null, null); } public T ExecScalar<T>(string Sql, DbConnection Connection, Transaction Tst) { T rlt; if (Connection == null) { Connection = GetConnection(); } try { if (Connection.State == ConnectionState.Closed) { Connection.Open(); } if (Tst != null) { Connection.EnlistTransaction(Tst); } DbCommand cm = GetCommand(Sql, Connection); object returnValue = cm.ExecuteScalar(); rlt = (T)Convert.ChangeType(returnValue, typeof(T)); return rlt; } catch (TransactionException err) { if (Tst != null) { Tst.Rollback(err); } ErrorHandler.Handle(err); return default(T); } catch (Exception err) { if (Tst != null) { Tst.Rollback(err); } ErrorHandler.Handle(err); return default(T); } finally { Connection.Close(); } } public T ExecScalar<T>(string Sql) { return ExecScalar<T>(Sql, null, null); } public void EnumTables(TableEnumerationHandler callback) { DataTable dt = GetSchema("tables"); foreach (DataRow row in dt.Rows) { callback(row, "TABLE_NAME"); } } //public void EnumColumns(string tableName, ColumnEnumerationHandler callback) //{ //} public DataTable GetSchema() { return GetSchema(null); } public DataTable GetSchema(string collectionName) { DataTable dt; DbConnection cn = GetConnection(); cn.Open(); if (string.IsNullOrEmpty(collectionName)) { dt = cn.GetSchema(); } else { dt = cn.GetSchema(collectionName); } cn.Close(); return dt; } public abstract DataAdapter GetAdapter(string Sql); public virtual DbCommand GetCommand(string sql) { return GetCommand(sql, GetConnection()); } public abstract DbCommand GetCommand(string Sql, DbConnection Connection); public abstract DbCommand GetCommand(string Sql, DbConnection Connection, DbTransaction Transaction); public abstract DbConnection GetConnectionSingleTry(); public virtual DbConnection GetConnection() { return GetConnection(5, 1000); } public virtual DbConnection GetConnection(int retryTimes, int waitInterval) { for (int i = 0; i < retryTimes; i++) { DbConnection rlt = GetConnectionSingleTry(); if (rlt != null) { return rlt; } else { Thread.Sleep(waitInterval); } } return null; } public abstract DataColumnCollection GetColumnsInfo(string tableName); } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Serialization; using Microsoft.TeamFoundation.Build.WebApi; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; namespace Microsoft.VisualStudio.Services.Agent.Worker.Build { [ServiceLocator(Default = typeof(SvnCommandManager))] public interface ISvnCommandManager : IAgentService { /// <summary> /// Initializes svn command path and execution environment /// </summary> /// <param name="context">The build commands' execution context</param> /// <param name="endpoint">The Subversion server endpoint providing URL, username/password, and untrasted certs acceptace information</param> /// <param name="cancellationToken">The cancellation token used to stop svn command execution</param> void Init( IExecutionContext context, ServiceEndpoint endpoint, CancellationToken cancellationToken); /// <summary> /// svn info URL --depth empty --revision <sourceRevision> --xml --username <user> --password <password> --non-interactive [--trust-server-cert] /// </summary> /// <param name="serverPath"></param> /// <param name="sourceRevision"></param> /// <returns></returns> Task<long> GetLatestRevisionAsync(string serverPath, string sourceRevision); /// <summary> /// Removes unused and duplicate mappings. /// </summary> /// <param name="allMappings"></param> /// <returns></returns> Dictionary<string, SvnMappingDetails> NormalizeMappings(List<SvnMappingDetails> allMappings); /// <summary> /// Normalizes path separator for server and local paths. /// </summary> /// <param name="path"></param> /// <param name="pathSeparator"></param> /// <param name="altPathSeparator"></param> /// <returns></returns> string NormalizeRelativePath(string path, char pathSeparator, char altPathSeparator); /// <summary> /// Detects old mappings (if any) and refreshes the SVN working copies to match the new mappings. /// </summary> /// <param name="rootPath"></param> /// <param name="distinctMappings"></param> /// <param name="cleanRepository"></param> /// <param name="sourceBranch"></param> /// <param name="revision"></param> /// <returns></returns> Task<string> UpdateWorkspace(string rootPath, Dictionary<string, SvnMappingDetails> distinctMappings, bool cleanRepository, string sourceBranch, string revision); /// <summary> /// Finds a local path the provided server path is mapped to. /// </summary> /// <param name="serverPath"></param> /// <param name="rootPath"></param> /// <returns></returns> string ResolveServerPath(string serverPath, string rootPath); } public class SvnCommandManager : AgentService, ISvnCommandManager { public void Init( IExecutionContext context, ServiceEndpoint endpoint, CancellationToken cancellationToken) { // Validation. ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(endpoint, nameof(endpoint)); ArgUtil.NotNull(cancellationToken, nameof(cancellationToken)); ArgUtil.NotNull(endpoint.Url, nameof(endpoint.Url)); ArgUtil.Equal(true, endpoint.Url.IsAbsoluteUri, nameof(endpoint.Url.IsAbsoluteUri)); ArgUtil.NotNull(endpoint.Data, nameof(endpoint.Data)); ArgUtil.NotNull(endpoint.Authorization, nameof(endpoint.Authorization)); ArgUtil.NotNull(endpoint.Authorization.Parameters, nameof(endpoint.Authorization.Parameters)); ArgUtil.Equal(EndpointAuthorizationSchemes.UsernamePassword, endpoint.Authorization.Scheme, nameof(endpoint.Authorization.Scheme)); _context = context; _endpoint = endpoint; _cancellationToken = cancellationToken; // Find svn in %Path% IWhichUtil whichTool = HostContext.GetService<IWhichUtil>(); string svnPath = whichTool.Which("svn"); if (string.IsNullOrEmpty(svnPath)) { throw new Exception(StringUtil.Loc("SvnNotInstalled")); } else { _context.Debug($"Found svn installation path: {svnPath}."); _svn = svnPath; } // External providers may need basic auth or tokens endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Username, out _username); endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Password, out _password); // TODO: replace explicit string literals with WellKnownEndpointData constants // as soon as the latters are available thru the Microsoft.TeamFoundation.Build.WebApi package _acceptUntrusted = endpoint.Data.ContainsKey(/* WellKnownEndpointData.SvnAcceptUntrustedCertificates */ "acceptUntrustedCerts") && StringUtil.ConvertToBoolean(endpoint.Data[/* WellKnownEndpointData.SvnAcceptUntrustedCertificates */ "acceptUntrustedCerts"], defaultValue: false); } public async Task<string> UpdateWorkspace( string rootPath, Dictionary<string, SvnMappingDetails> distinctMappings, bool cleanRepository, string sourceBranch, string revision) { if (cleanRepository) { // A clean build has been requested, if the $(build.Clean) variable didn't force // the BuildDirectoryManager to re-create the source directory earlier, // let's do it now explicitly. IBuildDirectoryManager buildDirectoryManager = HostContext.GetService<IBuildDirectoryManager>(); BuildCleanOption? cleanOption = _context.Variables.Build_Clean; buildDirectoryManager.CreateDirectory( _context, description: "source directory", path: rootPath, deleteExisting: !(cleanOption == BuildCleanOption.All || cleanOption == BuildCleanOption.Source)); } Dictionary<string, Uri> oldMappings = await GetOldMappings(rootPath); _context.Debug($"oldMappings.Count: {oldMappings.Count}"); oldMappings.ToList().ForEach(p => _context.Debug($" [{p.Key}] {p.Value}")); Dictionary<string, SvnMappingDetails> newMappings = BuildNewMappings(rootPath, sourceBranch, distinctMappings); _context.Debug($"newMappings.Count: {newMappings.Count}"); newMappings.ToList().ForEach(p => _context.Debug($" [{p.Key}] ServerPath: {p.Value.ServerPath}, LocalPath: {p.Value.LocalPath}, Depth: {p.Value.Depth}, Revision: {p.Value.Revision}, IgnoreExternals: {p.Value.IgnoreExternals}")); CleanUpSvnWorkspace(oldMappings, newMappings); long maxRevision = 0; foreach (SvnMappingDetails mapping in newMappings.Values) { long mappingRevision = await GetLatestRevisionAsync(mapping.ServerPath, revision); if (mappingRevision > maxRevision) { maxRevision = mappingRevision; } } await UpdateToRevisionAsync(oldMappings, newMappings, maxRevision); return maxRevision > 0 ? maxRevision.ToString() : "HEAD"; } private async Task<Dictionary<string, Uri>> GetOldMappings(string rootPath) { if (File.Exists(rootPath)) { throw new Exception(StringUtil.Loc("SvnFileAlreadyExists", rootPath)); } Dictionary<string, Uri> mappings = new Dictionary<string, Uri>(); if (Directory.Exists(rootPath)) { foreach (string workingDirectoryPath in GetSvnWorkingCopyPaths(rootPath)) { Uri url = await GetRootUrlAsync(workingDirectoryPath); if (url != null) { mappings.Add(workingDirectoryPath, url); } } } return mappings; } private List<string> GetSvnWorkingCopyPaths(string rootPath) { if (Directory.Exists(Path.Combine(rootPath, ".svn"))) { return new List<string>() { rootPath }; } else { ConcurrentStack<string> candidates = new ConcurrentStack<string>(); Directory.EnumerateDirectories(rootPath, "*", SearchOption.TopDirectoryOnly) .AsParallel() .ForAll(fld => candidates.PushRange(GetSvnWorkingCopyPaths(fld).ToArray())); return candidates.ToList(); } } private Dictionary<string, SvnMappingDetails> BuildNewMappings(string rootPath, string sourceBranch, Dictionary<string, SvnMappingDetails> distinctMappings) { Dictionary<string, SvnMappingDetails> mappings = new Dictionary<string, SvnMappingDetails>(); if (distinctMappings != null && distinctMappings.Count > 0) { foreach (KeyValuePair<string, SvnMappingDetails> mapping in distinctMappings) { SvnMappingDetails mappingDetails = mapping.Value; string localPath = mappingDetails.LocalPath; string absoluteLocalPath = Path.Combine(rootPath, localPath); SvnMappingDetails newMappingDetails = new SvnMappingDetails(); newMappingDetails.ServerPath = mappingDetails.ServerPath; newMappingDetails.LocalPath = absoluteLocalPath; newMappingDetails.Revision = mappingDetails.Revision; newMappingDetails.Depth = mappingDetails.Depth; newMappingDetails.IgnoreExternals = mappingDetails.IgnoreExternals; mappings.Add(absoluteLocalPath, newMappingDetails); } } else { SvnMappingDetails newMappingDetails = new SvnMappingDetails(); newMappingDetails.ServerPath = sourceBranch; newMappingDetails.LocalPath = rootPath; newMappingDetails.Revision = "HEAD"; newMappingDetails.Depth = 3; //Infinity newMappingDetails.IgnoreExternals = true; mappings.Add(rootPath, newMappingDetails); } return mappings; } public async Task<long> GetLatestRevisionAsync(string serverPath, string sourceRevision) { Trace.Verbose($@"Get latest revision of: '{_endpoint.Url.AbsoluteUri}' at or before: '{sourceRevision}'."); string xml = await RunPorcelainCommandAsync( "info", BuildSvnUri(serverPath), "--depth", "empty", "--revision", sourceRevision, "--xml"); // Deserialize the XML. // The command returns a non-zero exit code if the source revision is not found. // The assertions performed here should never fail. XmlSerializer serializer = new XmlSerializer(typeof(SvnInfo)); ArgUtil.NotNullOrEmpty(xml, nameof(xml)); using (StringReader reader = new StringReader(xml)) { SvnInfo info = serializer.Deserialize(reader) as SvnInfo; ArgUtil.NotNull(info, nameof(info)); ArgUtil.NotNull(info.Entries, nameof(info.Entries)); ArgUtil.Equal(1, info.Entries.Length, nameof(info.Entries.Length)); long revision = 0; long.TryParse(info.Entries[0].Commit?.Revision?? sourceRevision, out revision); return revision; } } public string ResolveServerPath(string serverPath, string rootPath) { ArgUtil.Equal(true, serverPath.StartsWith(@"^/"), nameof(serverPath)); foreach (string workingDirectoryPath in GetSvnWorkingCopyPaths(rootPath)) { try { Trace.Verbose($@"Get SVN info for the working directory path '{workingDirectoryPath}'."); string xml = RunPorcelainCommandAsync( "info", workingDirectoryPath, "--depth", "empty", "--xml").GetAwaiter().GetResult(); // Deserialize the XML. // The command returns a non-zero exit code if the local path is not a working copy. // The assertions performed here should never fail. XmlSerializer serializer = new XmlSerializer(typeof(SvnInfo)); ArgUtil.NotNullOrEmpty(xml, nameof(xml)); using (StringReader reader = new StringReader(xml)) { SvnInfo info = serializer.Deserialize(reader) as SvnInfo; ArgUtil.NotNull(info, nameof(info)); ArgUtil.NotNull(info.Entries, nameof(info.Entries)); ArgUtil.Equal(1, info.Entries.Length, nameof(info.Entries.Length)); if (serverPath.Equals(info.Entries[0].RelativeUrl, StringComparison.Ordinal) || serverPath.StartsWith(info.Entries[0].RelativeUrl + '/', StringComparison.Ordinal)) { // We've found the mapping the serverPath belongs to. int n = info.Entries[0].RelativeUrl.Length; string relativePath = serverPath.Length <= n + 1 ? string.Empty : serverPath.Substring(n + 1); return Path.Combine(workingDirectoryPath, relativePath); } } } catch (ProcessExitCodeException) { Trace.Warning($@"The path '{workingDirectoryPath}' is not an SVN working directory path."); } } Trace.Warning($@"Haven't found any suitable mapping for '{serverPath}'"); // Since the server path starts with the "^/" prefix we return the original path without these two characters. return serverPath.Substring(2); } private async Task<Uri> GetRootUrlAsync(string localPath) { Trace.Verbose($@"Get URL for: '{localPath}'."); try { string xml = await RunPorcelainCommandAsync( "info", localPath, "--depth", "empty", "--xml"); // Deserialize the XML. // The command returns a non-zero exit code if the local path is not a working copy. // The assertions performed here should never fail. XmlSerializer serializer = new XmlSerializer(typeof(SvnInfo)); ArgUtil.NotNullOrEmpty(xml, nameof(xml)); using (StringReader reader = new StringReader(xml)) { SvnInfo info = serializer.Deserialize(reader) as SvnInfo; ArgUtil.NotNull(info, nameof(info)); ArgUtil.NotNull(info.Entries, nameof(info.Entries)); ArgUtil.Equal(1, info.Entries.Length, nameof(info.Entries.Length)); return new Uri(info.Entries[0].Url); } } catch (ProcessExitCodeException) { Trace.Verbose($@"The folder '{localPath}.svn' seems not to be a subversion system directory."); return null; } } private async Task UpdateToRevisionAsync(Dictionary<string, Uri> oldMappings, Dictionary<string, SvnMappingDetails> newMappings, long maxRevision) { foreach (KeyValuePair<string, SvnMappingDetails> mapping in newMappings) { string localPath = mapping.Key; SvnMappingDetails mappingDetails = mapping.Value; string effectiveServerUri = BuildSvnUri(mappingDetails.ServerPath); string effectiveRevision = EffectiveRevision(mappingDetails.Revision, maxRevision); mappingDetails.Revision = effectiveRevision; if (!Directory.Exists(Path.Combine(localPath, ".svn"))) { _context.Debug(String.Format( "Checking out with depth: {0}, revision: {1}, ignore externals: {2}", mappingDetails.Depth, effectiveRevision, mappingDetails.IgnoreExternals)); mappingDetails.ServerPath = effectiveServerUri; await CheckoutAsync(mappingDetails); } else if (oldMappings.ContainsKey(localPath) && oldMappings[localPath].Equals(new Uri(effectiveServerUri))) { _context.Debug(String.Format( "Updating with depth: {0}, revision: {1}, ignore externals: {2}", mappingDetails.Depth, mappingDetails.Revision, mappingDetails.IgnoreExternals)); await UpdateAsync(mappingDetails); } else { _context.Debug(String.Format( "Switching to {0} with depth: {1}, revision: {2}, ignore externals: {3}", mappingDetails.ServerPath, mappingDetails.Depth, mappingDetails.Revision, mappingDetails.IgnoreExternals)); await SwitchAsync(mappingDetails); } } } private string EffectiveRevision(string mappingRevision, long maxRevision) { if (!mappingRevision.Equals("HEAD", StringComparison.OrdinalIgnoreCase)) { // A specific revision has been requested in mapping return mappingRevision; } else if (maxRevision == 0) { // Tip revision return "HEAD"; } else { return maxRevision.ToString(); } } private void CleanUpSvnWorkspace(Dictionary<string, Uri> oldMappings, Dictionary<string, SvnMappingDetails> newMappings) { Trace.Verbose("Clean up Svn workspace."); oldMappings.Where(m => !newMappings.ContainsKey(m.Key)) .AsParallel() .ForAll(m => { Trace.Verbose($@"Delete unmapped folder: '{m.Key}'"); IOUtil.DeleteDirectory(m.Key, CancellationToken.None); }); } /// <summary> /// svn update localPath --depth empty --revision <sourceRevision> --xml --username lin --password ideafix --non-interactive [--trust-server-cert] /// </summary> /// <param name="mapping"></param> /// <returns></returns> private async Task UpdateAsync(SvnMappingDetails mapping) { Trace.Verbose($@"Update '{mapping.LocalPath}'."); await RunCommandAsync( "update", mapping.LocalPath, "--revision", mapping.Revision, "--depth", ToDepthArgument(mapping.Depth), mapping.IgnoreExternals ? "--ignore-externals" : null); } /// <summary> /// svn switch localPath --depth empty --revision <sourceRevision> --xml --username lin --password ideafix --non-interactive [--trust-server-cert] /// </summary> /// <param name="mapping"></param> /// <returns></returns> private async Task SwitchAsync(SvnMappingDetails mapping) { Trace.Verbose($@"Switch '{mapping.LocalPath}' to '{mapping.ServerPath}'."); await RunCommandAsync( "switch", $"^/{mapping.ServerPath}", mapping.LocalPath, "--ignore-ancestry", "--revision", mapping.Revision, "--depth", ToDepthArgument(mapping.Depth), mapping.IgnoreExternals ? "--ignore-externals" : null); } /// <summary> /// svn checkout localPath --depth empty --revision <sourceRevision> --xml --username lin --password ideafix --non-interactive [--trust-server-cert] /// </summary> /// <param name="mapping"></param> /// <returns></returns> private async Task CheckoutAsync(SvnMappingDetails mapping) { Trace.Verbose($@"Checkout '{mapping.ServerPath}' to '{mapping.LocalPath}'."); await RunCommandAsync( "checkout", mapping.ServerPath, mapping.LocalPath, "--revision", mapping.Revision, "--depth", ToDepthArgument(mapping.Depth), mapping.IgnoreExternals ? "--ignore-externals" : null); } private string BuildSvnUri(string serverPath) { StringBuilder sb = new StringBuilder(_endpoint.Url.ToString()); if (!string.IsNullOrEmpty(serverPath)) { if (sb[sb.Length - 1] != '/') { sb.Append('/'); } sb.Append(serverPath); } return sb.Replace('\\', '/').ToString(); } private string FormatArgumentsWithDefaults(params string[] args) { // Format each arg. List < string> formattedArgs = new List<string>(); foreach (string arg in args ?? new string[0]) { if (!string.IsNullOrEmpty(arg)) { // Validate the arg. if (arg.IndexOfAny(new char[] { '"', '\r', '\n' }) >= 0) { throw new Exception(StringUtil.Loc("InvalidCommandArg", arg)); } // Add the arg. formattedArgs.Add(QuotedArgument(arg)); } } // Add the common parameters. if (_acceptUntrusted) { formattedArgs.Add("--trust-server-cert"); } if (!string.IsNullOrWhiteSpace(_username)) { formattedArgs.Add("--username"); formattedArgs.Add(QuotedArgument(_username)); } if (!string.IsNullOrWhiteSpace(_password)) { formattedArgs.Add("--password"); formattedArgs.Add(QuotedArgument(_password)); } formattedArgs.Add("--non-interactive"); return string.Join(" ", formattedArgs); } private string QuotedArgument(string arg) { char quote = '\"'; char altQuote = '\''; if (arg.IndexOf(quote) > -1) { quote = '\''; altQuote = '\"'; } return (arg.IndexOfAny(new char[] { ' ', altQuote}) ==-1) ? arg : $"{quote}{arg}{quote}"; } private string ToDepthArgument(int depth) { switch (depth) { case 0: return "empty"; case 1: return "files"; case 2: return "immediates"; default: return "infinity"; } } private async Task RunCommandAsync(params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(_context, nameof(_context)); // Invoke tf. using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { var outputLock = new object(); processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { _context.Output(e.Data); } }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { _context.Output(e.Data); } }; string arguments = FormatArgumentsWithDefaults(args); _context.Command($@"{_svn} {arguments}"); await processInvoker.ExecuteAsync( workingDirectory: IOUtil.GetWorkPath(HostContext), fileName: _svn, arguments: arguments, environment: null, requireExitCodeZero: true, cancellationToken: _cancellationToken); } } private async Task<string> RunPorcelainCommandAsync(params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(_context, nameof(_context)); // Invoke tf. using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { var output = new List<string>(); var outputLock = new object(); processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { _context.Debug(e.Data); output.Add(e.Data); } }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { _context.Debug(e.Data); output.Add(e.Data); } }; string arguments = FormatArgumentsWithDefaults(args); _context.Debug($@"{_svn} {arguments}"); // TODO: Test whether the output encoding needs to be specified on a non-Latin OS. try { await processInvoker.ExecuteAsync( workingDirectory: IOUtil.GetWorkPath(HostContext), fileName: _svn, arguments: arguments, environment: null, requireExitCodeZero: true, cancellationToken: _cancellationToken); } catch (ProcessExitCodeException) { // The command failed. Dump the output and throw. output.ForEach(x => _context.Output(x ?? string.Empty)); throw; } // Note, string.join gracefully handles a null element within the IEnumerable<string>. return string.Join(Environment.NewLine, output); } } public Dictionary<string, SvnMappingDetails> NormalizeMappings(List<SvnMappingDetails> allMappings) { // We use Ordinal comparer because SVN is case sensetive and keys in the dictionary are URLs. Dictionary<string, SvnMappingDetails> distinctMappings = new Dictionary<string, SvnMappingDetails>(StringComparer.Ordinal); HashSet<string> localPaths = new HashSet<string>(StringComparer.Ordinal); foreach (SvnMappingDetails map in allMappings) { string localPath = NormalizeRelativePath(map.LocalPath, Path.DirectorySeparatorChar, '/'); string serverPath = NormalizeRelativePath(map.ServerPath, '/', '\\'); if (string.IsNullOrEmpty(serverPath)) { _context.Debug(StringUtil.Loc("SvnEmptyServerPath", localPath)); _context.Debug(StringUtil.Loc("SvnMappingIgnored")); distinctMappings.Clear(); distinctMappings.Add(string.Empty, map); break; } if (localPaths.Contains(localPath)) { _context.Debug(StringUtil.Loc("SvnMappingDuplicateLocal", localPath)); continue; } else { localPaths.Add(localPath); } if (distinctMappings.ContainsKey(serverPath)) { _context.Debug(StringUtil.Loc("SvnMappingDuplicateServer", serverPath)); continue; } // Put normalized values of the local and server paths back into the mapping. map.LocalPath = localPath; map.ServerPath = serverPath; distinctMappings.Add(serverPath, map); } return distinctMappings; } public string NormalizeRelativePath(string path, char pathSeparator, char altPathSeparator) { string relativePath = (path ?? string.Empty).Replace(altPathSeparator, pathSeparator); relativePath = relativePath.Trim(pathSeparator, ' '); if (relativePath.Contains(":") || relativePath.Contains("..")) { throw new Exception(StringUtil.Loc("SvnIncorrectRelativePath", relativePath)); } return relativePath; } // The cancellation token used to stop svn command execution private CancellationToken _cancellationToken; // The Subversion server endpoint providing URL, username/password, and untrasted certs acceptace information private ServiceEndpoint _endpoint; // The build commands' execution context private IExecutionContext _context; // The svn command line utility location private string _svn; // The svn user name from SVN repository connection endpoint private string _username; // The svn user password from SVN repository connection endpoint private string _password; // The acceptUntrustedCerts property from SVN repository connection endpoint private bool _acceptUntrusted; } //////////////////////////////////////////////////////////////////////////////// // svn info data objects //////////////////////////////////////////////////////////////////////////////// [XmlRoot(ElementName = "info", Namespace = "")] public sealed class SvnInfo { [XmlElement(ElementName = "entry", Namespace = "")] public SvnInfoEntry[] Entries { get; set; } } public sealed class SvnInfoEntry { [XmlAttribute(AttributeName = "kind", Namespace = "")] public string Kind { get; set; } [XmlAttribute(AttributeName = "path", Namespace = "")] public string Path { get; set; } [XmlAttribute(AttributeName = "revision", Namespace = "")] public string Revision { get; set; } [XmlElement(ElementName = "url", Namespace = "")] public string Url { get; set; } [XmlElement(ElementName = "relative-url", Namespace = "")] public string RelativeUrl { get; set; } [XmlElement(ElementName = "repository", Namespace = "")] public SvnInfoRepository[] Repository { get; set; } [XmlElement(ElementName = "wc-info", Namespace = "", IsNullable = true)] public SvnInfoWorkingCopy[] WorkingCopyInfo { get; set; } [XmlElement(ElementName = "commit", Namespace = "")] public SvnInfoCommit Commit { get; set; } } public sealed class SvnInfoRepository { [XmlElement(ElementName = "wcroot-abspath", Namespace = "")] public string AbsPath { get; set; } [XmlElement(ElementName = "schedule", Namespace = "")] public string Schedule { get; set; } [XmlElement(ElementName = "depth", Namespace = "")] public string Depth { get; set; } } public sealed class SvnInfoWorkingCopy { [XmlElement(ElementName = "root", Namespace = "")] public string Root { get; set; } [XmlElement(ElementName = "uuid", Namespace = "")] public Guid Uuid { get; set; } } public sealed class SvnInfoCommit { [XmlAttribute(AttributeName = "revision", Namespace = "")] public string Revision { get; set; } [XmlElement(ElementName = "author", Namespace = "")] public string Author { get; set; } [XmlElement(ElementName = "date", Namespace = "")] public string Date { get; set; } } }
// // ListViewTestModule.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Gtk; using Hyena.Data; using Hyena.Collections; using Hyena.Gui; using Selection = Hyena.Collections.Selection; namespace Hyena.Data.Gui { [TestModule ("List View")] public class ListViewTestModule : Window { private View view; private Model model; public ListViewTestModule () : base ("ListView") { WindowPosition = WindowPosition.Center; SetDefaultSize (800, 600); ScrolledWindow scroll = new ScrolledWindow (); scroll.HscrollbarPolicy = PolicyType.Automatic; scroll.VscrollbarPolicy = PolicyType.Automatic; view = new View (); model = new Model (); scroll.Add (view); Add (scroll); ShowAll (); view.SetModel (model); } private class View : ListView<ModelItem> { public View () { ColumnController = new ColumnController (); ColumnController.AddRange ( new Column (String.Empty, new ColumnCellCheckBox ("F", true), 1), new Column ("Apples", new ColumnCellText ("B", true), 1), new Column ("Pears", new ColumnCellText ("C", true), 1), new Column ("How Hot", new ColumnCellRating ("G", true), 1), new Column ("Peaches", new ColumnCellText ("D", true), 1), new Column ("Doodle", new ColumnCellDoodle ("E", true), 1), new Column ("GUIDs!OMG", new ColumnCellText ("A", true), 1) ); } } private class Model : IListModel<ModelItem> { private List<ModelItem> store = new List<ModelItem> (); private Selection selection = new Selection (); public event EventHandler Cleared; public event EventHandler Reloaded; public Model () { Random random = new Random (0); for (int i = 0; i < 1000; i++) { store.Add (new ModelItem (i, random)); } } public void Clear () { } public void Reload () { } public int Count { get { return store.Count; } } public bool CanReorder { get { return false; } } public ModelItem this[int index] { get { return store[index]; } } public Selection Selection { get { return selection; } } } private class ModelItem { public ModelItem (int i, Random rand) { a = Guid.NewGuid ().ToString (); b = rand.Next (0, 255); c = rand.NextDouble (); d = String.Format ("Item {0}", i); e = new List<Gdk.Point> (); f = rand.Next (0, 1) == 1; g = rand.Next (0, 5); } string a; public string A { get { return a; } } int b; public int B { get { return b; } } double c; public double C { get { return c; } } string d; public string D { get { return d; } } List<Gdk.Point> e; public List<Gdk.Point> E { get { return e; } } bool f; public bool F { get { return f; } set { f = value; } } int g; public int G { get { return g; } set { g = value; } } } private class ColumnCellDoodle : ColumnCell, IInteractiveCell { private Random random = new Random (); private bool red = false; public ColumnCellDoodle (string property, bool expand) : base (property, expand) { } public override void Render (CellContext context, StateType state, double cellWidth, double cellHeight) { red = !red; Cairo.Context cr = context.Context; cr.Rectangle (0, 0, cellWidth, cellHeight); cr.Color = CairoExtensions.RgbaToColor (red ? 0xff000099 : 0x00000099); cr.Fill (); List<Gdk.Point> points = Points; for (int i = 0, n = points.Count; i < n; i++) { if (i == 0) { cr.MoveTo (points[i].X, points[i].Y); } else { cr.LineTo (points[i].X, points[i].Y); } } cr.Color = CairoExtensions.RgbToColor ((uint)random.Next (0xffffff)); cr.LineWidth = 1; cr.Stroke (); } private object last_pressed_bound; public bool ButtonEvent (int x, int y, bool pressed, Gdk.EventButton evnt) { if (!pressed) { last_pressed_bound = null; return false; } last_pressed_bound = BoundObject; Points.Add (new Gdk.Point (x, y)); return true; } public bool MotionEvent (int x, int y, Gdk.EventMotion evnt) { if (last_pressed_bound == BoundObject) { Points.Add (new Gdk.Point (x, y)); return true; } return false; } public bool PointerLeaveEvent () { last_pressed_bound = null; return true; } private List<Gdk.Point> Points { get { return (List<Gdk.Point>)BoundObject; } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Xml; using Microsoft.NodejsTools.Telemetry; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools; namespace Microsoft.NodejsTools.Project.ImportWizard { internal class ImportSettings : DependencyObject { public static readonly string DefaultLanguageExtensionsFilter = string.Join(";", new[] { ".txt", ".htm", ".html", ".css", ".png", ".jpg", ".gif", ".bmp", ".ico", ".svg", ".json", ".md", ".ejs", ".styl", ".xml", ".ts", Jade.JadeContentTypeDefinition.JadeFileExtension, Jade.JadeContentTypeDefinition.PugFileExtension }.Select(x => "*" + x)); private bool _isAutoGeneratedProjectPath; public ImportSettings() { this.TopLevelJavaScriptFiles = new BulkObservableCollection<string>(); this.Filters = DefaultLanguageExtensionsFilter; } public string ProjectPath { get { return (string)GetValue(ProjectPathProperty); } set { SetValue(ProjectPathProperty, value); } } public string SourcePath { get { return (string)GetValue(SourcePathProperty); } set { SetValue(SourcePathProperty, value); } } public string Filters { get { return (string)GetValue(FiltersProperty); } set { SetValue(FiltersProperty, value); } } public ObservableCollection<string> TopLevelJavaScriptFiles { get { return (ObservableCollection<string>)GetValue(TopLevelJavaScriptFilesProperty); } private set { SetValue(TopLevelJavaScriptFilesPropertyKey, value); } } public string StartupFile { get { return (string)GetValue(StartupFileProperty); } set { SetValue(StartupFileProperty, value); } } public static readonly DependencyProperty ProjectPathProperty = DependencyProperty.Register("ProjectPath", typeof(string), typeof(ImportSettings), new PropertyMetadata(ProjectPath_Updated)); public static readonly DependencyProperty SourcePathProperty = DependencyProperty.Register("SourcePath", typeof(string), typeof(ImportSettings), new PropertyMetadata(SourcePath_Updated)); public static readonly DependencyProperty FiltersProperty = DependencyProperty.Register("Filters", typeof(string), typeof(ImportSettings), new PropertyMetadata()); private static readonly DependencyPropertyKey TopLevelJavaScriptFilesPropertyKey = DependencyProperty.RegisterReadOnly("TopLevelJavaScriptFiles", typeof(ObservableCollection<string>), typeof(ImportSettings), new PropertyMetadata()); public static readonly DependencyProperty TopLevelJavaScriptFilesProperty = TopLevelJavaScriptFilesPropertyKey.DependencyProperty; public static readonly DependencyProperty StartupFileProperty = DependencyProperty.Register("StartupFile", typeof(string), typeof(ImportSettings), new PropertyMetadata()); public bool IsValid { get { return (bool)GetValue(IsValidProperty); } private set { SetValue(IsValidPropertyKey, value); } } private static void RecalculateIsValid(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!d.Dispatcher.CheckAccess()) { d.Dispatcher.Invoke((Action)(() => RecalculateIsValid(d, e))); return; } var s = d as ImportSettings; if (s == null) { d.SetValue(IsValidPropertyKey, false); return; } d.SetValue(IsValidPropertyKey, CommonUtils.IsValidPath(s.SourcePath) && CommonUtils.IsValidPath(s.ProjectPath) && Directory.Exists(s.SourcePath) ); } private static void SourcePath_Updated(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!d.Dispatcher.CheckAccess()) { d.Dispatcher.BeginInvoke((Action)(() => SourcePath_Updated(d, e))); return; } RecalculateIsValid(d, e); var s = d as ImportSettings; if (s == null) { return; } if (string.IsNullOrEmpty(s.ProjectPath) || s._isAutoGeneratedProjectPath) { s.ProjectPath = CommonUtils.GetAvailableFilename(s.SourcePath, Path.GetFileName(s.SourcePath), ".njsproj"); s._isAutoGeneratedProjectPath = true; } var sourcePath = s.SourcePath; if (Directory.Exists(sourcePath)) { var filters = s.Filters; var dispatcher = s.Dispatcher; // Nice async machinery does not work correctly in unit-tests, // so using Dispatcher directly. Task.Factory.StartNew(() => { var files = Directory.EnumerateFiles(sourcePath, "*.js", SearchOption.TopDirectoryOnly); if (filters.Split(';').Any(x => x.EndsWith(NodejsConstants.TypeScriptExtension, StringComparison.OrdinalIgnoreCase))) { files = Directory.EnumerateFiles( sourcePath, "*.ts", SearchOption.TopDirectoryOnly ).Concat(files); } var fileList = files.Select(f => Path.GetFileName(f)).ToList(); dispatcher.BeginInvoke((Action)(() => { var tlpf = s.TopLevelJavaScriptFiles as BulkObservableCollection<string>; if (tlpf != null) { tlpf.Clear(); tlpf.AddRange(fileList); } else { s.TopLevelJavaScriptFiles.Clear(); foreach (var file in fileList) { s.TopLevelJavaScriptFiles.Add(file); } } if (fileList.Contains("server.ts")) { s.StartupFile = "server.ts"; } else if (fileList.Contains("server.js")) { s.StartupFile = "server.js"; } else if (fileList.Contains("app.ts")) { s.StartupFile = "app.ts"; } else if (fileList.Contains("app.js")) { s.StartupFile = "app.js"; } else if (fileList.Count > 0) { s.StartupFile = fileList.First(); } })); }); } else { s.TopLevelJavaScriptFiles.Clear(); } } private static void ProjectPath_Updated(DependencyObject d, DependencyPropertyChangedEventArgs e) { var self = d as ImportSettings; if (self != null) { self._isAutoGeneratedProjectPath = false; } RecalculateIsValid(d, e); } private static readonly DependencyPropertyKey IsValidPropertyKey = DependencyProperty.RegisterReadOnly("IsValid", typeof(bool), typeof(ImportSettings), new PropertyMetadata(false)); public static readonly DependencyProperty IsValidProperty = IsValidPropertyKey.DependencyProperty; private static XmlWriter GetDefaultWriter(string projectPath) { var settings = new XmlWriterSettings { CloseOutput = true, Encoding = Encoding.UTF8, Indent = true, IndentChars = " ", NewLineChars = Environment.NewLine, NewLineOnAttributes = false }; var dir = Path.GetDirectoryName(projectPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } return XmlWriter.Create(projectPath, settings); } public string CreateRequestedProject() { var task = CreateRequestedProjectAsync(); task.Wait(); return task.Result; } public Task<string> CreateRequestedProjectAsync() { var projectPath = this.ProjectPath; var sourcePath = this.SourcePath; var filters = this.Filters; var startupFile = this.StartupFile; return Task.Run<string>(() => { var success = false; Guid projectGuid; try { string typeScriptVersion = GetLatestAvailableTypeScriptVersionFromSetup(); using (var writer = GetDefaultWriter(projectPath)) { WriteProjectXml(writer, projectPath, sourcePath, filters, startupFile, typeScriptVersion, true, out projectGuid); } TelemetryHelper.LogProjectImported(); success = true; return projectPath; } finally { if (!success) { try { File.Delete(projectPath); } catch { // Try and avoid leaving stray files, but it does // not matter much if we do. } } } }); } private static bool ShouldIncludeDirectory(string dirName) { // Why relative paths only? // Consider the following absolute path: // c:\sources\.dotted\myselectedfolder\routes\ // Where the folder selected in the wizard is: // c:\sources\.dotted\myselectedfolder\ // We don't want to exclude that folder from the project, despite a part // of that path having a dot prefix. // By evaluating relative paths only: // routes\ // We won't reject the folder. Debug.Assert(!Path.IsPathRooted(dirName)); return !dirName.Split(new char[] { '/', '\\' }).Any(name => name.StartsWith(".")); } internal static void WriteProjectXml( XmlWriter writer, string projectPath, string sourcePath, string filters, string startupFile, string typeScriptVersion, bool excludeNodeModules, out Guid projectGuid ) { var projectHome = CommonUtils.GetRelativeDirectoryPath(Path.GetDirectoryName(projectPath), sourcePath); projectGuid = Guid.NewGuid(); writer.WriteStartDocument(); writer.WriteStartElement("Project", "http://schemas.microsoft.com/developer/msbuild/2003"); writer.WriteAttributeString("DefaultTargets", "Build"); writer.WriteStartElement("PropertyGroup"); writer.WriteStartElement("Configuration"); writer.WriteAttributeString("Condition", " '$(Configuration)' == '' "); writer.WriteString("Debug"); writer.WriteEndElement(); writer.WriteElementString("SchemaVersion", "2.0"); writer.WriteElementString("ProjectGuid", projectGuid.ToString("B")); writer.WriteElementString("ProjectHome", projectHome); writer.WriteElementString("ProjectView", "ShowAllFiles"); if (CommonUtils.IsValidPath(startupFile)) { writer.WriteElementString("StartupFile", Path.GetFileName(startupFile)); } else { writer.WriteElementString("StartupFile", string.Empty); } writer.WriteElementString("WorkingDirectory", "."); writer.WriteElementString("OutputPath", "."); writer.WriteElementString("ProjectTypeGuids", "{3AF33F2E-1136-4D97-BBB7-1795711AC8B8};{349c5851-65df-11da-9384-00065b846f21};{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}"); var typeScriptSupport = EnumerateAllFiles(sourcePath, filters, excludeNodeModules) .Any(filename => NodejsConstants.TypeScriptExtension.Equals(Path.GetExtension(filename), StringComparison.OrdinalIgnoreCase)); if (typeScriptSupport) { writer.WriteElementString("TypeScriptSourceMap", "true"); writer.WriteElementString("TypeScriptModuleKind", "CommonJS"); writer.WriteElementString("EnableTypeScript", "true"); if (typeScriptVersion != null) { writer.WriteElementString("TypeScriptToolsVersion", typeScriptVersion); } } writer.WriteStartElement("VisualStudioVersion"); writer.WriteAttributeString("Condition", "'$(VisualStudioVersion)' == ''"); writer.WriteString("14.0"); writer.WriteEndElement(); writer.WriteStartElement("VSToolsPath"); writer.WriteAttributeString("Condition", "'$(VSToolsPath)' == ''"); writer.WriteString(@"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)"); writer.WriteEndElement(); writer.WriteEndElement(); // </PropertyGroup> // VS requires property groups with conditions for Debug // and Release configurations or many COMExceptions are // thrown. writer.WriteStartElement("PropertyGroup"); writer.WriteAttributeString("Condition", "'$(Configuration)' == 'Debug'"); writer.WriteEndElement(); writer.WriteStartElement("PropertyGroup"); writer.WriteAttributeString("Condition", "'$(Configuration)' == 'Release'"); writer.WriteEndElement(); var folders = new HashSet<string>( Directory.EnumerateDirectories(sourcePath, "*", SearchOption.AllDirectories) .Select(dirName => CommonUtils.TrimEndSeparator( CommonUtils.GetRelativeDirectoryPath(sourcePath, dirName) ) ) .Where(ShouldIncludeDirectory) ); // Exclude node_modules and bower_components folders. if (excludeNodeModules) { folders.RemoveWhere(NodejsConstants.ContainsNodeModulesOrBowerComponentsFolder); } writer.WriteStartElement("ItemGroup"); foreach (var file in EnumerateAllFiles(sourcePath, filters, excludeNodeModules)) { var ext = Path.GetExtension(file); if (NodejsConstants.JavaScriptExtension.Equals(ext, StringComparison.OrdinalIgnoreCase)) { writer.WriteStartElement("Compile"); } else if (NodejsConstants.TypeScriptExtension.Equals(ext, StringComparison.OrdinalIgnoreCase)) { writer.WriteStartElement("TypeScriptCompile"); } else { writer.WriteStartElement("Content"); } writer.WriteAttributeString("Include", file); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("ItemGroup"); foreach (var folder in folders.Where(s => !string.IsNullOrWhiteSpace(s)).OrderBy(s => s)) { writer.WriteStartElement("Folder"); writer.WriteAttributeString("Include", folder); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("Import"); writer.WriteAttributeString("Project", @"$(MSBuildToolsPath)\Microsoft.Common.targets"); writer.WriteAttributeString("Condition", @"Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"); writer.WriteEndElement(); writer.WriteComment("Do not delete the following Import Project. While this appears to do nothing it is a marker for setting TypeScript properties before our import that depends on them."); writer.WriteStartElement("Import"); writer.WriteAttributeString("Project", @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets"); writer.WriteAttributeString("Condition", @"False"); writer.WriteEndElement(); writer.WriteStartElement("Import"); writer.WriteAttributeString("Project", @"$(VSToolsPath)\Node.js Tools\Microsoft.NodejsTools.targets"); writer.WriteEndElement(); writer.WriteRaw(@" <ProjectExtensions> <VisualStudio> <FlavorProperties GUID=""{349c5851-65df-11da-9384-00065b846f21}""> <WebProjectProperties> <UseIIS>False</UseIIS> <AutoAssignPort>True</AutoAssignPort> <DevelopmentServerPort>0</DevelopmentServerPort> <DevelopmentServerVPath>/</DevelopmentServerVPath> <IISUrl>http://localhost:48022/</IISUrl> <NTLMAuthentication>False</NTLMAuthentication> <UseCustomServer>True</UseCustomServer> <CustomServerUrl>http://localhost:1337</CustomServerUrl> <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile> </WebProjectProperties> </FlavorProperties> <FlavorProperties GUID=""{349c5851-65df-11da-9384-00065b846f21}"" User=""""> <WebProjectProperties> <StartPageUrl> </StartPageUrl> <StartAction>CurrentPage</StartAction> <AspNetDebugging>True</AspNetDebugging> <SilverlightDebugging>False</SilverlightDebugging> <NativeDebugging>False</NativeDebugging> <SQLDebugging>False</SQLDebugging> <ExternalProgram> </ExternalProgram> <StartExternalURL> </StartExternalURL> <StartCmdLineArguments> </StartCmdLineArguments> <StartWorkingDirectory> </StartWorkingDirectory> <EnableENC>False</EnableENC> <AlwaysStartWebServerOnDebug>False</AlwaysStartWebServerOnDebug> </WebProjectProperties> </FlavorProperties> </VisualStudio> </ProjectExtensions> "); writer.WriteEndElement(); // </Project> writer.WriteEndDocument(); } private static IEnumerable<string> EnumerateAllFiles(string source, string filters, bool excludeNodeModules) { var files = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var patterns = filters.Split(';').Concat(new[] { "*.js" }).Select(p => p.Trim()).ToArray(); var directories = new List<string>() { source }; try { directories.AddRange( Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories) .Where(dirName => ShouldIncludeDirectory(CommonUtils.TrimEndSeparator(CommonUtils.GetRelativeDirectoryPath(source, dirName)))) ); } catch (UnauthorizedAccessException) { } foreach (var dir in directories) { if (excludeNodeModules && NodejsConstants.ContainsNodeModulesOrBowerComponentsFolder(dir)) { continue; } try { foreach (var filter in patterns) { files.UnionWith(Directory.EnumerateFiles(dir, filter, SearchOption.TopDirectoryOnly)); } } catch (UnauthorizedAccessException) { } } var res = files .Where(path => path.StartsWith(source, StringComparison.Ordinal)) .Select(path => path.Substring(source.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) .Distinct(StringComparer.OrdinalIgnoreCase); return res; } private const string tsSdkSetupPackageIdPrefix = "Microsoft.VisualStudio.Component.TypeScript."; private static string GetLatestAvailableTypeScriptVersionFromSetup() { var setupCompositionService = (IVsSetupCompositionService)CommonPackage.GetGlobalService(typeof(SVsSetupCompositionService)); // Populate the package status uint count = 0; uint sizeNeeded = 0; IVsSetupPackageInfo[] packages = null; setupCompositionService.GetSetupPackagesInfo(count, packages, out sizeNeeded); if (sizeNeeded > 0) { packages = new IVsSetupPackageInfo[sizeNeeded]; count = sizeNeeded; setupCompositionService.GetSetupPackagesInfo(count, packages, out sizeNeeded); return packages.Where(p => (__VsSetupPackageState)p.CurrentState == __VsSetupPackageState.INSTALL_PACKAGE_PRESENT) .Select(p => p.PackageId) .Where(p => p.StartsWith(tsSdkSetupPackageIdPrefix)) .Select(p => p.Substring(tsSdkSetupPackageIdPrefix.Length, p.Length - tsSdkSetupPackageIdPrefix.Length)) .OrderByDescending(v => v) .First(); } return ""; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Windows.Forms; using MigAz.Providers; using MigAz.Azure.Core.Interface; using System.Linq; using System.IO; using System.Threading.Tasks; using MigAz.Azure; using MigAz.Azure.UserControls; using MigAz.Azure.Generator.AsmToArm; using MigAz.Azure.Forms; using MigAz.Azure.Core; using System.Collections.Generic; using Newtonsoft.Json; namespace MigAz.Forms { public partial class MigAzForm : Form { #region Variables private List<AzureEnvironment> _AzureEnvironments = new List<AzureEnvironment>(); private List<AzureEnvironment> _UserDefinedAzureEnvironments = new List<AzureEnvironment>(); private Guid _AppSessionGuid = Guid.NewGuid(); private FileLogProvider _logProvider; private IStatusProvider _statusProvider; private AzureRetriever _AzureRetriever; private AppSettingsProvider _appSettingsProvider; private AzureTelemetryProvider _telemetryProvider = new AzureTelemetryProvider(); private TreeNode _EventSourceNode; private AzureContext _TargetAzureContext; private AzureGenerator _AzureGenerator; #endregion #region Constructors public MigAzForm() { InitializeComponent(); _logProvider = new FileLogProvider(); _logProvider.OnMessage += _logProvider_OnMessage; _statusProvider = new UIStatusProvider(this.toolStripStatusLabel1); _appSettingsProvider = new AppSettingsProvider(); _AzureEnvironments = AzureEnvironment.GetAzureEnvironments(); _AzureRetriever = new AzureRetriever(_logProvider, _statusProvider); _TargetAzureContext = new AzureContext(_AzureRetriever, _appSettingsProvider.GetTargetSettings(), app.Default.LoginPromptBehavior); _AzureGenerator = new AzureGenerator(_logProvider, _statusProvider); if (app.Default.UserDefinedAzureEnvironments != null && app.Default.UserDefinedAzureEnvironments != String.Empty) { _UserDefinedAzureEnvironments = JsonConvert.DeserializeObject<List<AzureEnvironment>>(app.Default.UserDefinedAzureEnvironments); } targetAzureContextViewer.Bind(_TargetAzureContext, _AzureRetriever, _AzureEnvironments, ref _UserDefinedAzureEnvironments); propertyPanel1.Clear(); splitContainer2.SplitterDistance = this.Height / 2; splitContainer3.SplitterDistance = splitContainer3.Width / 2; splitContainer4.SplitterDistance = 45; lblLastOutputRefresh.Text = String.Empty; txtDestinationFolder.Text = AppDomain.CurrentDomain.BaseDirectory; // Future thought, do away with the "Set"s and consolidate to a Bind? this.targetTreeView1.LogProvider = this.LogProvider; this.targetTreeView1.StatusProvider = this.StatusProvider; this.targetTreeView1.ImageList = this.imageList1; this.targetTreeView1.TargetSettings = _appSettingsProvider.GetTargetSettings(); this.propertyPanel1.TargetTreeView = targetTreeView1; this.propertyPanel1.PropertyChanged += PropertyPanel1_PropertyChanged; AlertIfNewVersionAvailable(); } #region New Version Check private async Task AlertIfNewVersionAvailable() { string currentVersion = "2.4.4.3"; VersionCheck versionCheck = new VersionCheck(this.LogProvider); string newVersionNumber = await versionCheck.GetAvailableVersion("https://migaz.azurewebsites.net/api/v2", currentVersion); if (versionCheck.IsVersionNewer(currentVersion, newVersionNumber)) { NewVersionAvailableDialog newVersionDialog = new NewVersionAvailableDialog(); newVersionDialog.Bind(currentVersion, newVersionNumber); newVersionDialog.ShowDialog(); } } #endregion #region Azure Migration Source Context Events private void MigrationSourceControl_ClearContext() { this.propertyPanel1.Clear(); this.targetTreeView1.Clear(); dgvMigAzMessages.DataSource = null; btnRefreshOutput.Enabled = false; btnExport.Enabled = false; foreach (TabPage t in tabOutputResults.TabPages) { tabOutputResults.TabPages.Remove(t); } } private async Task MigrationSourceControl_AfterNodeChecked(MigrationTarget sender) { TreeNode resultUpdateARMTree = await targetTreeView1.AddMigrationTarget(sender); } private async Task MigrationSourceControl_AfterNodeUnchecked(MigrationTarget sender) { await targetTreeView1.RemoveMigrationTarget(sender); } private async Task MigrationSourceControl_AfterNodeChanged(MigrationTarget sender) { await targetTreeView1.RefreshExportArtifacts(); } private async Task MigrationSourceControl_BeforeAzureTenantChange(AzureContext sender) { targetAzureContextViewer.ExistingContext = sender; } private async Task MigrationSourceControl_AfterAzureTenantChange(AzureContext sender) { targetAzureContextViewer.ExistingContext = sender; } private async Task MigrationSourceControl_AfterUserSignOut() { } private async Task MigrationSourceControl_BeforeUserSignOut() { } private async Task MigrationSourceControl_AfterAzureSubscriptionChange(AzureContext sender) { targetAzureContextViewer.ExistingContext = sender; } private async Task MigrationSourceControl_BeforeAzureSubscriptionChange(AzureContext sender) { targetAzureContextViewer.ExistingContext = sender; } private async Task MigrationSourceControl_UserAuthenticated(AzureContext sender) { targetAzureContextViewer.ExistingContext = sender; this.targetTreeView1.Enabled = true; } private async Task MigrationSourceControl_AzureEnvironmentChanged(AzureContext sender) { targetAzureContextViewer.ExistingContext = sender; } #endregion #region Form Objects private IMigrationSourceUserControl MigrationSourceControl { get { foreach (Control control in splitContainer3.Panel1.Controls) { if (control.GetType().GetInterfaces().Contains(typeof(IMigrationSourceUserControl))) { IMigrationSourceUserControl migrationSourceControl = (IMigrationSourceUserControl)control; return migrationSourceControl; } } return null; } } #endregion private async Task PropertyPanel1_PropertyChanged(Azure.Core.MigrationTarget migrationTarget) { TreeNode targetNode = this.targetTreeView1.SeekMigrationTargetTreeNode(migrationTarget); if (targetNode != null) { targetNode.Tag = migrationTarget; targetNode.Text = migrationTarget.ToString(); if (migrationTarget.GetType() == typeof(Azure.MigrationTarget.ResourceGroup)) targetNode.Name = migrationTarget.ToString(); } await this.targetTreeView1.RefreshExportArtifacts(); } private void _logProvider_OnMessage(string message) { txtLog.AppendText(message); txtLog.SelectionStart = txtLog.TextLength; } private void AzureRetriever_OnRestResult(AzureRestResponse response) { txtRest.AppendText(response.RequestGuid.ToString() + " " + response.Url + Environment.NewLine); txtRest.AppendText(response.Response + Environment.NewLine + Environment.NewLine); txtRest.SelectionStart = txtRest.TextLength; } #endregion #region Properties public AzureGenerator AzureGenerator { get { return _AzureGenerator; } } public ILogProvider LogProvider { get { return _logProvider; } } public IStatusProvider StatusProvider { get { return _statusProvider; } } internal AppSettingsProvider AppSettingsProvider { get { return _appSettingsProvider; } } #endregion #region Form Events private void MigAzForm_Load(object sender, EventArgs e) { _logProvider.WriteLog("MigAzForm_Load", "Program start"); this.Text = "MigAz"; } #endregion private void toolStripStatusLabel2_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("http://aka.ms/MigAz"); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void tabControl1_Resize(object sender, EventArgs e) { dgvMigAzMessages.Width = tabMigAzMonitoring.Width - 10; dgvMigAzMessages.Height = tabMigAzMonitoring.Height - 30; txtLog.Width = tabMigAzMonitoring.Width - 10; txtLog.Height = tabMigAzMonitoring.Height - 30; txtRest.Width = tabMigAzMonitoring.Width - 10; txtRest.Height = tabMigAzMonitoring.Height - 30; } private void panel1_Resize(object sender, EventArgs e) { btnExport.Width = panel1.Width - 15; btnChoosePath.Left = panel1.Width - btnChoosePath.Width - 10; txtDestinationFolder.Width = panel1.Width - btnChoosePath.Width - 30; } private void reportAnIssueOnGithubToolStripMenuItem_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("https://github.com/Azure/migAz/issues/new"); } private void visitMigAzOnGithubToolStripMenuItem_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("https://aka.ms/migaz"); } private async void btnExport_Click_1Async(object sender, EventArgs e) { // We are refreshing both the MemoryStreams and the Output Tabs via this call, prior to writing to files if (await RefreshOutput()) { if (this.AzureGenerator != null) { this.AzureGenerator.OutputDirectory = txtDestinationFolder.Text; this.AzureGenerator.Write(); StatusProvider.UpdateStatus("Ready"); var exportResults = new ExportResultsDialog(this.AzureGenerator); exportResults.ShowDialog(this); } } } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { TargetTreeView targetTreeView = this.targetTreeView1; if (targetTreeView != null && e.RowIndex > -1) { object alert = dgvMigAzMessages.Rows[e.RowIndex].Cells["SourceObject"].Value; targetTreeView.SeekAlertSource(alert); } } private void tabOutputResults_Resize(object sender, EventArgs e) { foreach (TabPage tabPage in tabOutputResults.TabPages) { foreach (Control control in tabPage.Controls) { control.Width = tabOutputResults.Width - 15; control.Height = tabOutputResults.Height - 30; } } } private void optionsToolStripMenuItem_Click(object sender, EventArgs e) { OptionsDialog optionsDialog = new OptionsDialog(); optionsDialog.Bind(_AzureEnvironments, _UserDefinedAzureEnvironments); optionsDialog.ShowDialog(); IMigrationSourceUserControl sourceUserControl = this.MigrationSourceControl; if (sourceUserControl != null) { if (sourceUserControl.GetType() == typeof(MigrationAzureSourceContext)) { MigrationAzureSourceContext migrationAzureSourceContext = (MigrationAzureSourceContext)sourceUserControl; migrationAzureSourceContext.AzureContext.LoginPromptBehavior = app.Default.LoginPromptBehavior; } } } private void btnChoosePath_Click(object sender, EventArgs e) { DialogResult result = folderBrowserDialog1.ShowDialog(); if (result == DialogResult.OK) txtDestinationFolder.Text = folderBrowserDialog1.SelectedPath; } private async void btnRefreshOutput_Click(object sender, EventArgs e) { await RefreshOutput(); } private async Task<bool> RefreshOutput() { if (await AssertHasTargetErrors()) { return false; } IMigrationSourceUserControl migrationSourceControl = this.MigrationSourceControl; if (migrationSourceControl == null) throw new ArgumentException("Unable to Refresh Output: NULL MigrationSourceControl Context"); if (targetAzureContextViewer.ExistingContext == null) throw new ArgumentException("Unable to Refresh Output: NULL Target Existing Azure Context"); if (targetAzureContextViewer.ExistingContext.AzureSubscription == null) throw new ArgumentException("Unable to Refresh Output: NULL Target Existing Azure Context"); if (this.AzureGenerator == null) throw new ArgumentException("Unable to Refresh Output: NULL TemplateGenerator"); if (this.targetAzureContextViewer == null) throw new ArgumentException("Unable to Refresh Output: NULL TargetAzureContextViewer"); if (this.targetAzureContextViewer.SelectedAzureContext == null) throw new ArgumentException("Unable to Refresh Output: NULL SelectedAzureContext on TargetAzureContextViewer"); if (this.targetAzureContextViewer.SelectedAzureContext.TokenProvider == null) throw new ArgumentException("Unable to Refresh Output: NULL TokenProvider on SelectedAzureContext"); if (this.AzureGenerator != null) { this.AzureGenerator.AccessSASTokenLifetimeSeconds = app.Default.AccessSASTokenLifetimeSeconds; this.AzureGenerator.ExportArtifacts = this.targetTreeView1.ExportArtifacts; this.AzureGenerator.OutputDirectory = this.txtDestinationFolder.Text; this.AzureGenerator.TargetAzureTokenProvider = (AzureTokenProvider)this.targetAzureContextViewer.SelectedAzureContext.TokenProvider; await this.AzureGenerator.GenerateStreams(); foreach (TabPage tabPage in tabOutputResults.TabPages) { if (!this.AzureGenerator.TemplateStreams.ContainsKey(tabPage.Name)) tabOutputResults.TabPages.Remove(tabPage); } foreach (var templateStream in this.AzureGenerator.TemplateStreams) { TabPage tabPage = null; if (!tabOutputResults.TabPages.ContainsKey(templateStream.Key)) { tabPage = new TabPage(templateStream.Key); tabPage.Name = templateStream.Key; tabOutputResults.TabPages.Add(tabPage); if (templateStream.Key.EndsWith(".html")) { WebBrowser webBrowser = new WebBrowser(); webBrowser.Width = tabOutputResults.Width - 15; webBrowser.Height = tabOutputResults.Height - 30; webBrowser.AllowNavigation = false; webBrowser.ScrollBarsEnabled = true; tabPage.Controls.Add(webBrowser); } else if (templateStream.Key.EndsWith(".json") || templateStream.Key.EndsWith(".ps1")) { TextBox textBox = new TextBox(); textBox.Width = tabOutputResults.Width - 15; textBox.Height = tabOutputResults.Height - 30; textBox.ReadOnly = true; textBox.Multiline = true; textBox.WordWrap = false; textBox.ScrollBars = ScrollBars.Both; tabPage.Controls.Add(textBox); } } else { tabPage = tabOutputResults.TabPages[templateStream.Key]; } if (tabPage.Controls[0].GetType() == typeof(TextBox)) { TextBox textBox = (TextBox)tabPage.Controls[0]; templateStream.Value.Position = 0; textBox.Text = new StreamReader(templateStream.Value).ReadToEnd(); } else if (tabPage.Controls[0].GetType() == typeof(WebBrowser)) { WebBrowser webBrowser = (WebBrowser)tabPage.Controls[0]; templateStream.Value.Position = 0; if (webBrowser.Document == null) { webBrowser.DocumentText = new StreamReader(templateStream.Value).ReadToEnd(); } else { webBrowser.Document.OpenNew(true); webBrowser.Document.Write(new StreamReader(templateStream.Value).ReadToEnd()); } } } if (tabOutputResults.TabPages.Count != this.AzureGenerator.TemplateStreams.Count) throw new ArgumentException("Count mismatch between tabOutputResults TabPages and Migrator TemplateStreams. Counts should match after addition/removal above. tabOutputResults. TabPages Count: " + tabOutputResults.TabPages.Count + " Migration TemplateStream Count: " + this.AzureGenerator.TemplateStreams.Count); // Ensure Tabs are in same order as output streams int streamIndex = 0; foreach (string templateStreamKey in this.AzureGenerator.TemplateStreams.Keys) { int rotationCounter = 0; // This while loop is to bubble the tab to the end, as to rotate the tab sequence to ensure they match the order returned from the stream outputs // The addition/removal of Streams may result in order of existing tabPages being "out of order" to the streams generated, so we may need to consider reordering while (tabOutputResults.TabPages[streamIndex].Name != templateStreamKey) { TabPage currentTabpage = tabOutputResults.TabPages[streamIndex]; tabOutputResults.TabPages.Remove(currentTabpage); tabOutputResults.TabPages.Add(currentTabpage); rotationCounter++; if (rotationCounter > this.AzureGenerator.TemplateStreams.Count) throw new ArgumentException("Rotated through all tabs, unabled to locate tab '" + templateStreamKey + "' while ensuring tab order/sequencing."); } streamIndex++; } lblLastOutputRefresh.Text = "Last Refresh Completed: " + DateTime.Now.ToString(); btnRefreshOutput.Enabled = false; // post Telemetry Record to ASMtoARMToolAPI if (AppSettingsProvider.AllowTelemetry) { StatusProvider.UpdateStatus("BUSY: saving telemetry information"); _telemetryProvider.PostTelemetryRecord(_AppSessionGuid, this.MigrationSourceControl.MigrationSourceType, targetAzureContextViewer.ExistingContext.AzureSubscription, this.AzureGenerator); } } StatusProvider.UpdateStatus("Ready"); return true; } #region Split Container Resize Events private void splitContainer1_Panel2_Resize(object sender, EventArgs e) { propertyPanel1.Width = splitContainer1.Panel2.Width - 10; propertyPanel1.Height = splitContainer1.Panel2.Height - 100; panel1.Top = splitContainer1.Panel2.Height - panel1.Height - 15; panel1.Width = splitContainer1.Panel2.Width; } private void splitContainer2_Panel1_Resize(object sender, EventArgs e) { if (splitContainer2.Panel1.Controls.Count == 1) { if (splitContainer2.Panel1.Height < 300) splitContainer2.Panel1.Controls[0].Height = 300; else splitContainer2.Panel1.Controls[0].Height = splitContainer2.Panel1.Height - 20; } } private void splitContainer2_Panel2_Resize(object sender, EventArgs e) { this.tabMigAzMonitoring.Width = splitContainer2.Panel2.Width - 5; this.tabMigAzMonitoring.Height = splitContainer2.Panel2.Height - 5; this.tabOutputResults.Width = splitContainer2.Panel2.Width - 5; this.tabOutputResults.Height = splitContainer2.Panel2.Height - 55; } private void splitContainer3_Panel1_Resize(object sender, EventArgs e) { foreach (Control control in splitContainer3.Panel1.Controls) { if (splitContainer3.Panel1.Height < 300) control.Height = 300; else control.Height = splitContainer3.Panel1.Height - 10; control.Width = splitContainer3.Panel1.Width - 10; } } private void splitContainer3_Panel2_Resize(object sender, EventArgs e) { if (splitContainer3.Panel2.Controls.Count == 1) { if (splitContainer3.Panel2.Height < 300) splitContainer3.Panel2.Controls[0].Height = 300; else splitContainer3.Panel2.Controls[0].Height = splitContainer3.Panel2.Height - 20; splitContainer3.Panel2.Controls[0].Width = splitContainer3.Panel2.Width - 20; } } private void splitContainer4_Panel2_Resize(object sender, EventArgs e) { foreach (Control control in splitContainer4.Panel2.Controls) { control.Width = splitContainer4.Panel2.Width; control.Height = splitContainer4.Panel2.Height; } } private void splitContainer4_Panel1_Resize(object sender, EventArgs e) { foreach (Control control in splitContainer4.Panel1.Controls) { control.Width = splitContainer4.Panel1.Width - 10; control.Height = splitContainer4.Panel1.Height; } } #endregion #region Source and Target Context Selection Events + Methods private bool MigrationSourceSelectionControlVisible { get { foreach (Control control in splitContainer3.Panel1.Controls) { if (control.GetType() == typeof(UserControls.MigAzMigrationSourceSelection)) { return control.Visible; } } return false; } set { foreach (Control control in splitContainer3.Panel1.Controls) { if (control.GetType() == typeof(UserControls.MigAzMigrationSourceSelection)) { control.Visible = value; control.Enabled = value; } } } } private async void migAzMigrationSourceSelection1_AfterMigrationSourceSelected(UserControl migrationSourceUserControl) { if (migrationSourceUserControl.GetType() == typeof(MigrationAzureSourceContext)) { MigrationAzureSourceContext azureControl = (MigrationAzureSourceContext)migrationSourceUserControl; // This will move to be based on the source context (upon instantiation) azureControl.Bind(this._AzureRetriever, this._statusProvider, this._logProvider, this._appSettingsProvider.GetTargetSettings(), this.imageList1, app.Default.LoginPromptBehavior, this._AzureEnvironments, ref this._UserDefinedAzureEnvironments); azureControl.AzureContext.AzureEnvironment = GetDefaultAzureEnvironment(); azureControl.AzureEnvironmentChanged += MigrationSourceControl_AzureEnvironmentChanged; azureControl.UserAuthenticated += MigrationSourceControl_UserAuthenticated; azureControl.BeforeAzureSubscriptionChange += MigrationSourceControl_BeforeAzureSubscriptionChange; azureControl.AfterAzureSubscriptionChange += MigrationSourceControl_AfterAzureSubscriptionChange; azureControl.BeforeUserSignOut += MigrationSourceControl_BeforeUserSignOut; azureControl.AfterUserSignOut += MigrationSourceControl_AfterUserSignOut; azureControl.AfterAzureTenantChange += MigrationSourceControl_AfterAzureTenantChange; azureControl.BeforeAzureTenantChange += MigrationSourceControl_BeforeAzureTenantChange; azureControl.AfterNodeChecked += MigrationSourceControl_AfterNodeChecked; azureControl.AfterNodeUnchecked += MigrationSourceControl_AfterNodeUnchecked; azureControl.AfterNodeChanged += MigrationSourceControl_AfterNodeChanged; azureControl.ClearContext += MigrationSourceControl_ClearContext; azureControl.AfterContextChanged += AzureControl_AfterContextChanged; azureControl.AzureContext.AzureRetriever.OnRestResult += AzureRetriever_OnRestResult; } MigrationSourceSelectionControlVisible = false; splitContainer3.Panel1.Controls.Add(migrationSourceUserControl); migrationSourceUserControl.Top = 5; migrationSourceUserControl.Left = 5; splitContainer3_Panel1_Resize(this, null); } private AzureEnvironment GetDefaultAzureEnvironment() { AzureEnvironment defaultAzureEnvironment; if (_AzureEnvironments != null) { defaultAzureEnvironment = _AzureEnvironments.Where(a => a.Name == app.Default.AzureEnvironment).FirstOrDefault(); if (defaultAzureEnvironment != null) return defaultAzureEnvironment; } if (_UserDefinedAzureEnvironments != null) { defaultAzureEnvironment = _UserDefinedAzureEnvironments.Where(a => a.Name == app.Default.AzureEnvironment).FirstOrDefault(); if (defaultAzureEnvironment != null) return defaultAzureEnvironment; } return null; } private async void AzureControl_AfterContextChanged(UserControl sender) { IMigrationSourceUserControl migrationSourceUserControl = (IMigrationSourceUserControl)sender; targetAzureContextViewer.Enabled = migrationSourceUserControl.IsSourceContextAuthenticated; if (migrationSourceUserControl != null && migrationSourceUserControl.GetType() == typeof(MigrationAzureSourceContext)) { MigrationAzureSourceContext azureSourceContext = (MigrationAzureSourceContext)migrationSourceUserControl; targetAzureContextViewer.ExistingContext = azureSourceContext.AzureContext; } } #endregion public async Task<bool> AssertHasTargetErrors() { // Refresh output first, await, to ensure subsequence call for HasErrors has updated status. await this.targetTreeView1.RefreshExportArtifacts(); if (this.targetTreeView1.HasErrors) { tabMigAzMonitoring.SelectTab("tabMessages"); MessageBox.Show("There are still one or more error(s) with the template generation. Please resolve all errors before exporting."); } return this.targetTreeView1.HasErrors; } #region Target Tree View Events private async Task targetTreeView1_AfterNewTargetResourceAdded(TargetTreeView sender, TreeNode selectedNode) { // Refresh Alerts from new item await targetTreeView1_AfterExportArtifactRefresh(sender); } private async Task targetTreeView1_AfterExportArtifactRefresh(TargetTreeView sender) { dgvMigAzMessages.DataSource = sender.Alerts.Select(x => new { AlertType = x.AlertType, Message = x.Message, SourceObject = x.SourceObject }).ToList(); dgvMigAzMessages.Columns["Message"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dgvMigAzMessages.Columns["SourceObject"].Visible = false; // WordWrap Message Column dgvMigAzMessages.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders; dgvMigAzMessages.Columns["Message"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; dgvMigAzMessages.Columns["Message"].DefaultCellStyle.WrapMode = DataGridViewTriState.True; dgvMigAzMessages.Columns["Message"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; btnRefreshOutput.Enabled = true; btnExport.Enabled = true; await RebindPropertyPanel(); } private async Task RebindPropertyPanel() { //if (this.targetTreeView1 != null && this.targetTreeView1.SelectedNode != null) // await BindPropertyPanel(this.targetTreeView1, this.targetTreeView1.SelectedNode); } private async Task BindPropertyPanel(TargetTreeView targetTreeView, TreeNode selectedNode) { await propertyPanel1.Bind((MigrationTarget)selectedNode.Tag); } private async Task targetTreeView1_AfterTargetSelected(TargetTreeView targetTreeView, TreeNode selectedNode) { try { if (this.LogProvider != null) LogProvider.WriteLog("Control_AfterTargetSelected", "Start"); _EventSourceNode = selectedNode; await BindPropertyPanel(targetTreeView, selectedNode); _EventSourceNode = null; if (this.LogProvider != null) LogProvider.WriteLog("Control_AfterTargetSelected", "End"); if (this.StatusProvider != null) StatusProvider.UpdateStatus("Ready"); } catch (Exception exc) { UnhandledExceptionDialog unhandledExceptionDialog = new UnhandledExceptionDialog(this.LogProvider, exc); unhandledExceptionDialog.ShowDialog(); } } private async Task targetTreeView1_AfterSourceNodeRemoved(TargetTreeView sender, TreeNode removedNode) { if (this.LogProvider != null) LogProvider.WriteLog("targetTreeView1_AfterSourceNodeRemoved", "Start"); if (removedNode.Tag != null) { MigrationTarget migrationTarget = (MigrationTarget)removedNode.Tag; await this.MigrationSourceControl.UncheckMigrationTarget(migrationTarget); } if (this.LogProvider != null) LogProvider.WriteLog("targetTreeView1_AfterSourceNodeRemoved", "End"); } #endregion private void menuitemAzureEnvironments_Click(object sender, EventArgs e) { AzureEnvironmentDialog azureEnvironmentDialog = new AzureEnvironmentDialog(); azureEnvironmentDialog.Bind(_AzureRetriever, _AzureEnvironments, ref _UserDefinedAzureEnvironments); azureEnvironmentDialog.ShowDialog(); // Save User Defined Azure Environments to App Settings app.Default.UserDefinedAzureEnvironments = JsonConvert.SerializeObject(_UserDefinedAzureEnvironments); app.Default.Save(); } private async Task targetAzureContextViewer_AfterContextChanged(AzureLoginContextViewer sender) { if (sender.SelectedAzureContext.AzureSubscription != null) { await sender.SelectedAzureContext.AzureSubscription.InitializeChildrenAsync(); await sender.SelectedAzureContext.AzureSubscription.BindArmResources(targetTreeView1.TargetSettings); } targetTreeView1.TargetBlobStorageNamespace = sender.SelectedAzureContext.AzureEnvironment.BlobEndpointUrl; targetTreeView1.TargetSubscription = sender.SelectedAzureContext.AzureSubscription; await this.targetTreeView1.RefreshExportArtifacts(); } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Diagnostics; namespace SpyUO { public class About : System.Windows.Forms.Form { private System.Windows.Forms.Label lEditor; private System.Windows.Forms.Label lPhenos; private System.Windows.Forms.Label lEmail; private System.Windows.Forms.LinkLabel llUodreams; private PictureBox pictureBox1; private GroupBox groupBox1; private GroupBox groupBox2; private Label label3; private Label label4; private Label label5; private Label label1; private Button button1; private System.ComponentModel.Container components = null; public About() { InitializeComponent(); Text = Display.Title; } protected override void Dispose( bool disposing ) { if ( disposing ) { if ( components != null ) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Metodo necessario per il supporto della finestra di progettazione. Non modificare /// il contenuto del metodo con l'editor di codice. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(About)); this.lEditor = new System.Windows.Forms.Label(); this.lPhenos = new System.Windows.Forms.Label(); this.lEmail = new System.Windows.Forms.Label(); this.llUodreams = new System.Windows.Forms.LinkLabel(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // lEditor // this.lEditor.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lEditor.Location = new System.Drawing.Point(6, 26); this.lEditor.Name = "lEditor"; this.lEditor.Size = new System.Drawing.Size(82, 16); this.lEditor.TabIndex = 0; this.lEditor.Text = "Written by:"; this.lEditor.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // lPhenos // this.lPhenos.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lPhenos.Location = new System.Drawing.Point(94, 26); this.lPhenos.Name = "lPhenos"; this.lPhenos.Size = new System.Drawing.Size(168, 16); this.lPhenos.TabIndex = 1; this.lPhenos.Text = "Lorenzo \"Phenos\" Castelli"; // // lEmail // this.lEmail.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lEmail.Location = new System.Drawing.Point(6, 51); this.lEmail.Name = "lEmail"; this.lEmail.Size = new System.Drawing.Size(72, 16); this.lEmail.TabIndex = 2; this.lEmail.Text = "E-Mail:"; this.lEmail.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // llUodreams // this.llUodreams.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.llUodreams.LinkArea = new System.Windows.Forms.LinkArea(0, 22); this.llUodreams.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.llUodreams.Location = new System.Drawing.Point(94, 51); this.llUodreams.Name = "llUodreams"; this.llUodreams.Size = new System.Drawing.Size(168, 16); this.llUodreams.TabIndex = 3; this.llUodreams.TabStop = true; this.llUodreams.Text = "gcastelli@racine.ra.it"; this.llUodreams.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.llUodreams_LinkClicked); // // pictureBox1 // this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(12, 12); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(100, 100); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox1.TabIndex = 6; this.pictureBox1.TabStop = false; // // groupBox1 // this.groupBox1.Controls.Add(this.lEditor); this.groupBox1.Controls.Add(this.lPhenos); this.groupBox1.Controls.Add(this.lEmail); this.groupBox1.Controls.Add(this.llUodreams); this.groupBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox1.Location = new System.Drawing.Point(131, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(268, 88); this.groupBox1.TabIndex = 7; this.groupBox1.TabStop = false; this.groupBox1.Text = "SpyUO - Original Version"; // // groupBox2 // this.groupBox2.Controls.Add(this.label1); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox2.Location = new System.Drawing.Point(131, 112); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(268, 88); this.groupBox2.TabIndex = 8; this.groupBox2.TabStop = false; this.groupBox2.Text = "SpyUO - Mod KR Version"; // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(94, 51); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(72, 16); this.label1.TabIndex = 3; this.label1.Text = "- none -"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label3 // this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(6, 26); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(82, 16); this.label3.TabIndex = 0; this.label3.Text = "Written by:"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label4 // this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(94, 26); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(168, 16); this.label4.TabIndex = 1; this.label4.Text = "Two Unknown Guys"; // // label5 // this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.Location = new System.Drawing.Point(6, 51); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(72, 16); this.label5.TabIndex = 2; this.label5.Text = "E-Mail:"; this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // button1 // this.button1.Location = new System.Drawing.Point(157, 217); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(104, 28); this.button1.TabIndex = 9; this.button1.Text = "OK"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // About // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(420, 257); this.Controls.Add(this.button1); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.pictureBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "About"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private void llUodreams_LinkClicked( object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e ) { ProcessStartInfo info = new ProcessStartInfo( "\"mailto:gcastelli@racine.ra.it\"" ); info.UseShellExecute = true; info.ErrorDialog = true; System.Diagnostics.Process.Start( info ); } private void button1_Click(object sender, EventArgs e) { this.Close(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Xml.Serialization { using System.Collections; using System.Collections.Generic; using System.IO; using System; using System.Globalization; using System.ComponentModel; using Microsoft.Xml.Serialization; using Microsoft.Xml.Schema; using System.Diagnostics; using System.Threading; // using System.Security.Permissions; // using System.Security.Policy; using System.Security; using System.Net; using System.Reflection; using Microsoft.Xml; /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas"]/*' /> /// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlSchemas : CollectionBase, IEnumerable<XmlSchema> { private XmlSchemaSet _schemaSet; private Hashtable _references; private SchemaObjectCache _cache; // cached schema top-level items private bool _shareTypes; private Hashtable _mergedSchemas; internal Hashtable delayedSchemas = new Hashtable(); private bool _isCompiled = false; private static volatile XmlSchema s_xsd; private static volatile XmlSchema s_xml; /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.this"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSchema this[int index] { get { return (XmlSchema)List[index]; } set { List[index] = value; } } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.this1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSchema this[string ns] { get { IList values = (IList)SchemaSet.Schemas(ns); if (values.Count == 0) return null; if (values.Count == 1) return (XmlSchema)values[0]; throw new InvalidOperationException(string.Format(ResXml.XmlSchemaDuplicateNamespace, ns)); } } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.GetSchemas"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public IList GetSchemas(string ns) { return (IList)SchemaSet.Schemas(ns); } internal SchemaObjectCache Cache { get { if (_cache == null) _cache = new SchemaObjectCache(); return _cache; } } internal Hashtable MergedSchemas { get { if (_mergedSchemas == null) _mergedSchemas = new Hashtable(); return _mergedSchemas; } } internal Hashtable References { get { if (_references == null) _references = new Hashtable(); return _references; } } internal XmlSchemaSet SchemaSet { get { if (_schemaSet == null) { _schemaSet = new XmlSchemaSet(); _schemaSet.XmlResolver = null; _schemaSet.ValidationEventHandler += new ValidationEventHandler(IgnoreCompileErrors); } return _schemaSet; } } internal int Add(XmlSchema schema, bool delay) { if (delay) { if (delayedSchemas[schema] == null) delayedSchemas.Add(schema, schema); return -1; } else { return Add(schema); } } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Add"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int Add(XmlSchema schema) { if (List.Contains(schema)) return List.IndexOf(schema); return List.Add(schema); } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Add"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int Add(XmlSchema schema, Uri baseUri) { if (List.Contains(schema)) return List.IndexOf(schema); if (baseUri != null) schema.BaseUri = baseUri; return List.Add(schema); } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Add1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Add(XmlSchemas schemas) { foreach (XmlSchema schema in schemas) { Add(schema); } } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.AddReference"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void AddReference(XmlSchema schema) { References[schema] = schema; } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Insert"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Insert(int index, XmlSchema schema) { List.Insert(index, schema); } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.IndexOf"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int IndexOf(XmlSchema schema) { return List.IndexOf(schema); } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Contains"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool Contains(XmlSchema schema) { return List.Contains(schema); } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Contains1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool Contains(string targetNamespace) { return SchemaSet.Contains(targetNamespace); } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Remove"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Remove(XmlSchema schema) { List.Remove(schema); } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.CopyTo"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void CopyTo(XmlSchema[] array, int index) { List.CopyTo(array, index); } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.OnInsert"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected override void OnInsert(int index, object value) { AddName((XmlSchema)value); } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.OnRemove"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected override void OnRemove(int index, object value) { RemoveName((XmlSchema)value); } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.OnClear"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected override void OnClear() { _schemaSet = null; } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.OnSet"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected override void OnSet(int index, object oldValue, object newValue) { RemoveName((XmlSchema)oldValue); AddName((XmlSchema)newValue); } private void AddName(XmlSchema schema) { if (_isCompiled) throw new InvalidOperationException(ResXml.XmlSchemaCompiled); if (SchemaSet.Contains(schema)) SchemaSet.Reprocess(schema); else { Prepare(schema); SchemaSet.Add(schema); } } private void Prepare(XmlSchema schema) { // need to remove illegal <import> externals; ArrayList removes = new ArrayList(); string ns = schema.TargetNamespace; foreach (XmlSchemaExternal external in schema.Includes) { if (external is XmlSchemaImport) { if (ns == ((XmlSchemaImport)external).Namespace) { removes.Add(external); } } } foreach (XmlSchemaObject o in removes) { schema.Includes.Remove(o); } } private void RemoveName(XmlSchema schema) { SchemaSet.Remove(schema); } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Find"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Find(XmlQualifiedName name, Type type) { return Find(name, type, true); } internal object Find(XmlQualifiedName name, Type type, bool checkCache) { if (!IsCompiled) { foreach (XmlSchema schema in List) { Preprocess(schema); } } IList values = (IList)SchemaSet.Schemas(name.Namespace); if (values == null) return null; foreach (XmlSchema schema in values) { Preprocess(schema); XmlSchemaObject ret = null; if (typeof(XmlSchemaType).IsAssignableFrom(type)) { ret = schema.SchemaTypes[name]; if (ret == null || !type.IsAssignableFrom(ret.GetType())) { continue; } } else if (type == typeof(XmlSchemaGroup)) { ret = schema.Groups[name]; } else if (type == typeof(XmlSchemaAttributeGroup)) { ret = schema.AttributeGroups[name]; } else if (type == typeof(XmlSchemaElement)) { ret = schema.Elements[name]; } else if (type == typeof(XmlSchemaAttribute)) { ret = schema.Attributes[name]; } else if (type == typeof(XmlSchemaNotation)) { ret = schema.Notations[name]; } #if DEBUG else { // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe throw new InvalidOperationException(string.Format(ResXml.XmlInternalErrorDetails, "XmlSchemas.Find: Invalid object type " + type.FullName)); } #endif if (ret != null && _shareTypes && checkCache && !IsReference(ret)) ret = Cache.AddItem(ret, name, this); if (ret != null) { return ret; } } return null; } IEnumerator<XmlSchema> IEnumerable<XmlSchema>.GetEnumerator() { return new XmlSchemaEnumerator(this); } internal static void Preprocess(XmlSchema schema) { if (!schema.IsPreprocessed) { try { XmlNameTable nameTable = new Microsoft.Xml.NameTable(); Preprocessor prep = new Preprocessor(nameTable, new SchemaNames(nameTable), null); prep.SchemaLocations = new Hashtable(); prep.Execute(schema, schema.TargetNamespace, false); } catch (XmlSchemaException e) { throw CreateValidationException(e, e.Message); } } } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.IsDataSet"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static bool IsDataSet(XmlSchema schema) { foreach (XmlSchemaObject o in schema.Items) { if (o is XmlSchemaElement) { XmlSchemaElement e = (XmlSchemaElement)o; if (e.UnhandledAttributes != null) { foreach (XmlAttribute a in e.UnhandledAttributes) { if (a.LocalName == "IsDataSet" && a.NamespaceURI == "urn:schemas-microsoft-com:xml-msdata") { // currently the msdata:IsDataSet uses its own format for the boolean values if (a.Value == "True" || a.Value == "true" || a.Value == "1") return true; } } } } } return false; } private void Merge(XmlSchema schema) { if (MergedSchemas[schema] != null) return; IList originals = (IList)SchemaSet.Schemas(schema.TargetNamespace); if (originals != null && originals.Count > 0) { MergedSchemas.Add(schema, schema); Merge(originals, schema); } else { Add(schema); MergedSchemas.Add(schema, schema); } } private void AddImport(IList schemas, string ns) { foreach (XmlSchema s in schemas) { bool add = true; foreach (XmlSchemaExternal external in s.Includes) { if (external is XmlSchemaImport && ((XmlSchemaImport)external).Namespace == ns) { add = false; break; } } if (add) { XmlSchemaImport import = new XmlSchemaImport(); import.Namespace = ns; s.Includes.Add(import); } } } private void Merge(IList originals, XmlSchema schema) { foreach (XmlSchema s in originals) { if (schema == s) { return; } } foreach (XmlSchemaExternal external in schema.Includes) { if (external is XmlSchemaImport) { external.SchemaLocation = null; if (external.Schema != null) { Merge(external.Schema); } else { AddImport(originals, ((XmlSchemaImport)external).Namespace); } } else { if (external.Schema == null) { // we do not process includes or redefines by the schemaLocation if (external.SchemaLocation != null) { throw new InvalidOperationException(string.Format(ResXml.XmlSchemaIncludeLocation, this.GetType().Name, external.SchemaLocation)); } } else { external.SchemaLocation = null; Merge(originals, external.Schema); } } } // bring all included items to the parent schema; bool[] matchedItems = new bool[schema.Items.Count]; int count = 0; for (int i = 0; i < schema.Items.Count; i++) { XmlSchemaObject o = schema.Items[i]; XmlSchemaObject dest = Find(o, originals); if (dest != null) { if (!Cache.Match(dest, o, _shareTypes)) { // UNDONE remove denug only code before shipping // Debug.WriteLineIf(DiagnosticsSwitches.XmlSerialization.TraceVerbose, "XmlSerialization::Failed to Merge " + MergeFailedMessage(o, dest, schema.TargetNamespace) // + "' Plase Compare hash:\r\n" + Cache.looks[dest] + "\r\n" + Cache.looks[o]); throw new InvalidOperationException(MergeFailedMessage(o, dest, schema.TargetNamespace)); } matchedItems[i] = true; count++; } } if (count != schema.Items.Count) { XmlSchema destination = (XmlSchema)originals[0]; for (int i = 0; i < schema.Items.Count; i++) { if (!matchedItems[i]) { destination.Items.Add(schema.Items[i]); } } destination.IsPreprocessed = false; Preprocess(destination); } } private static string ItemName(XmlSchemaObject o) { if (o is XmlSchemaNotation) { return ((XmlSchemaNotation)o).Name; } else if (o is XmlSchemaGroup) { return ((XmlSchemaGroup)o).Name; } else if (o is XmlSchemaElement) { return ((XmlSchemaElement)o).Name; } else if (o is XmlSchemaType) { return ((XmlSchemaType)o).Name; } else if (o is XmlSchemaAttributeGroup) { return ((XmlSchemaAttributeGroup)o).Name; } else if (o is XmlSchemaAttribute) { return ((XmlSchemaAttribute)o).Name; } return null; } internal static XmlQualifiedName GetParentName(XmlSchemaObject item) { while (item.Parent != null) { if (item.Parent is XmlSchemaType) { XmlSchemaType type = (XmlSchemaType)item.Parent; if (type.Name != null && type.Name.Length != 0) { return type.QualifiedName; } } item = item.Parent; } return XmlQualifiedName.Empty; } private static string GetSchemaItem(XmlSchemaObject o, string ns, string details) { if (o == null) { return null; } while (o.Parent != null && !(o.Parent is XmlSchema)) { o = o.Parent; } if (ns == null || ns.Length == 0) { XmlSchemaObject tmp = o; while (tmp.Parent != null) { tmp = tmp.Parent; } if (tmp is XmlSchema) { ns = ((XmlSchema)tmp).TargetNamespace; } } string item = null; if (o is XmlSchemaNotation) { item = string.Format(ResXml.XmlSchemaNamedItem, ns, "notation", ((XmlSchemaNotation)o).Name, details); } else if (o is XmlSchemaGroup) { item = string.Format(ResXml.XmlSchemaNamedItem, ns, "group", ((XmlSchemaGroup)o).Name, details); } else if (o is XmlSchemaElement) { XmlSchemaElement e = ((XmlSchemaElement)o); if (e.Name == null || e.Name.Length == 0) { XmlQualifiedName parentName = XmlSchemas.GetParentName(o); // Element reference '{0}' declared in schema type '{1}' from namespace '{2}' item = string.Format(ResXml.XmlSchemaElementReference, e.RefName.ToString(), parentName.Name, parentName.Namespace); } else { item = string.Format(ResXml.XmlSchemaNamedItem, ns, "element", e.Name, details); } } else if (o is XmlSchemaType) { item = string.Format(ResXml.XmlSchemaNamedItem, ns, o.GetType() == typeof(XmlSchemaSimpleType) ? "simpleType" : "complexType", ((XmlSchemaType)o).Name, null); } else if (o is XmlSchemaAttributeGroup) { item = string.Format(ResXml.XmlSchemaNamedItem, ns, "attributeGroup", ((XmlSchemaAttributeGroup)o).Name, details); } else if (o is XmlSchemaAttribute) { XmlSchemaAttribute a = ((XmlSchemaAttribute)o); if (a.Name == null || a.Name.Length == 0) { XmlQualifiedName parentName = XmlSchemas.GetParentName(o); // Attribure reference '{0}' declared in schema type '{1}' from namespace '{2}' return string.Format(ResXml.XmlSchemaAttributeReference, a.RefName.ToString(), parentName.Name, parentName.Namespace); } else { item = string.Format(ResXml.XmlSchemaNamedItem, ns, "attribute", a.Name, details); } } else if (o is XmlSchemaContent) { XmlQualifiedName parentName = XmlSchemas.GetParentName(o); // Check content definition of schema type '{0}' from namespace '{1}'. {2} item = string.Format(ResXml.XmlSchemaContentDef, parentName.Name, parentName.Namespace, null); } else if (o is XmlSchemaExternal) { string itemType = o is XmlSchemaImport ? "import" : o is XmlSchemaInclude ? "include" : o is XmlSchemaRedefine ? "redefine" : o.GetType().Name; item = string.Format(ResXml.XmlSchemaItem, ns, itemType, details); } else if (o is XmlSchema) { item = string.Format(ResXml.XmlSchema, ns, details); } else { item = string.Format(ResXml.XmlSchemaNamedItem, ns, o.GetType().Name, null, details); } return item; } private static string Dump(XmlSchemaObject o) { XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = true; XmlSerializer s = new XmlSerializer(o.GetType()); StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); XmlWriter xmlWriter = XmlWriter.Create(sw, settings); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("xs", XmlSchema.Namespace); s.Serialize(xmlWriter, o, ns); return sw.ToString(); } private static string MergeFailedMessage(XmlSchemaObject src, XmlSchemaObject dest, string ns) { string err = string.Format(ResXml.XmlSerializableMergeItem, ns, GetSchemaItem(src, ns, null)); err += "\r\n" + Dump(src); err += "\r\n" + Dump(dest); return err; } internal XmlSchemaObject Find(XmlSchemaObject o, IList originals) { string name = ItemName(o); if (name == null) return null; Type type = o.GetType(); foreach (XmlSchema s in originals) { foreach (XmlSchemaObject item in s.Items) { if (item.GetType() == type && name == ItemName(item)) { return item; } } } return null; } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.IsCompiled"]/*' /> public bool IsCompiled { get { return _isCompiled; } } /// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Compile"]/*' /> public void Compile(ValidationEventHandler handler, bool fullCompile) { if (_isCompiled) return; foreach (XmlSchema s in delayedSchemas.Values) Merge(s); delayedSchemas.Clear(); if (fullCompile) { _schemaSet = new XmlSchemaSet(); _schemaSet.XmlResolver = null; _schemaSet.ValidationEventHandler += handler; foreach (XmlSchema s in References.Values) _schemaSet.Add(s); int schemaCount = _schemaSet.Count; foreach (XmlSchema s in List) { if (!SchemaSet.Contains(s)) { _schemaSet.Add(s); schemaCount++; } } if (!SchemaSet.Contains(XmlSchema.Namespace)) { AddReference(XsdSchema); _schemaSet.Add(XsdSchema); schemaCount++; } if (!SchemaSet.Contains(XmlReservedNs.NsXml)) { AddReference(XmlSchema); _schemaSet.Add(XmlSchema); schemaCount++; } _schemaSet.Compile(); _schemaSet.ValidationEventHandler -= handler; _isCompiled = _schemaSet.IsCompiled && schemaCount == _schemaSet.Count; } else { try { XmlNameTable nameTable = new Microsoft.Xml.NameTable(); Preprocessor prep = new Preprocessor(nameTable, new SchemaNames(nameTable), null); prep.XmlResolver = null; prep.SchemaLocations = new Hashtable(); prep.ChameleonSchemas = new Hashtable(); foreach (XmlSchema schema in SchemaSet.Schemas()) { prep.Execute(schema, schema.TargetNamespace, true); } } catch (XmlSchemaException e) { throw CreateValidationException(e, e.Message); } } } internal static Exception CreateValidationException(XmlSchemaException exception, string message) { XmlSchemaObject source = exception.SourceSchemaObject; if (exception.LineNumber == 0 && exception.LinePosition == 0) { throw new InvalidOperationException(GetSchemaItem(source, null, message), exception); } else { string ns = null; if (source != null) { while (source.Parent != null) { source = source.Parent; } if (source is XmlSchema) { ns = ((XmlSchema)source).TargetNamespace; } } throw new InvalidOperationException(string.Format(ResXml.XmlSchemaSyntaxErrorDetails, ns, message, exception.LineNumber, exception.LinePosition), exception); } } internal static void IgnoreCompileErrors(object sender, ValidationEventArgs args) { return; } internal static XmlSchema XsdSchema { get { if (s_xsd == null) { s_xsd = CreateFakeXsdSchema(XmlSchema.Namespace, "schema"); } return s_xsd; } } internal static XmlSchema XmlSchema { get { if (s_xml == null) { s_xml = XmlSchema.Read(new StringReader(xmlSchema), null); } return s_xml; } } private static XmlSchema CreateFakeXsdSchema(string ns, string name) { /* Create fake xsd schema to fool the XmlSchema.Compiler <xsd:schema targetNamespace="http://www.w3.org/2001/XMLSchema" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="schema"> <xsd:complexType /> </xsd:element> </xsd:schema> */ XmlSchema schema = new XmlSchema(); schema.TargetNamespace = ns; XmlSchemaElement element = new XmlSchemaElement(); element.Name = name; XmlSchemaComplexType type = new XmlSchemaComplexType(); element.SchemaType = type; schema.Items.Add(element); return schema; } internal void SetCache(SchemaObjectCache cache, bool shareTypes) { _shareTypes = shareTypes; _cache = cache; if (shareTypes) { cache.GenerateSchemaGraph(this); } } internal bool IsReference(XmlSchemaObject type) { XmlSchemaObject parent = type; while (parent.Parent != null) { parent = parent.Parent; } return References.Contains(parent); } internal const string xmlSchema = @"<?xml version='1.0' encoding='UTF-8' ?> <xs:schema targetNamespace='http://www.w3.org/XML/1998/namespace' xmlns:xs='http://www.w3.org/2001/XMLSchema' xml:lang='en'> <xs:attribute name='lang' type='xs:language'/> <xs:attribute name='space'> <xs:simpleType> <xs:restriction base='xs:NCName'> <xs:enumeration value='default'/> <xs:enumeration value='preserve'/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name='base' type='xs:anyURI'/> <xs:attribute name='id' type='xs:ID' /> <xs:attributeGroup name='specialAttrs'> <xs:attribute ref='xml:base'/> <xs:attribute ref='xml:lang'/> <xs:attribute ref='xml:space'/> </xs:attributeGroup> </xs:schema>"; } public class XmlSchemaEnumerator : IEnumerator<XmlSchema>, System.Collections.IEnumerator { private XmlSchemas _list; private int _idx,_end; public XmlSchemaEnumerator(XmlSchemas list) { _list = list; _idx = -1; _end = list.Count - 1; } public void Dispose() { } public bool MoveNext() { if (_idx >= _end) return false; _idx++; return true; } public XmlSchema Current { get { return _list[_idx]; } } object System.Collections.IEnumerator.Current { get { return _list[_idx]; } } void System.Collections.IEnumerator.Reset() { _idx = -1; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Threading; using Microsoft.Extensions.Logging; namespace Microsoft.AspNet.SignalR.Infrastructure { // TODO: Figure out performance counters /// <summary> /// Manages performance counters using Windows performance counters. /// </summary> public class PerformanceCounterManager : IPerformanceCounterManager { /// <summary> /// The performance counter category name for SignalR counters. /// </summary> public const string CategoryName = "SignalR"; private readonly static PropertyInfo[] _counterProperties = GetCounterPropertyInfo(); private readonly static IPerformanceCounter _noOpCounter = new NoOpPerformanceCounter(); // private volatile bool _initialized; // private object _initLocker = new object(); private readonly ILogger _logger; /// <summary> /// Creates a new instance. /// </summary> public PerformanceCounterManager(ILoggerFactory loggerFactory) { if (loggerFactory == null) { throw new ArgumentNullException("loggerFactory"); } _logger = loggerFactory.CreateLogger<PerformanceCounterManager>(); InitNoOpCounters(); } /// <summary> /// Gets the performance counter representing the total number of connection Connect events since the application was started. /// </summary> [PerformanceCounter(Name = "Connections Connected", Description = "The total number of connection Connect events since the application was started.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ConnectionsConnected { get; private set; } /// <summary> /// Gets the performance counter representing the total number of connection Reconnect events since the application was started. /// </summary> [PerformanceCounter(Name = "Connections Reconnected", Description = "The total number of connection Reconnect events since the application was started.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ConnectionsReconnected { get; private set; } /// <summary> /// Gets the performance counter representing the total number of connection Disconnect events since the application was started. /// </summary> [PerformanceCounter(Name = "Connections Disconnected", Description = "The total number of connection Disconnect events since the application was started.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ConnectionsDisconnected { get; private set; } /// <summary> /// Gets the performance counter representing the number of connections currently connected using the ForeverFrame transport. /// </summary> [PerformanceCounter(Name = "Connections Current ForeverFrame", Description = "The number of connections currently connected using the ForeverFrame transport.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ConnectionsCurrentForeverFrame { get; private set; } /// <summary> /// Gets the performance counter representing the number of connections currently connected using the LongPolling transport. /// </summary> [PerformanceCounter(Name = "Connections Current LongPolling", Description = "The number of connections currently connected using the LongPolling transport.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ConnectionsCurrentLongPolling { get; private set; } /// <summary> /// Gets the performance counter representing the number of connections currently connected using the ServerSentEvents transport. /// </summary> [PerformanceCounter(Name = "Connections Current ServerSentEvents", Description = "The number of connections currently connected using the ServerSentEvents transport.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ConnectionsCurrentServerSentEvents { get; private set; } /// <summary> /// Gets the performance counter representing the number of connections currently connected using the WebSockets transport. /// </summary> [PerformanceCounter(Name = "Connections Current WebSockets", Description = "The number of connections currently connected using the WebSockets transport.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ConnectionsCurrentWebSockets { get; private set; } /// <summary> /// Gets the performance counter representing the number of connections currently connected. /// </summary> [PerformanceCounter(Name = "Connections Current", Description = "The number of connections currently connected.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ConnectionsCurrent { get; private set; } /// <summary> /// Gets the performance counter representing the toal number of messages received by connections (server to client) since the application was started. /// </summary> [PerformanceCounter(Name = "Connection Messages Received Total", Description = "The toal number of messages received by connections (server to client) since the application was started.", CounterType = PerformanceCounterType.NumberOfItems64)] public IPerformanceCounter ConnectionMessagesReceivedTotal { get; private set; } /// <summary> /// Gets the performance counter representing the total number of messages sent by connections (client to server) since the application was started. /// </summary> [PerformanceCounter(Name = "Connection Messages Sent Total", Description = "The total number of messages sent by connections (client to server) since the application was started.", CounterType = PerformanceCounterType.NumberOfItems64)] public IPerformanceCounter ConnectionMessagesSentTotal { get; private set; } /// <summary> /// Gets the performance counter representing the number of messages received by connections (server to client) per second. /// </summary> [PerformanceCounter(Name = "Connection Messages Received/Sec", Description = "The number of messages received by connections (server to client) per second.", CounterType = PerformanceCounterType.RateOfCountsPerSecond32)] public IPerformanceCounter ConnectionMessagesReceivedPerSec { get; private set; } /// <summary> /// Gets the performance counter representing the number of messages sent by connections (client to server) per second. /// </summary> [PerformanceCounter(Name = "Connection Messages Sent/Sec", Description = "The number of messages sent by connections (client to server) per second.", CounterType = PerformanceCounterType.RateOfCountsPerSecond32)] public IPerformanceCounter ConnectionMessagesSentPerSec { get; private set; } /// <summary> /// Gets the performance counter representing the total number of messages received by subscribers since the application was started. /// </summary> [PerformanceCounter(Name = "Message Bus Messages Received Total", Description = "The total number of messages received by subscribers since the application was started.", CounterType = PerformanceCounterType.NumberOfItems64)] public IPerformanceCounter MessageBusMessagesReceivedTotal { get; private set; } /// <summary> /// Gets the performance counter representing the number of messages received by a subscribers per second. /// </summary> [PerformanceCounter(Name = "Message Bus Messages Received/Sec", Description = "The number of messages received by subscribers per second.", CounterType = PerformanceCounterType.RateOfCountsPerSecond32)] public IPerformanceCounter MessageBusMessagesReceivedPerSec { get; private set; } /// <summary> /// Gets the performance counter representing the number of messages received by the scaleout message bus per second. /// </summary> [PerformanceCounter(Name = "Scaleout Message Bus Messages Received/Sec", Description = "The number of messages received by the scaleout message bus per second.", CounterType = PerformanceCounterType.RateOfCountsPerSecond32)] public IPerformanceCounter ScaleoutMessageBusMessagesReceivedPerSec { get; private set; } /// <summary> /// Gets the performance counter representing the total number of messages published to the message bus since the application was started. /// </summary> [PerformanceCounter(Name = "Message Bus Messages Published Total", Description = "The total number of messages published to the message bus since the application was started.", CounterType = PerformanceCounterType.NumberOfItems64)] public IPerformanceCounter MessageBusMessagesPublishedTotal { get; private set; } /// <summary> /// Gets the performance counter representing the number of messages published to the message bus per second. /// </summary> [PerformanceCounter(Name = "Message Bus Messages Published/Sec", Description = "The number of messages published to the message bus per second.", CounterType = PerformanceCounterType.RateOfCountsPerSecond32)] public IPerformanceCounter MessageBusMessagesPublishedPerSec { get; private set; } /// <summary> /// Gets the performance counter representing the current number of subscribers to the message bus. /// </summary> [PerformanceCounter(Name = "Message Bus Subscribers Current", Description = "The current number of subscribers to the message bus.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter MessageBusSubscribersCurrent { get; private set; } /// <summary> /// Gets the performance counter representing the total number of subscribers to the message bus since the application was started. /// </summary> [PerformanceCounter(Name = "Message Bus Subscribers Total", Description = "The total number of subscribers to the message bus since the application was started.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter MessageBusSubscribersTotal { get; private set; } /// <summary> /// Gets the performance counter representing the number of new subscribers to the message bus per second. /// </summary> [PerformanceCounter(Name = "Message Bus Subscribers/Sec", Description = "The number of new subscribers to the message bus per second.", CounterType = PerformanceCounterType.RateOfCountsPerSecond32)] public IPerformanceCounter MessageBusSubscribersPerSec { get; private set; } /// <summary> /// Gets the performance counter representing the number of workers allocated to deliver messages in the message bus. /// </summary> [PerformanceCounter(Name = "Message Bus Allocated Workers", Description = "The number of workers allocated to deliver messages in the message bus.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter MessageBusAllocatedWorkers { get; private set; } /// <summary> /// Gets the performance counter representing the number of workers currently busy delivering messages in the message bus. /// </summary> [PerformanceCounter(Name = "Message Bus Busy Workers", Description = "The number of workers currently busy delivering messages in the message bus.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter MessageBusBusyWorkers { get; private set; } /// <summary> /// Gets the performance counter representing representing the current number of topics in the message bus. /// </summary> [PerformanceCounter(Name = "Message Bus Topics Current", Description = "The number of topics in the message bus.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter MessageBusTopicsCurrent { get; private set; } /// <summary> /// Gets the performance counter representing the total number of all errors processed since the application was started. /// </summary> [PerformanceCounter(Name = "Errors: All Total", Description = "The total number of all errors processed since the application was started.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ErrorsAllTotal { get; private set; } /// <summary> /// Gets the performance counter representing the number of all errors processed per second. /// </summary> [PerformanceCounter(Name = "Errors: All/Sec", Description = "The number of all errors processed per second.", CounterType = PerformanceCounterType.RateOfCountsPerSecond32)] public IPerformanceCounter ErrorsAllPerSec { get; private set; } /// <summary> /// Gets the performance counter representing the total number of hub resolution errors processed since the application was started. /// </summary> [PerformanceCounter(Name = "Errors: Hub Resolution Total", Description = "The total number of hub resolution errors processed since the application was started.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ErrorsHubResolutionTotal { get; private set; } /// <summary> /// Gets the performance counter representing the number of hub resolution errors per second. /// </summary> [PerformanceCounter(Name = "Errors: Hub Resolution/Sec", Description = "The number of hub resolution errors per second.", CounterType = PerformanceCounterType.RateOfCountsPerSecond32)] public IPerformanceCounter ErrorsHubResolutionPerSec { get; private set; } /// <summary> /// Gets the performance counter representing the total number of hub invocation errors processed since the application was started. /// </summary> [PerformanceCounter(Name = "Errors: Hub Invocation Total", Description = "The total number of hub invocation errors processed since the application was started.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ErrorsHubInvocationTotal { get; private set; } /// <summary> /// Gets the performance counter representing the number of hub invocation errors per second. /// </summary> [PerformanceCounter(Name = "Errors: Hub Invocation/Sec", Description = "The number of hub invocation errors per second.", CounterType = PerformanceCounterType.RateOfCountsPerSecond32)] public IPerformanceCounter ErrorsHubInvocationPerSec { get; private set; } /// <summary> /// Gets the performance counter representing the total number of transport errors processed since the application was started. /// </summary> [PerformanceCounter(Name = "Errors: Tranport Total", Description = "The total number of transport errors processed since the application was started.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ErrorsTransportTotal { get; private set; } /// <summary> /// Gets the performance counter representing the number of transport errors per second. /// </summary> [PerformanceCounter(Name = "Errors: Transport/Sec", Description = "The number of transport errors per second.", CounterType = PerformanceCounterType.RateOfCountsPerSecond32)] public IPerformanceCounter ErrorsTransportPerSec { get; private set; } /// <summary> /// Gets the performance counter representing the number of logical streams in the currently configured scaleout message bus provider. /// </summary> [PerformanceCounter(Name = "Scaleout Streams Total", Description = "The number of logical streams in the currently configured scaleout message bus provider.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ScaleoutStreamCountTotal { get; private set; } /// <summary> /// Gets the performance counter representing the number of logical streams in the currently configured scaleout message bus provider that are in the open state. /// </summary> [PerformanceCounter(Name = "Scaleout Streams Open", Description = "The number of logical streams in the currently configured scaleout message bus provider that are in the open state", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ScaleoutStreamCountOpen { get; private set; } /// <summary> /// Gets the performance counter representing the number of logical streams in the currently configured scaleout message bus provider that are in the buffering state. /// </summary> [PerformanceCounter(Name = "Scaleout Streams Buffering", Description = "The number of logical streams in the currently configured scaleout message bus provider that are in the buffering state", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ScaleoutStreamCountBuffering { get; private set; } /// <summary> /// Gets the performance counter representing the total number of scaleout errors since the application was started. /// </summary> [PerformanceCounter(Name = "Scaleout Errors Total", Description = "The total number of scaleout errors since the application was started.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ScaleoutErrorsTotal { get; private set; } /// <summary> /// Gets the performance counter representing the number of scaleout errors per second. /// </summary> [PerformanceCounter(Name = "Scaleout Errors/Sec", Description = "The number of scaleout errors per second.", CounterType = PerformanceCounterType.RateOfCountsPerSecond32)] public IPerformanceCounter ScaleoutErrorsPerSec { get; private set; } /// <summary> /// Gets the performance counter representing the current scaleout send queue length. /// </summary> [PerformanceCounter(Name = "Scaleout Send Queue Length", Description = "The current scaleout send queue length.", CounterType = PerformanceCounterType.NumberOfItems32)] public IPerformanceCounter ScaleoutSendQueueLength { get; private set; } private void InitNoOpCounters() { // Set all the counter properties to no-op by default. // These will get reset to real counters when/if the Initialize method is called. foreach (var property in _counterProperties) { property.SetValue(this, new NoOpPerformanceCounter(), null); } } internal static PropertyInfo[] GetCounterPropertyInfo() { return typeof(PerformanceCounterManager) .GetProperties() .Where(p => p.PropertyType == typeof(IPerformanceCounter)) .ToArray(); } internal static PerformanceCounterAttribute GetPerformanceCounterAttribute(PropertyInfo property) { return property.GetCustomAttributes(typeof(PerformanceCounterAttribute), false) .Cast<PerformanceCounterAttribute>() .SingleOrDefault(); } #if PERFCOUNTER internal string InstanceName { get; private set; } /// <summary> /// Initializes the performance counters. /// </summary> /// <param name="instanceName">The host instance name.</param> /// <param name="hostShutdownToken">The CancellationToken representing the host shutdown.</param> public void Initialize(string instanceName, CancellationToken hostShutdownToken) { if (_initialized) { return; } var needToRegisterWithShutdownToken = false; lock (_initLocker) { if (!_initialized) { InstanceName = SanitizeInstanceName(instanceName); SetCounterProperties(); // The initializer ran, so let's register the shutdown cleanup if (hostShutdownToken != CancellationToken.None) { needToRegisterWithShutdownToken = true; } _initialized = true; } } if (needToRegisterWithShutdownToken) { hostShutdownToken.Register(UnloadCounters); } } private void UnloadCounters() { lock (_initLocker) { if (!_initialized) { // We were never initalized return; } } var counterProperties = this.GetType() .GetProperties() .Where(p => p.PropertyType == typeof(IPerformanceCounter)); foreach (var property in counterProperties) { var counter = property.GetValue(this, null) as IPerformanceCounter; counter.Close(); counter.RemoveInstance(); } } private void SetCounterProperties() { var loadCounters = true; foreach (var property in _counterProperties) { PerformanceCounterAttribute attribute = GetPerformanceCounterAttribute(property); if (attribute == null) { continue; } IPerformanceCounter counter = null; if (loadCounters) { counter = LoadCounter(CategoryName, attribute.Name, isReadOnly:false); if (counter == null) { // We failed to load the counter so skip the rest loadCounters = false; } } counter = counter ?? _noOpCounter; property.SetValue(this, counter, null); } } private static string SanitizeInstanceName(string instanceName) { // Details on how to sanitize instance names are at http://msdn.microsoft.com/en-us/library/vstudio/system.diagnostics.performancecounter.instancename if (string.IsNullOrWhiteSpace(instanceName)) { instanceName = Guid.NewGuid().ToString(); } // Substitute invalid chars with valid replacements var substMap = new Dictionary<char, char> { { '(', '[' }, { ')', ']' }, { '#', '-' }, { '\\', '-' }, { '/', '-' } }; var sanitizedName = new String(instanceName.Select(c => substMap.ContainsKey(c) ? substMap[c] : c).ToArray()); // Names must be shorter than 128 chars, see doc link above var maxLength = 127; return sanitizedName.Length <= maxLength ? sanitizedName : sanitizedName.Substring(0, maxLength); } private IPerformanceCounter LoadCounter(string categoryName, string counterName, bool isReadOnly) { return LoadCounter(categoryName, counterName, InstanceName, isReadOnly); } [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This file is shared")] [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Counters are disposed later")] public IPerformanceCounter LoadCounter(string categoryName, string counterName, string instanceName, bool isReadOnly) { // See http://msdn.microsoft.com/en-us/library/356cx381.aspx for the list of exceptions // and when they are thrown. try { var counter = new PerformanceCounter(categoryName, counterName, instanceName, isReadOnly); // Initialize the counter sample counter.NextSample(); return new PerformanceCounterWrapper(counter); } catch (InvalidOperationException ex) { _logger.WriteError("Performance counter failed to load: " + ex.GetBaseException()); return null; } catch (UnauthorizedAccessException ex) { _logger.WriteError("Performance counter failed to load: " + ex.GetBaseException()); return null; } catch (Win32Exception ex) { _logger.WriteError("Performance counter failed to load: " + ex.GetBaseException()); return null; } catch (PlatformNotSupportedException ex) { _logger.WriteError("Performance counter failed to load: " + ex.GetBaseException()); return null; } } #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using JetBrains.Annotations; using Silphid.DataTypes; using Silphid.Extensions; using Silphid.Injexit; using Silphid.Requests; using Silphid.Showzup.Recipes; using Silphid.Showzup.Requests; using Silphid.Showzup.Virtual.Layout; using UniRx; using UniRx.Completables; using UniRx.Triggers; using UnityEngine; using UnityEngine.UI; namespace Silphid.Showzup.Virtual { [RequireComponent(typeof(RectTransform))] public class ListControl : MonoBehaviour, IListPresenter, IContainerProvider, IRequestHandler { // Priority #1: // TODO: Fix fixed layout // TODO: Fix non-virtualized mode // TODO: Fix items that continue loading even when viewport has moved away since a while (dispose should cancel loading). // TODO: Optimization: Track loaded index range to iterate only through loaded range during relayout instead of almost complete collection. // TODO: Test virtualization with small number of items (when they all fit within viewport) // TODO: OnDestroy, dispose all pending loading views / unload all views // TODO: *JSBR* Find why the error is not display (in function FindViewport) // Priority #2: // TODO: Drag-and-drop. // TODO: Paging. // Priority #3: // TODO: View pooling. // Priority #4: // TODO: Test nested list controls. // TODO: Reintegrate IMoveHandler handling for TV remote navigation. // TODO: Reintegrate IRequestHandler implementation for PresentRequest. // TODO: Relayout automatically when some item's preferred size changes. // Priority #5: // TODO: Animated/transitioned item adding/removal (maybe only for single-item across, aka "Stack"). // TODO: Proper implementation of ICompletable returned by Present(). // TODO: Optimize virtualization on scroll to avoid iterating through all RectTransforms every time (use a differential approach or throttle?) // TODO: Fix relayout upon item removal and load more views at the end as appropriate. // TODO: Unload extra views at the end upon item insertion. #region Private fields private readonly List<Entry> _entries = new List<Entry>(); private readonly ISubject<IView> _loadedViewsSubject = new Subject<IView>(); private readonly ISubject<IView> _unloadedViewsSubject = new Subject<IView>(); private IReadOnlyList<object> _models; private IOptions _options; private CompositeDisposable _reactiveCollectionDisposable; private ICompletableSubject _completableSubject; private bool _isInitialized; private ILayoutCollection _layoutCollection; private ILayout _layout; private RectTransform _contentTransform; private LayoutElement _contentLayoutElement; private RectTransform _viewportTransform; private ScrollRectEx _scrollRectEx; private readonly ReactiveProperty<IntRange> _activeRange = new ReactiveProperty<IntRange>(IntRange.Empty); private RangeCache _ranges; private readonly ChoiceHelper _choiceHelper; #endregion #region Config properties public RectTransform Content; public string[] Variants; public LayoutInfo LayoutInfo = new LayoutInfo(); public bool Virtualize; public bool HandlesChooseRequest; public bool ConsumeRequest; private Vector2 AvailableSize => LayoutInfo.Transformer.TransformSize(_contentTransform.rect.size); private Rect ViewportRect => LayoutInfo.Transformer.TransformRect(_viewportTransform.GetRectRelativeTo(Content)); #endregion #region Injected properties [Inject, UsedImplicitly] private IRecipeProvider RecipeProvider { get; set; } [Inject, UsedImplicitly] private IViewLoader ViewLoader { get; set; } [Inject, UsedImplicitly] private IVariantProvider VariantProvider { get; set; } #endregion #region Initialization public ListControl() { _choiceHelper = new ChoiceHelper(this); } private void EnsureInitialized() { if (_isInitialized) return; _isInitialized = true; _layoutCollection = new LayoutCollection(_entries, LayoutInfo); _ranges = new RangeCache(_layoutCollection); _layout = new DelegatingLayout(LayoutInfo, _ranges); AssertDependencies(); InitViewport(); if (Virtualize) InitVirtualization(); } private void AssertDependencies() { if (LayoutInfo == null) throw new ArgumentNullException(nameof(LayoutInfo)); if (Content == null) throw new ArgumentNullException(nameof(Content)); _contentTransform = Content.GetComponent<RectTransform>(); _contentLayoutElement = Content.GetComponent<LayoutElement>(); if (_contentLayoutElement == null) throw new InvalidOperationException("Content must have a LayoutElement component"); } private void InitViewport() { var viewport = FindViewport(); _viewportTransform = viewport.RectTransform; _scrollRectEx = viewport.ScrollRectEx; } public void Start() { EnsureInitialized(); } private void OnDestroy() { StopObservingReactiveCollection(); } #endregion #region IContainerProvider members private IContainer _container; public IContainer Container => _container ?? (_container = this.GetParentContainer()); #endregion #region IListPresenter public ICompletable Present(IReadOnlyList<object> models, IOptions options = null) => Completable.Defer(() => PresentInternal(models, options)) .DoOnCompleted(() => UpdateLayout()); public IObservable<IView> LoadedViews => _loadedViewsSubject; public IObservable<IView> UnloadedViews => _unloadedViewsSubject; #endregion #region Present implementation private ICompletable PresentInternal(IReadOnlyList<object> models, IOptions options) { EnsureInitialized(); lock (this) { _models = models; _options = options.With(VariantProvider.GetVariantsNamed(Variants)); StopObservingReactiveCollection(); if (models is IReadOnlyReactiveCollection<object> reactiveModels) ObserveReactiveCollection(reactiveModels); RecreateAllEntries(); LoadInitialViews(); _completableSubject?.OnCompleted(); _completableSubject = new CompletableSubject(); return _completableSubject; } } private void RecreateAllEntries() { _entries.ForEach(x => x.Disposable?.Dispose()); _entries.Clear(); foreach (var model in _models) _entries.Add(new Entry(model)); } #endregion #region View loading/unloading private void LoadInitialViews() { if (Virtualize) ResetActiveRange(); else foreach (var entry in _entries) LoadView(entry); } private void LoadView(int index, LayoutDirection direction = LayoutDirection.Forward) { LoadView(_entries[index], direction); } private void LoadView(Entry entry, LayoutDirection direction = LayoutDirection.Forward) { lock (this) { if (entry.IsViewLoaded) return; //Debug.Log("Load: " + _entries.IndexOf(entry)); entry.Disposable?.Dispose(); // var cancellation = new CancellationDisposable(); var disposable = new SerialDisposable(); // { Disposable = cancellation }; entry.Disposable = disposable; ResolveRecipe(entry) .ContinueWith(recipe => LoadView(recipe, CancellationToken.None)) //cancellation.Token) .Subscribe( view => { lock (this) { if (disposable.IsDisposed) { //Debug.Log($"IsDisposed Destroy: {_entries.IndexOf(entry)}"); view.GameObject.Destroy(); } else { entry.View = view; entry.IsLayoutValid = false; disposable.Disposable = Disposable.Create(() => UnloadViewInternal(entry)); view.GameObject.SetParent(Content.gameObject); var index = _entries.IndexOf(entry); _ranges.OnItemLoaded(index); UpdateLayout(direction); } } if (entry.View != null) _loadedViewsSubject.OnNext(entry.View); }); } } private IObservable<Recipe> ResolveRecipe(Entry entry) => entry.Recipe == null ? RecipeProvider.GetRecipe(entry.Model, _options) .Do(x => entry.Recipe = x) : Observable.Return(entry.Recipe.Value); private IObservable<IView> LoadView(Recipe recipe, CancellationToken cancellationToken) => ViewLoader.Load(GetInstantiationContainer(), recipe, Container, cancellationToken); private void UnloadView(int index) { //Debug.Log("Unload: " + index); _entries[index] .Disposable?.Dispose(); } private void UnloadViewInternal(Entry entry) { IView unloadedView; lock (this) { if (!entry.IsViewLoaded) return; unloadedView = entry.View; entry.View = null; entry.IsLayoutValid = false; unloadedView.GameObject.Destroy(); var index = _entries.IndexOf(entry); _ranges.OnItemUnloaded(index); } _unloadedViewsSubject.OnNext(unloadedView); } #endregion #region ReactiveCollection private void StopObservingReactiveCollection() { _reactiveCollectionDisposable?.Dispose(); _reactiveCollectionDisposable = null; } private void ObserveReactiveCollection(IReadOnlyReactiveCollection<object> models) { _reactiveCollectionDisposable = new CompositeDisposable( models.ObserveAdd() .Subscribe(x => OnAdd(x.Index, x.Value)), models.ObserveRemove() .Subscribe(x => OnRemove(x.Index, x.Value)), models.ObserveMove() .Subscribe(x => OnMove(x.OldIndex, x.NewIndex)), models.ObserveReplace() .Subscribe(x => OnReplace(x.Index, x.NewValue)), models.ObserveReset() .Subscribe(x => OnReset())); } private void OnAdd(int index, object model) { lock (this) { var entry = new Entry(model); _entries.Insert(index, entry); // TODO: Update RangeCache if (_activeRange.Value.Contains(index)) LoadView(entry); } } private void OnRemove(int index, object model) { lock (this) { _entries[index] .Disposable?.Dispose(); _entries.RemoveAt(index); UpdateLayout(); // TODO: Update RangeCache // TODO: Update layout only if was within visible range } } private void OnMove(int oldIndex, int newIndex) { lock (this) { var entry = _entries[oldIndex]; _entries.RemoveAt(oldIndex); _entries.Insert(newIndex, entry); UpdateLayout(); // TODO: Update RangeCache // TODO: Update layout if was or becomes within visible range } } private void OnReplace(int index, object model) { lock (this) { _entries[index] .Disposable?.Dispose(); var entry = new Entry(model); _entries[index] = entry; LoadView(entry); // TODO: Update RangeCache // TODO: Load view only if within visible range } } private void OnReset() { lock (this) { RecreateAllEntries(); // TODO: Update RangeCache // TODO: Load all views (but only within visible range ???) foreach (var entry in _entries.Where((_, index) => _activeRange.Value.Contains(index))) LoadView(entry); } } #endregion #region Instantiation container private Transform _instantiationContainer; private Transform GetInstantiationContainer() { if (_instantiationContainer == null) { var obj = new GameObject("InstantiationContainer"); obj.SetActive(false); _instantiationContainer = obj.transform; _instantiationContainer.transform.parent = transform; } return _instantiationContainer; } #endregion #region Virtualization private void InitVirtualization() { _scrollRectEx.content.ObserveEveryValueChanged(x => x.anchoredPosition) .AsUnitObservable() .Merge(Content.OnRectTransformDimensionsChangeAsObservable()) .Subscribe(_ => UpdateActiveRange()) .AddTo(this); _activeRange.PairWithPrevious() .Subscribe(x => OnActiveRangeChanged(x.Item1, x.Item2)) .AddTo(this); } private void ResetActiveRange() { _activeRange.Value = IntRange.Empty; _ranges.Invalidate(); UpdateActiveRange(); } private void UpdateActiveRange() { _activeRange.Value = GetActiveRange(); } private IntRange GetActiveRange() => _layout.GetActiveRange(_layoutCollection, ViewportRect, AvailableSize); private void OnActiveRangeChanged(IntRange oldRange, IntRange newRange) { //Debug.Log($"Range: {newRange}"); var combinedRange = oldRange.Union(newRange); foreach (var index in combinedRange) { bool isInOld = oldRange.Contains(index); bool isInNew = newRange.Contains(index); if (isInOld && !isInNew) UnloadView(index); else if (!isInOld && isInNew) { var direction = oldRange.IsEmpty || index >= oldRange.Start ? LayoutDirection.Forward : LayoutDirection.Backward; LoadView(index, direction); } } } private Viewport FindViewport() { var viewport = this.SelfAndAncestors<Viewport>() .FirstOrDefault(); //TODO find why error trigger if (viewport == null) throw new InvalidOperationException( "Virtualization requires a Viewport component on ListControl or some ancestor"); if (viewport.RectTransform == null) throw new InvalidOperationException( "Virtualization requires that RectTransform property of Viewport component be set"); if (viewport.ScrollRectEx == null) throw new InvalidOperationException( "Virtualization requires that ScrollRectEx property of Viewport component be set"); return viewport; } #endregion #region Layout private void OnRectTransformDimensionsChange() { EnsureInitialized(); UpdateLayout(); } public void UpdateLayout(LayoutDirection direction = LayoutDirection.Forward) { var (contentSize, adjustment) = _layout.Perform(direction, _layoutCollection, ViewportRect, AvailableSize); SetContentSize(contentSize); AdjustScrollRect(adjustment); } private void SetContentSize(float size) { if (LayoutInfo.Orientation == Orientation.Vertical) _contentLayoutElement.minHeight = size; else _contentLayoutElement.minWidth = size; LayoutRebuilder.ForceRebuildLayoutImmediate(_scrollRectEx.content); } private void AdjustScrollRect(float adjustment) { _scrollRectEx.Adjust(LayoutInfo.Transformer.InverseTransformSize(new Vector2(0, adjustment))); } #endregion public bool Handle(IRequest request) => _choiceHelper.Handle( request, _entries, HandlesChooseRequest, ConsumeRequest); } }
using System; using System.Data; using System.Data.SqlClient; using Rainbow.Framework.Settings; namespace Rainbow.Framework.Content.Data { /// <summary> /// Class that encapsulates all data logic necessary /// articles within the Portal database. /// </summary> public class ArticlesDB { //This is used as a common setting from Articles public static string ImagesSetting = "ImageCollection"; /// <summary> /// The GetArticles method returns a SqlDataReader containing all of the /// Articles for a specific portal module from the announcements /// database. /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="version">The version.</param> /// <returns></returns> public SqlDataReader GetArticles(int moduleID, WorkFlowVersion version) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetArticles", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterWorkflowVersion = new SqlParameter("@WorkflowVersion", SqlDbType.Int, 4); parameterWorkflowVersion.Value = (int) version; myCommand.Parameters.Add(parameterWorkflowVersion); // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return result; } /// <summary> /// The GetArticlesAll method returns a SqlDataReader containing all of the /// Articles for a specific portal module from the announcements /// database (including expired one). /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="version">The version.</param> /// <returns></returns> public SqlDataReader GetArticlesAll(int moduleID, WorkFlowVersion version) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetArticlesAll", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterWorkflowVersion = new SqlParameter("@WorkflowVersion", SqlDbType.Int, 4); parameterWorkflowVersion.Value = (int) version; myCommand.Parameters.Add(parameterWorkflowVersion); // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return result; } /// <summary> /// The GetSingleArticle method returns a SqlDataReader containing details /// about a specific Article from the Articles database table. /// </summary> /// <param name="itemID">The item ID.</param> /// <param name="version">The version.</param> /// <returns></returns> public SqlDataReader GetSingleArticle(int itemID, WorkFlowVersion version) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSingleArticle", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterWorkflowVersion = new SqlParameter("@WorkflowVersion", SqlDbType.Int, 4); parameterWorkflowVersion.Value = (int) version; myCommand.Parameters.Add(parameterWorkflowVersion); // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return result; } /// <summary> /// The DeleteArticle method deletes a specified Article from /// the Articles database table. /// </summary> /// <param name="itemID">The item ID.</param> public void DeleteArticle(int itemID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DeleteArticle", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } } /// <summary> /// The AddArticle method adds a new Article within the /// Articles database table, and returns ItemID value as a result. /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="userName">Name of the user.</param> /// <param name="title">The title.</param> /// <param name="subtitle">The subtitle.</param> /// <param name="articleAbstract">The article abstract.</param> /// <param name="description">The description.</param> /// <param name="startDate">The start date.</param> /// <param name="expireDate">The expire date.</param> /// <param name="isInNewsletter">if set to <c>true</c> [is in newsletter].</param> /// <param name="moreLink">The more link.</param> /// <returns></returns> public int AddArticle(int moduleID, string userName, string title, string subtitle, string articleAbstract, string description, DateTime startDate, DateTime expireDate, bool isInNewsletter, string moreLink) { if (userName.Length < 1) { userName = "unknown"; } // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_AddArticle", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100); parameterUserName.Value = userName; myCommand.Parameters.Add(parameterUserName); SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100); parameterTitle.Value = title; myCommand.Parameters.Add(parameterTitle); SqlParameter parameterSubtitle = new SqlParameter("@Subtitle", SqlDbType.NVarChar, 200); parameterSubtitle.Value = subtitle; myCommand.Parameters.Add(parameterSubtitle); SqlParameter parameterAbstract = new SqlParameter("@Abstract", SqlDbType.NText); parameterAbstract.Value = articleAbstract; myCommand.Parameters.Add(parameterAbstract); SqlParameter parameterDescription = new SqlParameter("@Description", SqlDbType.NText); parameterDescription.Value = description; myCommand.Parameters.Add(parameterDescription); SqlParameter parameterStartDate = new SqlParameter("@StartDate", SqlDbType.DateTime); parameterStartDate.Value = startDate; myCommand.Parameters.Add(parameterStartDate); SqlParameter parameterExpireDate = new SqlParameter("@ExpireDate", SqlDbType.DateTime); parameterExpireDate.Value = expireDate; myCommand.Parameters.Add(parameterExpireDate); SqlParameter parameterIsInNewsletter = new SqlParameter("@IsInNewsletter", SqlDbType.Bit); parameterIsInNewsletter.Value = isInNewsletter; myCommand.Parameters.Add(parameterIsInNewsletter); SqlParameter parameterMoreLink = new SqlParameter("@MoreLink", SqlDbType.NVarChar, 150); parameterMoreLink.Value = moreLink; myCommand.Parameters.Add(parameterMoreLink); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return (int) parameterItemID.Value; } /// <summary> /// The UpdateArticle method updates a specified Article within /// the Articles database table. /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="itemID">The item ID.</param> /// <param name="userName">Name of the user.</param> /// <param name="title">The title.</param> /// <param name="subtitle">The subtitle.</param> /// <param name="articleAbstract">The article abstract.</param> /// <param name="description">The description.</param> /// <param name="startDate">The start date.</param> /// <param name="expireDate">The expire date.</param> /// <param name="isInNewsletter">if set to <c>true</c> [is in newsletter].</param> /// <param name="moreLink">The more link.</param> public void UpdateArticle(int moduleID, int itemID, string userName, string title, string subtitle, string articleAbstract, string description, DateTime startDate, DateTime expireDate, bool isInNewsletter, string moreLink) { if (userName.Length < 1) { userName = "unknown"; } // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_UpdateArticle", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100); parameterUserName.Value = userName; myCommand.Parameters.Add(parameterUserName); SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100); parameterTitle.Value = title; myCommand.Parameters.Add(parameterTitle); SqlParameter parameterSubtitle = new SqlParameter("@Subtitle", SqlDbType.NVarChar, 200); parameterSubtitle.Value = subtitle; myCommand.Parameters.Add(parameterSubtitle); SqlParameter parameterAbstract = new SqlParameter("@Abstract", SqlDbType.NText); parameterAbstract.Value = articleAbstract; myCommand.Parameters.Add(parameterAbstract); SqlParameter parameterDescription = new SqlParameter("@Description", SqlDbType.NText); parameterDescription.Value = description; myCommand.Parameters.Add(parameterDescription); SqlParameter parameterStartDate = new SqlParameter("@StartDate", SqlDbType.DateTime); parameterStartDate.Value = startDate; myCommand.Parameters.Add(parameterStartDate); SqlParameter parameterExpireDate = new SqlParameter("@ExpireDate", SqlDbType.DateTime); parameterExpireDate.Value = expireDate; myCommand.Parameters.Add(parameterExpireDate); SqlParameter parameterIsInNewsletter = new SqlParameter("@IsInNewsletter", SqlDbType.Bit); parameterIsInNewsletter.Value = isInNewsletter; myCommand.Parameters.Add(parameterIsInNewsletter); SqlParameter parameterMoreLink = new SqlParameter("@MoreLink", SqlDbType.NVarChar, 150); parameterMoreLink.Value = moreLink; myCommand.Parameters.Add(parameterMoreLink); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } } } }
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 Associations.Areas.HelpPage.ModelDescriptions; using Associations.Areas.HelpPage.Models; namespace Associations.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); } } } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ //# define debug_output using System; using System.Text; using System.Net.Sockets; using System.Threading; using System.Collections; using System.Net; using System.Diagnostics; using System.IO; namespace MLifter.DAL.DB.DbMediaServer { enum RState { METHOD, URL, URLPARM, URLVALUE, VERSION, HEADERKEY, HEADERVALUE, BODY, OK }; enum RespState { OK = 200, BAD_REQUEST = 400, NOT_FOUND = 404 } /// <summary> /// Content struct for a HTTP request /// </summary> public struct HTTPRequestStruct { /// <summary> /// The Method /// </summary> public string Method; /// <summary> /// The URL /// </summary> public string URL; /// <summary> /// The version /// </summary> public string Version; /// <summary> /// The arguments /// </summary> public Hashtable Args; /// <summary> /// ToDo: ? /// </summary> public bool Execute; /// <summary> /// The headers /// </summary> public Hashtable Headers; /// <summary> /// The body size /// </summary> public int BodySize; /// <summary> /// The body content /// </summary> public byte[] BodyData; } /// <summary> /// Content struct for a HTTP response /// </summary> public struct HTTPResponseStruct { /// <summary> /// The status /// </summary> public int status; /// <summary> /// The version /// </summary> public string version; /// <summary> /// The headers /// </summary> public Hashtable Headers; /// <summary> /// The body size /// </summary> public int BodySize; /// <summary> /// The body content /// </summary> public byte[] BodyData; /// <summary> /// The response stream /// </summary> public Stream mediaStream; } /// <summary> /// Takes care of the incoming http request, parses the request /// </summary> /// <remarks>Documented by Dev10, 2008-08-07</remarks> public class CsHTTPRequest { private TcpClient client; private RState ParserState; private HTTPRequestStruct HTTPRequest; private HTTPResponseStruct HTTPResponse; byte[] myReadBuffer; CsHTTPServer Parent; /// <summary> /// Initializes a new instance of the <see cref="CsHTTPRequest"/> class. /// </summary> /// <param name="client">The TcpClient.</param> /// <param name="Parent">The Server instance (TcpListener).</param> /// <remarks>Documented by Dev10, 2008-08-07</remarks> public CsHTTPRequest(TcpClient client, CsHTTPServer Parent) { this.client = client; this.Parent = Parent; this.HTTPResponse.BodySize = 0; } /// <summary> /// Processes actually the HTTP Request. /// </summary> /// <remarks>Documented by Dev10, 2008-08-07</remarks> public void Process() { myReadBuffer = new byte[client.ReceiveBufferSize]; String myCompleteMessage = ""; int numberOfBytesRead = 0; #if DEBUG && debug_output Debug.WriteLine("Connection accepted. Buffer: " + client.ReceiveBufferSize.ToString()); #endif NetworkStream ns = client.GetStream(); string hValue = ""; string hKey = ""; try { // binary data buffer index int bfndx = 0; // Incoming message may be larger than the buffer size. do { numberOfBytesRead = ns.Read(myReadBuffer, 0, myReadBuffer.Length); myCompleteMessage = String.Concat(myCompleteMessage, Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead)); // read buffer index int ndx = 0; do { switch (ParserState) { case RState.METHOD: if (myReadBuffer[ndx] != ' ') HTTPRequest.Method += (char)myReadBuffer[ndx++]; else { ndx++; ParserState = RState.URL; } break; case RState.URL: if (myReadBuffer[ndx] == '?') { ndx++; hKey = ""; HTTPRequest.Execute = true; HTTPRequest.Args = new Hashtable(); ParserState = RState.URLPARM; } else if (myReadBuffer[ndx] != ' ') HTTPRequest.URL += (char)myReadBuffer[ndx++]; else { ndx++; HTTPRequest.URL = Uri.UnescapeDataString(HTTPRequest.URL); ParserState = RState.VERSION; } break; case RState.URLPARM: if (myReadBuffer[ndx] == '=') { ndx++; hValue = ""; ParserState = RState.URLVALUE; } else if (myReadBuffer[ndx] == ' ') { ndx++; HTTPRequest.URL = Uri.UnescapeDataString(HTTPRequest.URL); ParserState = RState.VERSION; } else { hKey += (char)myReadBuffer[ndx++]; } break; case RState.URLVALUE: if (myReadBuffer[ndx] == '&') { ndx++; hKey = Uri.UnescapeDataString(hKey); hValue = Uri.UnescapeDataString(hValue); HTTPRequest.Args[hKey] = HTTPRequest.Args[hKey] != null ? HTTPRequest.Args[hKey] + ", " + hValue : hValue; hKey = ""; ParserState = RState.URLPARM; } else if (myReadBuffer[ndx] == ' ') { ndx++; hKey = Uri.UnescapeDataString(hKey); hValue = Uri.UnescapeDataString(hValue); HTTPRequest.Args[hKey] = HTTPRequest.Args[hKey] != null ? HTTPRequest.Args[hKey] + ", " + hValue : hValue; HTTPRequest.URL = Uri.UnescapeDataString(HTTPRequest.URL); ParserState = RState.VERSION; } else { hValue += (char)myReadBuffer[ndx++]; } break; case RState.VERSION: if (myReadBuffer[ndx] == '\r') ndx++; else if (myReadBuffer[ndx] != '\n') HTTPRequest.Version += (char)myReadBuffer[ndx++]; else { ndx++; hKey = ""; HTTPRequest.Headers = new Hashtable(); ParserState = RState.HEADERKEY; } break; case RState.HEADERKEY: if (myReadBuffer[ndx] == '\r') ndx++; else if (myReadBuffer[ndx] == '\n') { ndx++; if (HTTPRequest.Headers["Content-Length"] != null) { HTTPRequest.BodySize = Convert.ToInt32(HTTPRequest.Headers["Content-Length"]); this.HTTPRequest.BodyData = new byte[this.HTTPRequest.BodySize]; ParserState = RState.BODY; } else ParserState = RState.OK; } else if (myReadBuffer[ndx] == ':') ndx++; else if (myReadBuffer[ndx] != ' ') hKey += (char)myReadBuffer[ndx++]; else { ndx++; hValue = ""; ParserState = RState.HEADERVALUE; } break; case RState.HEADERVALUE: if (myReadBuffer[ndx] == '\r') ndx++; else if (myReadBuffer[ndx] != '\n') hValue += (char)myReadBuffer[ndx++]; else { ndx++; if (!HTTPRequest.Headers.ContainsKey(hKey)) HTTPRequest.Headers.Add(hKey, hValue); hKey = ""; ParserState = RState.HEADERKEY; } break; case RState.BODY: // Append to request BodyData Array.Copy(myReadBuffer, ndx, this.HTTPRequest.BodyData, bfndx, numberOfBytesRead - ndx); bfndx += numberOfBytesRead - ndx; ndx = numberOfBytesRead; if (this.HTTPRequest.BodySize <= bfndx) { ParserState = RState.OK; } break; default: ndx++; break; } } while (ndx < numberOfBytesRead); } while (ns.DataAvailable); #if DEBUG && debug_output // Print out the received message to the console. Debug.WriteLine("Media server received request: " + Environment.NewLine + myCompleteMessage); #endif //Build up the HTTPResponse HTTPResponse.version = "HTTP/1.1"; if (ParserState != RState.OK) HTTPResponse.status = (int)RespState.BAD_REQUEST; else HTTPResponse.status = (int)RespState.OK; this.HTTPResponse.Headers = new Hashtable(); this.HTTPResponse.Headers.Add("Server", Parent.Name); this.HTTPResponse.Headers.Add("Date", DateTime.Now.ToString("r")); this.HTTPResponse.Headers.Add("Cache-Control", "no-cache"); this.HTTPResponse.Headers.Add("Pragma", "no-cache"); this.HTTPResponse.Headers.Add("Expires", "-1"); #if DEBUG && debug_output //Call the overriden SubClass Method to complete the HTTPResponse Content Debug.WriteLine("Preparing reponse."); #endif this.Parent.OnResponse(ref this.HTTPRequest, ref this.HTTPResponse); //Create the Header String string HeadersString = this.HTTPResponse.version + " " + this.Parent.respStatus[this.HTTPResponse.status] + "\r\n"; foreach (DictionaryEntry Header in this.HTTPResponse.Headers) { HeadersString += Header.Key + ": " + Header.Value + "\r\n"; } HeadersString += "\r\n"; byte[] bHeadersString = Encoding.ASCII.GetBytes(HeadersString); #if DEBUG && debug_output // Send headers Debug.WriteLine("Response headers: " + Environment.NewLine + HeadersString); #endif ns.Write(bHeadersString, 0, bHeadersString.Length); ns.Flush(); // Send body (File) if (this.HTTPResponse.mediaStream != null) using (this.HTTPResponse.mediaStream) { byte[] b = new byte[client.SendBufferSize]; int bytesRead; int totalBytes = 0; int totalLength = Convert.ToInt32(this.HTTPResponse.mediaStream.Length); while ((bytesRead = this.HTTPResponse.mediaStream.Read(b, 0, b.Length)) > 0) { ns.Write(b, 0, bytesRead); totalBytes += bytesRead; #if DEBUG && debug_output Debug.WriteLine(string.Format("Sent {0:0,0} / {1:0,0} KBytes ({2:0.0%}).", 1.0 * totalBytes / 1024, 1.0 * totalLength / 1024, 1.0 * totalBytes / totalLength)); #endif } ns.Flush(); this.HTTPResponse.mediaStream.Close(); } } catch (Exception e) { if (e is WebException) Trace.WriteLine("A Webexception in CsHTTPRequest was thrown. URI: " + ((WebException)e).Response.ResponseUri.ToString() + Environment.NewLine + e.ToString()); else Trace.WriteLine("An Exception in CsHTTPRequest was thrown: " + e.ToString()); if (e.InnerException != null && e.InnerException is SocketException) { SocketException se = ((SocketException)e.InnerException); Trace.WriteLine("Socket exception: " + se.ToString()); Trace.WriteLine("Error code: " + se.ErrorCode + " SocketErrorCode: " + se.SocketErrorCode); } } finally { ns.Close(); client.Close(); if (this.HTTPResponse.mediaStream != null) this.HTTPResponse.mediaStream.Close(); } } } }
using System; using System.Collections.Generic; using CoreGraphics; using System.Linq; using AVFoundation; using CoreAnimation; using CoreFoundation; using CoreMedia; using Foundation; using UIKit; namespace SoZoomy { public partial class ViewController : UIViewController { AVCaptureSession session; AVCaptureDevice device; AVCaptureMetadataOutput metadataOutput; Dictionary <int, FaceView> faceViews; int? lockedFaceID; float lockedFaceSize; double lockTime; AVPlayer memeEffect; AVPlayer beepEffect; const float MEME_FLASH_DELAY = 0.7f; const float MEME_ZOOM_DELAY = 1.1f; const float MEME_ZOOM_TIME = 0.25f; IntPtr VideoZoomFactorContext, VideoZoomRampingContext, MemePlaybackContext; float MaxZoom { get { return (float)Math.Min (device != null ? device.ActiveFormat.VideoMaxZoomFactor : 1, 6); } } static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public ViewController () : base (UserInterfaceIdiomIsPhone ? "ViewController_iPhone" : "ViewController_iPad", null) { VideoZoomFactorContext = new IntPtr (); VideoZoomRampingContext = new IntPtr (); MemePlaybackContext = new IntPtr (); } void setupAVCapture () { session = new AVCaptureSession (); session.SessionPreset = AVCaptureSession.PresetHigh; previewView.Session = session; updateCameraSelection (); CALayer rootLayer = previewView.Layer; rootLayer.MasksToBounds = true; // HACK: Remove .ToString() for AVLayerVideoGravity // (previewView.Layer as AVCaptureVideoPreviewLayer).VideoGravity = AVLayerVideoGravity.ResizeAspectFill.ToString(); (previewView.Layer as AVCaptureVideoPreviewLayer).VideoGravity = AVLayerVideoGravity.ResizeAspectFill; previewView.Layer.BackgroundColor = UIColor.Black.CGColor; setupAVFoundationFaceDetection (); if (device != null) { device.AddObserver (this, (NSString) "videoZoomFactor", (NSKeyValueObservingOptions)0, VideoZoomFactorContext); device.AddObserver (this, (NSString) "rampingVideoZoom", (NSKeyValueObservingOptions)0, VideoZoomRampingContext); } session.StartRunning (); } void setupAVFoundationFaceDetection () { faceViews = new Dictionary<int, FaceView> (); metadataOutput = new AVCaptureMetadataOutput (); if (!session.CanAddOutput (metadataOutput)) { metadataOutput = null; return; } var metaDataObjectDelegate = new MetaDataObjectDelegate (); metaDataObjectDelegate.DidOutputMetadataObjectsAction = DidOutputMetadataObjects; metadataOutput.SetDelegate (metaDataObjectDelegate, DispatchQueue.MainQueue); session.AddOutput (metadataOutput); if (metadataOutput.AvailableMetadataObjectTypes != AVMetadataObjectType.Face) { teardownAVFoundationFaceDetection (); return; } metadataOutput.MetadataObjectTypes = AVMetadataObjectType.Face; updateAVFoundationFaceDetection (); } void updateAVFoundationFaceDetection () { if (metadataOutput != null) metadataOutput.ConnectionFromMediaType (AVMediaType.Metadata).Enabled = true; } void teardownAVFoundationFaceDetection () { if (metadataOutput != null) session.RemoveOutput (metadataOutput); metadataOutput = null; faceViews = null; } void teardownAVCapture () { session.StopRunning (); teardownAVFoundationFaceDetection (); device.UnlockForConfiguration (); device.RemoveObserver (this, (NSString) "videoZoomFactor"); device.RemoveObserver (this, (NSString) "rampingVideoZoom"); device = null; session = null; } AVCaptureDeviceInput pickCamera () { AVCaptureDevicePosition desiredPosition = AVCaptureDevicePosition.Back; bool hadError = false; foreach (var device in AVCaptureDevice.DevicesWithMediaType (AVMediaType.Video)) { if (device.Position == desiredPosition) { NSError error = null; AVCaptureDeviceInput input = AVCaptureDeviceInput.FromDevice (device, out error); if (error != null) { hadError = true; displayErrorOnMainQueue (error, "Could not initialize for AVMediaTypeVideo"); } else if (session.CanAddInput (input)) return input; } } if (!hadError) displayErrorOnMainQueue (null, "No camera found for requested orientation"); return null; } void updateCameraSelection () { session.BeginConfiguration (); AVCaptureInput[] oldInputs = session.Inputs; foreach (var oldInput in oldInputs) session.RemoveInput (oldInput); AVCaptureDeviceInput input = pickCamera (); if (input == null) { foreach (var oldInput in oldInputs) session.AddInput (oldInput); } else { session.AddInput (input); device = input.Device; NSError error; if (!device.LockForConfiguration (out error)) Console.WriteLine ("Could not lock for device: " + error.LocalizedDescription); updateAVFoundationFaceDetection (); } session.CommitConfiguration (); } public void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVMetadataObject[] faces, AVCaptureConnection connection) { List<int> unseen = faceViews.Keys.ToList (); List<int> seen = new List<int> (); CATransaction.Begin (); CATransaction.SetValueForKey (NSObject.FromObject (true), (NSString) (CATransaction.DisableActions.ToString ())); foreach (var face in faces) { // HACK: int faceId = (face as AVMetadataFaceObject).FaceID; int faceId = (int)(face as AVMetadataFaceObject).FaceID; unseen.Remove (faceId); seen.Add (faceId); FaceView view; if (faceViews.ContainsKey (faceId)) view = faceViews [faceId]; else { view = new FaceView (); view.Layer.CornerRadius = 10; view.Layer.BorderWidth = 3; view.Layer.BorderColor = UIColor.Green.CGColor; previewView.AddSubview (view); faceViews.Add (faceId, view); view.Id = faceId; view.Callback = TouchCallBack; if (lockedFaceID != null) view.Alpha = 0; } AVMetadataFaceObject adjusted = (AVMetadataFaceObject)(previewView.Layer as AVCaptureVideoPreviewLayer).GetTransformedMetadataObject (face); view.Frame = adjusted.Bounds; } foreach (int faceId in unseen) { FaceView view = faceViews [faceId]; view.RemoveFromSuperview (); faceViews.Remove (faceId); if (faceId == lockedFaceID) clearLockedFace (); } if (lockedFaceID != null) { FaceView view = faceViews [lockedFaceID.GetValueOrDefault ()]; // HACK: Cast resulting nfloat to float // float size = (float)Math.Max (view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor; float size = (float)(Math.Max (view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor); float zoomDelta = lockedFaceSize / size; float lockTime = (float)(CATransition.CurrentMediaTime () - this.lockTime); float zoomRate = (float)(Math.Log (zoomDelta) / lockTime); if (Math.Abs (zoomDelta) > 0.1) device.RampToVideoZoom (zoomRate > 0 ? MaxZoom : 1, zoomRate); } CATransaction.Commit (); } void TouchCallBack (int faceId, FaceView view) { lockedFaceID = faceId; // HACK: Cast double to float // lockedFaceSize = Math.Max (view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor; lockedFaceSize = (float)(Math.Max (view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor); lockTime = CATransition.CurrentMediaTime (); UIView.BeginAnimations (null, IntPtr.Zero); UIView.SetAnimationDuration (0.3f); view.Layer.BorderColor = UIColor.Red.CGColor; foreach (var face in faceViews.Values) { if (face != view) face.Alpha = 0; } UIView.CommitAnimations (); beepEffect.Seek (CMTime.Zero); beepEffect.Play (); } void displayErrorOnMainQueue (NSError error, string message) { DispatchQueue.MainQueue.DispatchAsync (delegate { UIAlertView alert = new UIAlertView (); if (error != null) { alert.Title = message + " (" + error.Code + ")"; alert.Message = error.LocalizedDescription; } else alert.Title = message; alert.AddButton ("Dismiss"); alert.Show (); }); } public override void TouchesEnded (NSSet touches, UIEvent evt) { if (device != null) { if (lockedFaceID != null) clearLockedFace (); else { UITouch touch = (UITouch)touches.AnyObject; CGPoint point = touch.LocationInView (previewView); point = (previewView.Layer as AVCaptureVideoPreviewLayer).CaptureDevicePointOfInterestForPoint (point); if (device.FocusPointOfInterestSupported) device.FocusPointOfInterest = point; if (device.ExposurePointOfInterestSupported) device.ExposurePointOfInterest = point; // HACK: Change AVCaptureFocusMode.ModeAutoFocus to AVCaptureFocusMode.AutoFocus // if (device.IsFocusModeSupported (AVCaptureFocusMode.ModeAutoFocus)) // device.FocusMode = AVCaptureFocusMode.ModeAutoFocus; if (device.IsFocusModeSupported (AVCaptureFocusMode.AutoFocus)) device.FocusMode = AVCaptureFocusMode.AutoFocus; } } base.TouchesEnded (touches, evt); } public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context) { if (device == null) return; if (context == VideoZoomFactorContext) { // HACK: Cast nfloat to float // setZoomSliderValue (device.VideoZoomFactor); setZoomSliderValue ((float)device.VideoZoomFactor); memeButton.Enabled = (device.VideoZoomFactor > 1); } else if (context == VideoZoomRampingContext) { slider.Enabled = device.RampingVideoZoom; if (slider.Enabled && memeEffect.Rate == 0f) clearLockedFace (); } else if (context == MemePlaybackContext) { if (device.TorchAvailable) device.TorchMode = AVCaptureTorchMode.Off; fadeInFaces (); } else Console.WriteLine ("Unhandled observation: " + keyPath); } public override void ViewDidLoad () { base.ViewDidLoad (); string path = NSBundle.MainBundle.PathForResource ("Dramatic2", "m4a"); if (path != null) { memeEffect = AVPlayer.FromUrl (NSUrl.FromFilename (path)); memeEffect.AddObserver (this, (NSString) "rate", (NSKeyValueObservingOptions)0, MemePlaybackContext); } path = NSBundle.MainBundle.PathForResource ("Sosumi", "wav"); if (path != null) beepEffect = AVPlayer.FromUrl (NSUrl.FromFilename (path)); setupAVCapture (); if (MaxZoom == 1f && device != null) { displayErrorOnMainQueue (null, "Device does not support zoom"); slider.Enabled = false; } } public override void WillRotate (UIInterfaceOrientation toInterfaceOrientation, double duration) { (previewView.Layer as AVCaptureVideoPreviewLayer).Connection.VideoOrientation = (AVCaptureVideoOrientation)toInterfaceOrientation; } partial void meme (NSObject sender) { memeEffect.Seek (CMTime.Zero); memeEffect.Play (); NSObject.CancelPreviousPerformRequest (this); PerformSelector (new ObjCRuntime.Selector ("flash"), null, MEME_FLASH_DELAY); PerformSelector (new ObjCRuntime.Selector ("startZoom:"), NSNumber.FromFloat (getZoomSliderValue ()), MEME_ZOOM_DELAY); device.VideoZoomFactor = 1; foreach (var faceId in faceViews.Keys) { FaceView view = faceViews [faceId]; view.Alpha = 0; } } [Export("flash")] void flash () { if (device.TorchAvailable) device.TorchMode = AVCaptureTorchMode.On; } [Export("startZoom:")] void startZoom (NSNumber target) { float zoomPower = (float)Math.Log (target.FloatValue); device.RampToVideoZoom (target.FloatValue, zoomPower / MEME_ZOOM_TIME); } partial void sliderChanged (NSObject sender) { if (device != null && !device.RampingVideoZoom) device.VideoZoomFactor = getZoomSliderValue (); } void clearLockedFace () { lockedFaceID = null; fadeInFaces (); device.CancelVideoZoomRamp (); } void fadeInFaces () { UIView.BeginAnimations (null, IntPtr.Zero); UIView.SetAnimationDuration (0.3); foreach (var face in faceViews.Values) { face.Alpha = 1; face.Layer.BorderColor = UIColor.Green.CGColor; } UIView.CommitAnimations (); } float getZoomSliderValue () { return (float)Math.Pow (MaxZoom, slider.Value); } void setZoomSliderValue (float value) { slider.Value = (float)Math.Log (value) / (float)Math.Log (MaxZoom); } public class MetaDataObjectDelegate : AVCaptureMetadataOutputObjectsDelegate { public Action<AVCaptureMetadataOutput, AVMetadataObject[], AVCaptureConnection> DidOutputMetadataObjectsAction; public override void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVMetadataObject[] faces, AVCaptureConnection connection) { if (DidOutputMetadataObjectsAction != null) DidOutputMetadataObjectsAction (captureOutput, faces, connection); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // namespace System.Reflection.Emit { using System.Runtime.InteropServices; using System; using System.Reflection; using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; [Serializable] internal enum TypeKind { IsArray = 1, IsPointer = 2, IsByRef = 3, } // This is a kind of Type object that will represent the compound expression of a parameter type or field type. internal sealed class SymbolType : TypeInfo { public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){ if(typeInfo==null) return false; return IsAssignableFrom(typeInfo.AsType()); } #region Static Members internal static Type FormCompoundType(char[] bFormat, Type baseType, int curIndex) { // This function takes a string to describe the compound type, such as "[,][]", and a baseType. // // Example: [2..4] - one dimension array with lower bound 2 and size of 3 // Example: [3, 5, 6] - three dimension array with lower bound 3, 5, 6 // Example: [-3, ] [] - one dimensional array of two dimensional array (with lower bound -3 for // the first dimension) // Example: []* - pointer to a one dimensional array // Example: *[] - one dimensional array. The element type is a pointer to the baseType // Example: []& - ByRef of a single dimensional array. Only one & is allowed and it must appear the last! // Example: [?] - Array with unknown bound SymbolType symbolType; int iLowerBound; int iUpperBound; if (bFormat == null || curIndex == bFormat.Length) { // we have consumed all of the format string return baseType; } if (bFormat[curIndex] == '&') { // ByRef case symbolType = new SymbolType(TypeKind.IsByRef); symbolType.SetFormat(bFormat, curIndex, 1); curIndex++; if (curIndex != bFormat.Length) // ByRef has to be the last char!! throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat")); symbolType.SetElementType(baseType); return symbolType; } if (bFormat[curIndex] == '[') { // Array type. symbolType = new SymbolType(TypeKind.IsArray); int startIndex = curIndex; curIndex++; iLowerBound = 0; iUpperBound = -1; // Example: [2..4] - one dimension array with lower bound 2 and size of 3 // Example: [3, 5, 6] - three dimension array with lower bound 3, 5, 6 // Example: [-3, ] [] - one dimensional array of two dimensional array (with lower bound -3 sepcified) while (bFormat[curIndex] != ']') { if (bFormat[curIndex] == '*') { symbolType.m_isSzArray = false; curIndex++; } // consume, one dimension at a time if ((bFormat[curIndex] >= '0' && bFormat[curIndex] <= '9') || bFormat[curIndex] == '-') { bool isNegative = false; if (bFormat[curIndex] == '-') { isNegative = true; curIndex++; } // lower bound is specified. Consume the low bound while (bFormat[curIndex] >= '0' && bFormat[curIndex] <= '9') { iLowerBound = iLowerBound * 10; iLowerBound += bFormat[curIndex] - '0'; curIndex++; } if (isNegative) { iLowerBound = 0 - iLowerBound; } // set the upper bound to be less than LowerBound to indicate that upper bound it not specified yet! iUpperBound = iLowerBound - 1; } if (bFormat[curIndex] == '.') { // upper bound is specified // skip over ".." curIndex++; if (bFormat[curIndex] != '.') { // bad format!! Throw exception throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat")); } curIndex++; // consume the upper bound if ((bFormat[curIndex] >= '0' && bFormat[curIndex] <= '9') || bFormat[curIndex] == '-') { bool isNegative = false; iUpperBound = 0; if (bFormat[curIndex] == '-') { isNegative = true; curIndex++; } // lower bound is specified. Consume the low bound while (bFormat[curIndex] >= '0' && bFormat[curIndex] <= '9') { iUpperBound = iUpperBound * 10; iUpperBound += bFormat[curIndex] - '0'; curIndex++; } if (isNegative) { iUpperBound = 0 - iUpperBound; } if (iUpperBound < iLowerBound) { // User specified upper bound less than lower bound, this is an error. // Throw error exception. throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat")); } } } if (bFormat[curIndex] == ',') { // We have more dimension to deal with. // now set the lower bound, the size, and increase the dimension count! curIndex++; symbolType.SetBounds(iLowerBound, iUpperBound); // clear the lower and upper bound information for next dimension iLowerBound = 0; iUpperBound = -1; } else if (bFormat[curIndex] != ']') { throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat")); } } // The last dimension information symbolType.SetBounds(iLowerBound, iUpperBound); // skip over ']' curIndex++; symbolType.SetFormat(bFormat, startIndex, curIndex - startIndex); // set the base type of array symbolType.SetElementType(baseType); return FormCompoundType(bFormat, symbolType, curIndex); } else if (bFormat[curIndex] == '*') { // pointer type. symbolType = new SymbolType(TypeKind.IsPointer); symbolType.SetFormat(bFormat, curIndex, 1); curIndex++; symbolType.SetElementType(baseType); return FormCompoundType(bFormat, symbolType, curIndex); } return null; } #endregion #region Data Members internal TypeKind m_typeKind; internal Type m_baseType; internal int m_cRank; // count of dimension // If LowerBound and UpperBound is equal, that means one element. // If UpperBound is less than LowerBound, then the size is not specified. internal int[] m_iaLowerBound; internal int[] m_iaUpperBound; // count of dimension private char[] m_bFormat; // format string to form the full name. private bool m_isSzArray = true; #endregion #region Constructor internal SymbolType(TypeKind typeKind) { m_typeKind = typeKind; m_iaLowerBound = new int[4]; m_iaUpperBound = new int[4]; } #endregion #region Internal Members internal void SetElementType(Type baseType) { if (baseType == null) throw new ArgumentNullException("baseType"); Contract.EndContractBlock(); m_baseType = baseType; } private void SetBounds(int lower, int upper) { // Increase the rank, set lower and upper bound if (lower != 0 || upper != -1) m_isSzArray = false; if (m_iaLowerBound.Length <= m_cRank) { // resize the bound array int[] iaTemp = new int[m_cRank * 2]; Array.Copy(m_iaLowerBound, iaTemp, m_cRank); m_iaLowerBound = iaTemp; Array.Copy(m_iaUpperBound, iaTemp, m_cRank); m_iaUpperBound = iaTemp; } m_iaLowerBound[m_cRank] = lower; m_iaUpperBound[m_cRank] = upper; m_cRank++; } internal void SetFormat(char[] bFormat, int curIndex, int length) { // Cache the text display format for this SymbolType char[] bFormatTemp = new char[length]; Array.Copy(bFormat, curIndex, bFormatTemp, 0, length); m_bFormat = bFormatTemp; } #endregion #region Type Overrides internal override bool IsSzArray { get { if (m_cRank > 1) return false; return m_isSzArray; } } public override Type MakePointerType() { return SymbolType.FormCompoundType((new String(m_bFormat) + "*").ToCharArray(), m_baseType, 0); } public override Type MakeByRefType() { return SymbolType.FormCompoundType((new String(m_bFormat) + "&").ToCharArray(), m_baseType, 0); } public override Type MakeArrayType() { return SymbolType.FormCompoundType((new String(m_bFormat) + "[]").ToCharArray(), m_baseType, 0); } public override Type MakeArrayType(int rank) { if (rank <= 0) throw new IndexOutOfRangeException(); Contract.EndContractBlock(); string szrank = ""; if (rank == 1) { szrank = "*"; } else { for(int i = 1; i < rank; i++) szrank += ","; } string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,] SymbolType st = SymbolType.FormCompoundType((new String(m_bFormat) + s).ToCharArray(), m_baseType, 0) as SymbolType; return st; } public override int GetArrayRank() { if (!IsArray) throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); Contract.EndContractBlock(); return m_cRank; } public override Guid GUID { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } } public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override Module Module { get { Type baseType; for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType) baseType).m_baseType); return baseType.Module; } } public override Assembly Assembly { get { Type baseType; for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType) baseType).m_baseType); return baseType.Assembly; } } public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } } public override String Name { get { Type baseType; String sFormat = new String(m_bFormat); for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType) sFormat = new String(((SymbolType)baseType).m_bFormat) + sFormat; return baseType.Name + sFormat; } } public override String FullName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName); } } public override String AssemblyQualifiedName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); } } public override String ToString() { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString); } public override String Namespace { get { return m_baseType.Namespace; } } public override Type BaseType { get { return typeof(System.Array); } } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder, CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } [System.Runtime.InteropServices.ComVisible(true)] public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder, CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override Type GetInterface(String name,bool ignoreCase) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override Type[] GetInterfaces() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override EventInfo GetEvent(String name,BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override EventInfo[] GetEvents() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } [System.Runtime.InteropServices.ComVisible(true)] public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } protected override TypeAttributes GetAttributeFlagsImpl() { // Return the attribute flags of the base type? Type baseType; for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType); return baseType.Attributes; } protected override bool IsArrayImpl() { return m_typeKind == TypeKind.IsArray; } protected override bool IsPointerImpl() { return m_typeKind == TypeKind.IsPointer; } protected override bool IsByRefImpl() { return m_typeKind == TypeKind.IsByRef; } protected override bool IsPrimitiveImpl() { return false; } protected override bool IsValueTypeImpl() { return false; } protected override bool IsCOMObjectImpl() { return false; } public override bool IsConstructedGenericType { get { return false; } } public override Type GetElementType() { return m_baseType; } protected override bool HasElementTypeImpl() { return m_baseType != null; } public override Type UnderlyingSystemType { get { return this; } } public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } public override bool IsDefined (Type attributeType, bool inherit) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); } #endregion } }
using NUnit.Framework; using System; using FilenameBuddy; using System.IO; using Shouldly; namespace FilenameBuddyTests { [TestFixture()] public class Test { [SetUp] public void Setup() { Filename.SetCurrentDirectory(Directory.GetCurrentDirectory() + @"\Content\"); } /// <summary> /// get the current working directory /// </summary> /// <returns>The location.</returns> string progLocation() { return Filename.ReplaceSlashes(Directory.GetCurrentDirectory() + @"\Content\"); } [Test()] public void DefaultConstructor() { //default constructor = no filename Filename dude = new Filename(); Assert.IsTrue(string.IsNullOrEmpty(dude.File)); } [Test()] public void Constructor() { //set the filename in teh constructor Filename dude = new Filename("test"); dude.File.ShouldBe(progLocation() + @"test"); } [Test()] public void SetFilename() { //set the name and get it back Filename dude = new Filename(); dude.File = "test"; Assert.AreEqual("test", dude.File); } [Test()] public void SetAbsFilenameGetRelFilename() { //set the name and get it back Filename dude = new Filename(); dude.File = progLocation() + @"Buttnuts\test.txt"; Assert.AreEqual(@"Buttnuts/test.txt", dude.GetRelFilename()); } [Test()] public void SetRelFilename() { Filename dude = new Filename(); dude.SetRelFilename("test"); dude.File.ShouldBe(progLocation() + @"test"); } [Test()] public void SetRelFilename1() { Filename dude = new Filename(); dude.SetRelFilename(@"Buttnuts\test.txt"); dude.File.ShouldBe(progLocation() + @"Buttnuts/test.txt"); } [Test()] public void GetPath() { Filename dude = new Filename(); dude.SetRelFilename("test"); Assert.AreEqual(progLocation(), dude.GetPath()); } [Test()] public void GetPathWithExt() { Filename dude = new Filename(); dude.SetRelFilename("test.txt"); Assert.AreEqual(progLocation(), dude.GetPath()); } [Test()] public void GetPathWithSub() { Filename dude = new Filename(); dude.SetRelFilename("test.txt"); Assert.AreEqual(progLocation(), dude.GetPath()); } [Test()] public void GetRelPath() { Filename dude = new Filename(); dude.SetRelFilename(@"Buttnuts\test.txt"); Assert.AreEqual(@"Buttnuts/", dude.GetRelPath()); } [Test()] public void GetRelPath1() { Filename dude = new Filename(); dude.SetRelFilename(@"Buttnuts\assnuts\test.txt"); Assert.AreEqual(@"Buttnuts/assnuts/", dude.GetRelPath()); } [Test()] public void GetFilename() { Filename dude = new Filename(); dude.SetRelFilename(@"Content\Buttnuts\assnuts\test.txt"); Assert.AreEqual(@"test.txt", dude.GetFile()); } [Test()] public void GetFilename1() { Filename dude = new Filename(); dude.SetRelFilename(@"Content\Buttnuts\assnuts\test"); Assert.AreEqual(@"test", dude.GetFile()); } [Test()] public void GetFileExt() { Filename dude = new Filename(); dude.SetRelFilename(@"Content\Buttnuts\assnuts\test.txt"); Assert.AreEqual(@".txt", dude.GetFileExt()); } [Test()] public void GetFileExt1() { Filename dude = new Filename(); dude.SetRelFilename(@"Content\Buttnuts\assnuts\test"); Assert.AreEqual(@"", dude.GetFileExt()); } [Test()] public void GetFileNoExt() { Filename dude = new Filename(); dude.SetRelFilename(@"Content\Buttnuts\assnuts\test.txt"); Assert.AreEqual(@"test", dude.GetFileNoExt()); } [Test()] public void GetFileNoExtBreakIt() { Filename dude = new Filename(); dude.SetRelFilename(@"Content\Buttnuts\assnuts\test"); Assert.AreEqual(@"test", dude.GetFileNoExt()); } [Test()] public void GetPathFileNoExt() { Filename dude = new Filename(); string testFile = @"Buttnuts\assnuts\test.txt"; dude.SetRelFilename(testFile); Assert.AreEqual(progLocation() + @"Buttnuts/assnuts/test", dude.GetPathFileNoExt()); } [Test()] public void GetRelPathFileNoExt() { Filename dude = new Filename(); string testFile = @"Buttnuts\assnuts\test.txt"; dude.SetRelFilename(testFile); Assert.AreEqual(@"Buttnuts/assnuts/test", dude.GetRelPathFileNoExt()); } [Test()] public void GetRelFilename() { Filename dude = new Filename(); string testFile = @"Buttnuts\assnuts\test.txt"; dude.SetRelFilename(testFile); Assert.AreEqual(@"Buttnuts/assnuts/test.txt", dude.GetRelFilename()); } [Test()] public void SetCurrentDirectory() { Filename.SetCurrentDirectory(@"c:assnuts\shitass\Content\poopstains"); Filename dude = new Filename(); string testFile = @"Buttnuts\assnuts\test.txt"; dude.SetRelFilename(testFile); dude.File.ShouldBe(Filename.ReplaceSlashes(@"c:assnuts/shitass/Content/Buttnuts/assnuts/test.txt")); } [Test()] public void GetRelFilename1() { Filename dude = new Filename(); string testFile = @"test.txt"; dude.SetRelFilename(testFile); Assert.AreEqual(@"test.txt", dude.GetRelFilename()); } [Test()] public void GetRelFilename2() { Filename dude = new Filename(); string testFile = @"test.txt"; dude.SetRelFilename(testFile); Assert.AreEqual(@"test.txt", dude.GetRelFilename()); } [Test()] public void FilenameNoExt() { Filename dude = new Filename(); string testFile = @"test.txt"; dude.SetRelFilename(testFile); Assert.AreEqual(@"test", dude.GetFileNoExt()); } [Test()] public void FilenameNoExt1() { Filename dude = new Filename(); string testFile = @"windows.xna\test.txt"; dude.SetRelFilename(testFile); Assert.AreEqual(@"test", dude.GetFileNoExt()); } [Test()] public void GetExtension() { Filename dude = new Filename(); string testFile = @"windows.xna\test.longextension"; dude.SetRelFilename(testFile); Assert.AreEqual(@".longextension", dude.GetFileExt()); } [Test] public void Comparison() { var dude1 = new Filename("dude"); var dude2 = new Filename("dude"); Assert.IsTrue(dude1.Compare(dude2)); } [Test] public void Comparison_false() { var dude1 = new Filename("dude"); var dude2 = new Filename("cat"); Assert.IsFalse(dude1.Compare(dude2)); } [Test] public void HasFilename1() { var dude = new Filename(); dude.HasFilename.ShouldBeFalse(); } [Test] public void HasFilename2() { var dude = new Filename("dude"); dude.HasFilename.ShouldBeTrue(); } [Test] public void HasFilename3() { var dude = new Filename(); dude.File = "dude"; dude.HasFilename.ShouldBeTrue(); } [Test] public void HasFilename4() { var dude1 = new Filename("dude"); var dude2 = new Filename(dude1); dude2.HasFilename.ShouldBeTrue(); } [Test] public void HasFilename5() { var dude1 = new Filename(); var dude2 = new Filename(dude1); dude2.HasFilename.ShouldBeFalse(); } [Test] public void HasFilename6() { var dude1 = new Filename(); dude1.SetRelFilename("dude"); dude1.HasFilename.ShouldBeTrue(); } [Test] public void SetFromRelativeFilename() { Filename originalLocation = new Filename(); string testFile = @"Buttnuts\assnuts\test.txt"; originalLocation.SetRelFilename(testFile); var secondFilename = new Filename(originalLocation, "catpants\\cat.png"); secondFilename.GetRelFilename().ShouldBe(@"Buttnuts/assnuts/catpants/cat.png"); } [TestCase(@"test1\test.txt", @"test2.txt", @"test1/test2.txt")] [TestCase(@"test1\test.txt", @"test3\test2.txt", @"test1/test3/test2.txt")] [TestCase(@"test1\test2\test3.txt", @"..\test4\test5.txt", @"test1/test4/test5.txt")] public void SetFilenameRelativeToPath(string original, string target, string expectedResult) { var originalFilename = new Filename(original); var targetFilename = new Filename(); targetFilename.SetFilenameRelativeToPath(originalFilename, target); targetFilename.GetRelFilename().ShouldBe(expectedResult); } [TestCase(@"test1\test.txt", @"test1\test2.txt", @"test2.txt")] [TestCase(@"test1\test.txt", @"test1\test3\test2.txt", @"test3/test2.txt")] [TestCase(@"test1\test2\test3.txt", @"test1\test4\test5.txt", @"../test4/test5.txt")] public void GetFilenameRelativeToPath(string original, string target, string expectedResult) { var originalFilename = new Filename(original); var targetFilename = new Filename(target); targetFilename.GetFilenameRelativeToPath(originalFilename).ShouldBe(expectedResult); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Xunit; namespace System.Numerics.Tests { public class cast_fromTest { public delegate void ExceptionGenerator(); private const int NumberOfRandomIterations = 10; private static Random s_random = new Random(100); [Fact] public static void RunByteExplicitCastFromBigIntegerTests() { byte value = 0; BigInteger bigInteger; // Byte Explicit Cast from BigInteger: Random value < Byte.MinValue bigInteger = GenerateRandomBigIntegerLessThan(byte.MinValue, s_random); value = bigInteger.ToByteArray()[0]; Assert.Throws<OverflowException>(() => VerifyByteExplicitCastFromBigInteger(value, bigInteger)); // Byte Explicit Cast from BigInteger: Byte.MinValue - 1 bigInteger = new BigInteger(byte.MinValue); bigInteger -= BigInteger.One; value = bigInteger.ToByteArray()[0]; Assert.Throws<OverflowException>(() => VerifyByteExplicitCastFromBigInteger(value, bigInteger)); // Byte Explicit Cast from BigInteger: Byte.MinValue VerifyByteExplicitCastFromBigInteger(byte.MinValue); // Byte Explicit Cast from BigInteger: 0 VerifyByteExplicitCastFromBigInteger(0); // Byte Explicit Cast from BigInteger: 1 VerifyByteExplicitCastFromBigInteger(1); // Byte Explicit Cast from BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyByteExplicitCastFromBigInteger((byte)s_random.Next(1, byte.MaxValue)); } // Byte Explicit Cast from BigInteger: Byte.MaxValue + 1 bigInteger = new BigInteger(byte.MaxValue); bigInteger += BigInteger.One; value = bigInteger.ToByteArray()[0]; Assert.Throws<OverflowException>(() => VerifyByteExplicitCastFromBigInteger(value, bigInteger)); // Byte Explicit Cast from BigInteger: Random value > Byte.MaxValue bigInteger = GenerateRandomBigIntegerGreaterThan(byte.MaxValue, s_random); value = bigInteger.ToByteArray()[0]; Assert.Throws<OverflowException>(() => VerifyByteExplicitCastFromBigInteger(value, bigInteger)); } [Fact] public static void RunSByteExplicitCastFromBigIntegerTests() { sbyte value = 0; BigInteger bigInteger; // SByte Explicit Cast from BigInteger: Random value < SByte.MinValue bigInteger = GenerateRandomBigIntegerLessThan(sbyte.MinValue, s_random); value = unchecked((sbyte)bigInteger.ToByteArray()[0]); Assert.Throws<OverflowException>(() => VerifySByteExplicitCastFromBigInteger(value, bigInteger)); // SByte Explicit Cast from BigInteger: SByte.MinValue - 1 bigInteger = new BigInteger(sbyte.MinValue); bigInteger -= BigInteger.One; value = (sbyte)bigInteger.ToByteArray()[0]; Assert.Throws<OverflowException>(() => VerifySByteExplicitCastFromBigInteger(value, bigInteger)); // SByte Explicit Cast from BigInteger: SByte.MinValue VerifySByteExplicitCastFromBigInteger(sbyte.MinValue); // SByte Explicit Cast from BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySByteExplicitCastFromBigInteger((sbyte)s_random.Next(sbyte.MinValue, 0)); } // SByte Explicit Cast from BigInteger: -1 VerifySByteExplicitCastFromBigInteger(-1); // SByte Explicit Cast from BigInteger: 0 VerifySByteExplicitCastFromBigInteger(0); // SByte Explicit Cast from BigInteger: 1 VerifySByteExplicitCastFromBigInteger(1); // SByte Explicit Cast from BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySByteExplicitCastFromBigInteger((sbyte)s_random.Next(1, sbyte.MaxValue)); } // SByte Explicit Cast from BigInteger: SByte.MaxValue VerifySByteExplicitCastFromBigInteger(sbyte.MaxValue); // SByte Explicit Cast from BigInteger: SByte.MaxValue + 1 bigInteger = new BigInteger(sbyte.MaxValue); bigInteger += BigInteger.One; value = unchecked((sbyte)bigInteger.ToByteArray()[0]); Assert.Throws<OverflowException>(() => VerifySByteExplicitCastFromBigInteger(value, bigInteger)); // SByte Explicit Cast from BigInteger: Random value > SByte.MaxValue bigInteger = GenerateRandomBigIntegerGreaterThan((ulong)sbyte.MaxValue, s_random); value = unchecked((sbyte)bigInteger.ToByteArray()[0]); Assert.Throws<OverflowException>(() => VerifySByteExplicitCastFromBigInteger(value, bigInteger)); } [Fact] public static void RunUInt16ExplicitCastFromBigIntegerTests() { ushort value; BigInteger bigInteger; // UInt16 Explicit Cast from BigInteger: Random value < UInt16.MinValue bigInteger = GenerateRandomBigIntegerLessThan(ushort.MinValue, s_random); value = BitConverter.ToUInt16(ByteArrayMakeMinSize(bigInteger.ToByteArray(), 2), 0); Assert.Throws<OverflowException>(() => VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger)); // UInt16 Explicit Cast from BigInteger: UInt16.MinValue - 1 bigInteger = new BigInteger(ushort.MinValue); bigInteger -= BigInteger.One; value = BitConverter.ToUInt16(new byte[] { 0xff, 0xff }, 0); Assert.Throws<OverflowException>(() => VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger)); // UInt16 Explicit Cast from BigInteger: UInt16.MinValue VerifyUInt16ExplicitCastFromBigInteger(ushort.MinValue); // UInt16 Explicit Cast from BigInteger: 0 VerifyUInt16ExplicitCastFromBigInteger(0); // UInt16 Explicit Cast from BigInteger: 1 VerifyUInt16ExplicitCastFromBigInteger(1); // UInt16 Explicit Cast from BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyUInt16ExplicitCastFromBigInteger((ushort)s_random.Next(1, ushort.MaxValue)); } // UInt16 Explicit Cast from BigInteger: UInt16.MaxValue VerifyUInt16ExplicitCastFromBigInteger(ushort.MaxValue); // UInt16 Explicit Cast from BigInteger: UInt16.MaxValue + 1 bigInteger = new BigInteger(ushort.MaxValue); bigInteger += BigInteger.One; value = BitConverter.ToUInt16(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger)); // UInt16 Explicit Cast from BigInteger: Random value > UInt16.MaxValue bigInteger = GenerateRandomBigIntegerGreaterThan(ushort.MaxValue, s_random); value = BitConverter.ToUInt16(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger)); } [Fact] public static void RunInt16ExplicitCastFromBigIntegerTests() { short value; BigInteger bigInteger; // Int16 Explicit Cast from BigInteger: Random value < Int16.MinValue bigInteger = GenerateRandomBigIntegerLessThan(short.MinValue, s_random); value = BitConverter.ToInt16(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyInt16ExplicitCastFromBigInteger(value, bigInteger)); // Int16 Explicit Cast from BigInteger: Int16.MinValue - 1 bigInteger = new BigInteger(short.MinValue); bigInteger -= BigInteger.One; value = BitConverter.ToInt16(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyInt16ExplicitCastFromBigInteger(value, bigInteger)); // Int16 Explicit Cast from BigInteger: Int16.MinValue VerifyInt16ExplicitCastFromBigInteger(short.MinValue); // Int16 Explicit Cast from BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt16ExplicitCastFromBigInteger((short)s_random.Next(short.MinValue, 0)); } // Int16 Explicit Cast from BigInteger: -1 VerifyInt16ExplicitCastFromBigInteger(-1); // Int16 Explicit Cast from BigInteger: 0 VerifyInt16ExplicitCastFromBigInteger(0); // Int16 Explicit Cast from BigInteger: 1 VerifyInt16ExplicitCastFromBigInteger(1); // Int16 Explicit Cast from BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt16ExplicitCastFromBigInteger((short)s_random.Next(1, short.MaxValue)); } // Int16 Explicit Cast from BigInteger: Int16.MaxValue VerifyInt16ExplicitCastFromBigInteger(short.MaxValue); // Int16 Explicit Cast from BigInteger: Int16.MaxValue + 1 bigInteger = new BigInteger(short.MaxValue); bigInteger += BigInteger.One; value = BitConverter.ToInt16(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyInt16ExplicitCastFromBigInteger(value, bigInteger)); // Int16 Explicit Cast from BigInteger: Random value > Int16.MaxValue bigInteger = GenerateRandomBigIntegerGreaterThan((ulong)short.MaxValue, s_random); value = BitConverter.ToInt16(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyInt16ExplicitCastFromBigInteger(value, bigInteger)); } [Fact] public static void RunUInt32ExplicitCastFromBigIntegerTests() { uint value; BigInteger bigInteger; // UInt32 Explicit Cast from BigInteger: Random value < UInt32.MinValue bigInteger = GenerateRandomBigIntegerLessThan(uint.MinValue, s_random); value = BitConverter.ToUInt32(ByteArrayMakeMinSize(bigInteger.ToByteArray(), 4), 0); Assert.Throws<OverflowException>(() => VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger)); // UInt32 Explicit Cast from BigInteger: UInt32.MinValue - 1 bigInteger = new BigInteger(uint.MinValue); bigInteger -= BigInteger.One; value = BitConverter.ToUInt32(new byte[] { 0xff, 0xff, 0xff, 0xff }, 0); Assert.Throws<OverflowException>(() => VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger)); // UInt32 Explicit Cast from BigInteger: UInt32.MinValue VerifyUInt32ExplicitCastFromBigInteger(uint.MinValue); // UInt32 Explicit Cast from BigInteger: 0 VerifyUInt32ExplicitCastFromBigInteger(0); // UInt32 Explicit Cast from BigInteger: 1 VerifyUInt32ExplicitCastFromBigInteger(1); // UInt32 Explicit Cast from BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyUInt32ExplicitCastFromBigInteger((uint)(uint.MaxValue * s_random.NextDouble())); } // UInt32 Explicit Cast from BigInteger: UInt32.MaxValue VerifyUInt32ExplicitCastFromBigInteger(uint.MaxValue); // UInt32 Explicit Cast from BigInteger: UInt32.MaxValue + 1 bigInteger = new BigInteger(uint.MaxValue); bigInteger += BigInteger.One; value = BitConverter.ToUInt32(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger)); // UInt32 Explicit Cast from BigInteger: Random value > UInt32.MaxValue bigInteger = GenerateRandomBigIntegerGreaterThan(uint.MaxValue, s_random); value = BitConverter.ToUInt32(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger)); } [Fact] public static void RunInt32ExplicitCastFromBigIntegerTests() { int value; BigInteger bigInteger; // Int32 Explicit Cast from BigInteger: Random value < Int32.MinValue bigInteger = GenerateRandomBigIntegerLessThan(int.MinValue, s_random); value = BitConverter.ToInt32(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyInt32ExplicitCastFromBigInteger(value, bigInteger)); // Int32 Explicit Cast from BigInteger: Int32.MinValue - 1 bigInteger = new BigInteger(int.MinValue); bigInteger -= BigInteger.One; value = BitConverter.ToInt32(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyInt32ExplicitCastFromBigInteger(value, bigInteger)); // Int32 Explicit Cast from BigInteger: Int32.MinValue VerifyInt32ExplicitCastFromBigInteger(int.MinValue); // Int32 Explicit Cast from BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt32ExplicitCastFromBigInteger((int)s_random.Next(int.MinValue, 0)); } // Int32 Explicit Cast from BigInteger: -1 VerifyInt32ExplicitCastFromBigInteger(-1); // Int32 Explicit Cast from BigInteger: 0 VerifyInt32ExplicitCastFromBigInteger(0); // Int32 Explicit Cast from BigInteger: 1 VerifyInt32ExplicitCastFromBigInteger(1); // Int32 Explicit Cast from BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt32ExplicitCastFromBigInteger((int)s_random.Next(1, int.MaxValue)); } // Int32 Explicit Cast from BigInteger: Int32.MaxValue VerifyInt32ExplicitCastFromBigInteger(int.MaxValue); // Int32 Explicit Cast from BigInteger: Int32.MaxValue + 1 bigInteger = new BigInteger(int.MaxValue); bigInteger += BigInteger.One; value = BitConverter.ToInt32(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyInt32ExplicitCastFromBigInteger(value, bigInteger)); // Int32 Explicit Cast from BigInteger: Random value > Int32.MaxValue bigInteger = GenerateRandomBigIntegerGreaterThan(int.MaxValue, s_random); value = BitConverter.ToInt32(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyInt32ExplicitCastFromBigInteger(value, bigInteger)); } [Fact] public static void RunUInt64ExplicitCastFromBigIntegerTests() { ulong value; BigInteger bigInteger; // UInt64 Explicit Cast from BigInteger: Random value < UInt64.MinValue bigInteger = GenerateRandomBigIntegerLessThan(0, s_random); value = BitConverter.ToUInt64(ByteArrayMakeMinSize(bigInteger.ToByteArray(), 8), 0); Assert.Throws<OverflowException>(() => VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger)); // UInt64 Explicit Cast from BigInteger: UInt64.MinValue - 1 bigInteger = new BigInteger(ulong.MinValue); bigInteger -= BigInteger.One; value = BitConverter.ToUInt64(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, 0); Assert.Throws<OverflowException>(() => VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger)); // UInt64 Explicit Cast from BigInteger: UInt64.MinValue VerifyUInt64ExplicitCastFromBigInteger(ulong.MinValue); // UInt64 Explicit Cast from BigInteger: 0 VerifyUInt64ExplicitCastFromBigInteger(0); // UInt64 Explicit Cast from BigInteger: 1 VerifyUInt64ExplicitCastFromBigInteger(1); // UInt64 Explicit Cast from BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyUInt64ExplicitCastFromBigInteger((ulong)(ulong.MaxValue * s_random.NextDouble())); } // UInt64 Explicit Cast from BigInteger: UInt64.MaxValue VerifyUInt64ExplicitCastFromBigInteger(ulong.MaxValue); // UInt64 Explicit Cast from BigInteger: UInt64.MaxValue + 1 bigInteger = new BigInteger(ulong.MaxValue); bigInteger += BigInteger.One; value = BitConverter.ToUInt64(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger)); // UInt64 Explicit Cast from BigInteger: Random value > UInt64.MaxValue bigInteger = GenerateRandomBigIntegerGreaterThan(ulong.MaxValue, s_random); value = BitConverter.ToUInt64(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger)); } [Fact] public static void RunInt64ExplicitCastFromBigIntegerTests() { long value; BigInteger bigInteger; // Int64 Explicit Cast from BigInteger: Random value < Int64.MinValue bigInteger = GenerateRandomBigIntegerLessThan(long.MinValue, s_random); value = BitConverter.ToInt64(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyInt64ExplicitCastFromBigInteger(value, bigInteger)); // Int64 Explicit Cast from BigInteger: Int64.MinValue - 1 bigInteger = new BigInteger(long.MinValue); bigInteger -= BigInteger.One; value = BitConverter.ToInt64(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyInt64ExplicitCastFromBigInteger(value, bigInteger)); // Int64 Explicit Cast from BigInteger: Int64.MinValue VerifyInt64ExplicitCastFromBigInteger(long.MinValue); // Int64 Explicit Cast from BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt64ExplicitCastFromBigInteger(((long)(long.MaxValue * s_random.NextDouble())) - long.MaxValue); } // Int64 Explicit Cast from BigInteger: -1 VerifyInt64ExplicitCastFromBigInteger(-1); // Int64 Explicit Cast from BigInteger: 0 VerifyInt64ExplicitCastFromBigInteger(0); // Int64 Explicit Cast from BigInteger: 1 VerifyInt64ExplicitCastFromBigInteger(1); // Int64 Explicit Cast from BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyInt64ExplicitCastFromBigInteger((long)(long.MaxValue * s_random.NextDouble())); } // Int64 Explicit Cast from BigInteger: Int64.MaxValue VerifyInt64ExplicitCastFromBigInteger(long.MaxValue); // Int64 Explicit Cast from BigInteger: Int64.MaxValue + 1 bigInteger = new BigInteger(long.MaxValue); bigInteger += BigInteger.One; value = BitConverter.ToInt64(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyInt64ExplicitCastFromBigInteger(value, bigInteger)); // Int64 Explicit Cast from BigInteger: Random value > Int64.MaxValue bigInteger = GenerateRandomBigIntegerGreaterThan(long.MaxValue, s_random); value = BitConverter.ToInt64(bigInteger.ToByteArray(), 0); Assert.Throws<OverflowException>(() => VerifyInt64ExplicitCastFromBigInteger(value, bigInteger)); } [Fact] public static void RunSingleExplicitCastFromBigIntegerTests() { BigInteger bigInteger; // Single Explicit Cast from BigInteger: Random value < Single.MinValue bigInteger = GenerateRandomBigIntegerLessThan(float.MinValue * 2.0, s_random); VerifySingleExplicitCastFromBigInteger(float.NegativeInfinity, bigInteger); // Single Explicit Cast from BigInteger: Single.MinValue - 1 bigInteger = new BigInteger(float.MinValue); bigInteger -= BigInteger.One; VerifySingleExplicitCastFromBigInteger(float.MinValue, bigInteger); // Single Explicit Cast from BigInteger: Single.MinValue VerifySingleExplicitCastFromBigInteger(float.MinValue); // Single Explicit Cast from BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySingleExplicitCastFromBigInteger(((float)(float.MaxValue * s_random.NextDouble())) - float.MaxValue); } // Single Explicit Cast from BigInteger: Random Negative Non-integral > -100 for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySingleExplicitCastFromBigInteger(((float)(100 * s_random.NextDouble())) - 100); } // Single Explicit Cast from BigInteger: -1 VerifySingleExplicitCastFromBigInteger(-1); // Single Explicit Cast from BigInteger: 0 VerifySingleExplicitCastFromBigInteger(0); // Single Explicit Cast from BigInteger: 1 VerifySingleExplicitCastFromBigInteger(1); // Single Explicit Cast from BigInteger: Random Positive Non-integral < 100 for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySingleExplicitCastFromBigInteger((float)(100 * s_random.NextDouble())); } // Single Explicit Cast from BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifySingleExplicitCastFromBigInteger((float)(float.MaxValue * s_random.NextDouble())); } // Single Explicit Cast from BigInteger: Single.MaxValue + 1 bigInteger = new BigInteger(float.MaxValue); bigInteger += BigInteger.One; VerifySingleExplicitCastFromBigInteger(float.MaxValue, bigInteger); // Single Explicit Cast from BigInteger: Random value > Single.MaxValue bigInteger = GenerateRandomBigIntegerGreaterThan((double)float.MaxValue * 2, s_random); VerifySingleExplicitCastFromBigInteger(float.PositiveInfinity, bigInteger); // Single Explicit Cast from BigInteger: value < Single.MaxValue but can not be accurately represented in a Single bigInteger = new BigInteger(16777217); VerifySingleExplicitCastFromBigInteger(16777216f, bigInteger); // Single Explicit Cast from BigInteger: Single.MinValue < value but can not be accurately represented in a Single bigInteger = new BigInteger(-16777217); VerifySingleExplicitCastFromBigInteger(-16777216f, bigInteger); } [Fact] public static void RunDoubleExplicitCastFromBigIntegerTests() { BigInteger bigInteger; // Double Explicit Cast from BigInteger: Random value < Double.MinValue bigInteger = GenerateRandomBigIntegerLessThan(double.MinValue, s_random); bigInteger *= 2; VerifyDoubleExplicitCastFromBigInteger(double.NegativeInfinity, bigInteger); // Double Explicit Cast from BigInteger: Double.MinValue - 1 bigInteger = new BigInteger(double.MinValue); bigInteger -= BigInteger.One; VerifyDoubleExplicitCastFromBigInteger(double.MinValue, bigInteger); // Double Explicit Cast from BigInteger: Double.MinValue VerifyDoubleExplicitCastFromBigInteger(double.MinValue); // Double Explicit Cast from BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDoubleExplicitCastFromBigInteger(((double)(double.MaxValue * s_random.NextDouble())) - double.MaxValue); } // Double Explicit Cast from BigInteger: Random Negative Non-integral > -100 for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDoubleExplicitCastFromBigInteger(((double)(100 * s_random.NextDouble())) - 100); } // Double Explicit Cast from BigInteger: -1 VerifyDoubleExplicitCastFromBigInteger(-1); // Double Explicit Cast from BigInteger: 0 VerifyDoubleExplicitCastFromBigInteger(0); // Double Explicit Cast from BigInteger: 1 VerifyDoubleExplicitCastFromBigInteger(1); // Double Explicit Cast from BigInteger: Random Positive Non-integral < 100 for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDoubleExplicitCastFromBigInteger((double)(100 * s_random.NextDouble())); } // Double Explicit Cast from BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDoubleExplicitCastFromBigInteger((double)(double.MaxValue * s_random.NextDouble())); } // Double Explicit Cast from BigInteger: Double.MaxValue VerifyDoubleExplicitCastFromBigInteger(double.MaxValue); // Double Explicit Cast from BigInteger: Double.MaxValue + 1 bigInteger = new BigInteger(double.MaxValue); bigInteger += BigInteger.One; VerifyDoubleExplicitCastFromBigInteger(double.MaxValue, bigInteger); // Double Explicit Cast from BigInteger: Double.MinValue - 1 bigInteger = new BigInteger(double.MinValue); bigInteger -= BigInteger.One; VerifyDoubleExplicitCastFromBigInteger(double.MinValue, bigInteger); // Double Explicit Cast from BigInteger: Random value > Double.MaxValue bigInteger = GenerateRandomBigIntegerGreaterThan(double.MaxValue, s_random); bigInteger *= 2; VerifyDoubleExplicitCastFromBigInteger(double.PositiveInfinity, bigInteger); // Double Explicit Cast from BigInteger: Random value < -Double.MaxValue VerifyDoubleExplicitCastFromBigInteger(double.NegativeInfinity, -bigInteger); // Double Explicit Cast from BigInteger: very large values (more than Int32.MaxValue bits) should be infinity DoubleExplicitCastFromLargeBigIntegerTests(128, 1); // Double Explicit Cast from BigInteger: value < Double.MaxValue but can not be accurately represented in a Double bigInteger = new BigInteger(9007199254740993); VerifyDoubleExplicitCastFromBigInteger(9007199254740992, bigInteger); // Double Explicit Cast from BigInteger: Double.MinValue < value but can not be accurately represented in a Double bigInteger = new BigInteger(-9007199254740993); VerifyDoubleExplicitCastFromBigInteger(-9007199254740992, bigInteger); } [Fact] [OuterLoop] public static void RunDoubleExplicitCastFromLargeBigIntegerTests() { DoubleExplicitCastFromLargeBigIntegerTests(0, 4, 32, 3); } [Fact] public static void RunDecimalExplicitCastFromBigIntegerTests() { int[] bits = new int[3]; uint temp2; bool carry; byte[] temp; decimal value; BigInteger bigInteger; // Decimal Explicit Cast from BigInteger: Random value < Decimal.MinValue for (int i = 0; i < NumberOfRandomIterations; ++i) { bigInteger = GenerateRandomBigIntegerLessThan(decimal.MinValue, s_random); temp = bigInteger.ToByteArray(); carry = true; for (int j = 0; j < 3; j++) { temp2 = BitConverter.ToUInt32(temp, 4 * j); temp2 = ~temp2; if (carry) { carry = false; temp2 += 1; if (temp2 == 0) { carry = true; } } bits[j] = unchecked((int)temp2); } value = new decimal(bits[0], bits[1], bits[2], true, 0); Assert.Throws<OverflowException>(() => VerifyDecimalExplicitCastFromBigInteger(value, bigInteger)); } // Decimal Explicit Cast from BigInteger: Decimal.MinValue - 1 bigInteger = new BigInteger(decimal.MinValue); bigInteger -= BigInteger.One; temp = bigInteger.ToByteArray(); carry = true; for (int j = 0; j < 3; j++) { temp2 = BitConverter.ToUInt32(temp, 4 * j); temp2 = ~temp2; if (carry) { carry = false; temp2 = unchecked(temp2 + 1); if (temp2 == 0) { carry = true; } } bits[j] = (int)temp2; } value = new decimal(bits[0], bits[1], bits[2], true, 0); Assert.Throws<OverflowException>(() => VerifyDecimalExplicitCastFromBigInteger(value, bigInteger)); // Decimal Explicit Cast from BigInteger: Decimal.MinValue VerifyDecimalExplicitCastFromBigInteger(decimal.MinValue); // Decimal Explicit Cast from BigInteger: Random Negative for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDecimalExplicitCastFromBigInteger(((decimal)((double)decimal.MaxValue * s_random.NextDouble())) - decimal.MaxValue); } // Decimal Explicit Cast from BigInteger: Random Negative Non-Integral > -100 for (int i = 0; i < NumberOfRandomIterations; ++i) { value = (decimal)(100 * s_random.NextDouble() - 100); VerifyDecimalExplicitCastFromBigInteger(decimal.Truncate(value), new BigInteger(value)); } // Decimal Explicit Cast from BigInteger: -1 VerifyDecimalExplicitCastFromBigInteger(-1); // Decimal Explicit Cast from BigInteger: 0 VerifyDecimalExplicitCastFromBigInteger(0); // Decimal Explicit Cast from BigInteger: 1 VerifyDecimalExplicitCastFromBigInteger(1); // Decimal Explicit Cast from BigInteger: Random Positive Non-Integral < 100 for (int i = 0; i < NumberOfRandomIterations; ++i) { value = (decimal)(100 * s_random.NextDouble()); VerifyDecimalExplicitCastFromBigInteger(decimal.Truncate(value), new BigInteger(value)); } // Decimal Explicit Cast from BigInteger: Random Positive for (int i = 0; i < NumberOfRandomIterations; ++i) { VerifyDecimalExplicitCastFromBigInteger((decimal)((double)decimal.MaxValue * s_random.NextDouble())); } // Decimal Explicit Cast from BigInteger: Decimal.MaxValue VerifyDecimalExplicitCastFromBigInteger(decimal.MaxValue); // Decimal Explicit Cast from BigInteger: Decimal.MaxValue + 1 bigInteger = new BigInteger(decimal.MaxValue); bigInteger += BigInteger.One; temp = bigInteger.ToByteArray(); for (int j = 0; j < 3; j++) { bits[j] = BitConverter.ToInt32(temp, 4 * j); } value = new decimal(bits[0], bits[1], bits[2], false, 0); Assert.Throws<OverflowException>(() => VerifyDecimalExplicitCastFromBigInteger(value, bigInteger)); // Decimal Explicit Cast from BigInteger: Random value > Decimal.MaxValue for (int i = 0; i < NumberOfRandomIterations; ++i) { bigInteger = GenerateRandomBigIntegerGreaterThan(decimal.MaxValue, s_random); temp = bigInteger.ToByteArray(); for (int j = 0; j < 3; j++) { bits[j] = BitConverter.ToInt32(temp, 4 * j); } value = new decimal(bits[0], bits[1], bits[2], false, 0); Assert.Throws<OverflowException>(() => VerifyDecimalExplicitCastFromBigInteger(value, bigInteger)); } } /// <summary> /// Test cast to Double on Very Large BigInteger more than (1 &lt;&lt; Int.MaxValue) /// Tested BigInteger are: +/-pow(2, startShift + smallLoopShift * [1..smallLoopLimit] + Int32.MaxValue * [1..bigLoopLimit]) /// Expected double is positive and negative infinity /// Note: /// ToString() can not operate such large values /// </summary> private static void DoubleExplicitCastFromLargeBigIntegerTests(int startShift, int bigShiftLoopLimit, int smallShift = 0, int smallShiftLoopLimit = 1) { BigInteger init = BigInteger.One << startShift; for (int i = 0; i < smallShiftLoopLimit; i++) { BigInteger temp = init << ((i + 1) * smallShift); for (int j = 0; j < bigShiftLoopLimit; j++) { temp = temp << (int.MaxValue / 10); VerifyDoubleExplicitCastFromBigInteger(double.PositiveInfinity, temp); VerifyDoubleExplicitCastFromBigInteger(double.NegativeInfinity, -temp); } } } private static BigInteger GenerateRandomNegativeBigInteger(Random random) { BigInteger bigInteger; int arraySize = random.Next(1, 8) * 4; byte[] byteArray = new byte[arraySize]; for (int i = 0; i < arraySize; ++i) { byteArray[i] = (byte)random.Next(0, 256); } byteArray[arraySize - 1] |= 0x80; bigInteger = new BigInteger(byteArray); return bigInteger; } private static BigInteger GenerateRandomPositiveBigInteger(Random random) { BigInteger bigInteger; int arraySize = random.Next(1, 8) * 4; byte[] byteArray = new byte[arraySize]; for (int i = 0; i < arraySize; ++i) { byteArray[i] = (byte)random.Next(0, 256); } byteArray[arraySize - 1] &= 0x7f; bigInteger = new BigInteger(byteArray); return bigInteger; } private static BigInteger GenerateRandomBigIntegerLessThan(long value, Random random) { return (GenerateRandomNegativeBigInteger(random) + value) - 1; } private static BigInteger GenerateRandomBigIntegerLessThan(double value, Random random) { return (GenerateRandomNegativeBigInteger(random) + (BigInteger)value) - 1; } private static BigInteger GenerateRandomBigIntegerLessThan(decimal value, Random random) { return (GenerateRandomNegativeBigInteger(random) + (BigInteger)value) - 1; } private static BigInteger GenerateRandomBigIntegerGreaterThan(ulong value, Random random) { return (GenerateRandomPositiveBigInteger(random) + value) + 1; } private static BigInteger GenerateRandomBigIntegerGreaterThan(double value, Random random) { return (GenerateRandomPositiveBigInteger(random) + (BigInteger)value) + 1; } private static BigInteger GenerateRandomBigIntegerGreaterThan(decimal value, Random random) { return (GenerateRandomPositiveBigInteger(random) + (BigInteger)value) + 1; } private static void VerifyByteExplicitCastFromBigInteger(byte value) { BigInteger bigInteger = new BigInteger(value); VerifyByteExplicitCastFromBigInteger(value, bigInteger); } private static void VerifyByteExplicitCastFromBigInteger(byte value, BigInteger bigInteger) { Assert.Equal(value, (byte)bigInteger); } private static void VerifySByteExplicitCastFromBigInteger(sbyte value) { BigInteger bigInteger = new BigInteger(value); VerifySByteExplicitCastFromBigInteger(value, bigInteger); } private static void VerifySByteExplicitCastFromBigInteger(sbyte value, BigInteger bigInteger) { Assert.Equal(value, (sbyte)bigInteger); } private static void VerifyUInt16ExplicitCastFromBigInteger(ushort value) { BigInteger bigInteger = new BigInteger(value); VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger); } private static void VerifyUInt16ExplicitCastFromBigInteger(ushort value, BigInteger bigInteger) { Assert.Equal(value, (ushort)bigInteger); } private static void VerifyInt16ExplicitCastFromBigInteger(short value) { BigInteger bigInteger = new BigInteger(value); VerifyInt16ExplicitCastFromBigInteger(value, bigInteger); } private static void VerifyInt16ExplicitCastFromBigInteger(short value, BigInteger bigInteger) { Assert.Equal(value, (short)bigInteger); } private static void VerifyUInt32ExplicitCastFromBigInteger(uint value) { BigInteger bigInteger = new BigInteger(value); VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger); } private static void VerifyUInt32ExplicitCastFromBigInteger(uint value, BigInteger bigInteger) { Assert.Equal(value, (uint)bigInteger); } private static void VerifyInt32ExplicitCastFromBigInteger(int value) { BigInteger bigInteger = new BigInteger(value); VerifyInt32ExplicitCastFromBigInteger(value, bigInteger); } private static void VerifyInt32ExplicitCastFromBigInteger(int value, BigInteger bigInteger) { Assert.Equal(value, (int)bigInteger); } private static void VerifyUInt64ExplicitCastFromBigInteger(ulong value) { BigInteger bigInteger = new BigInteger(value); VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger); } private static void VerifyUInt64ExplicitCastFromBigInteger(ulong value, BigInteger bigInteger) { Assert.Equal(value, (ulong)bigInteger); } private static void VerifyInt64ExplicitCastFromBigInteger(long value) { BigInteger bigInteger = new BigInteger(value); VerifyInt64ExplicitCastFromBigInteger(value, bigInteger); } private static void VerifyInt64ExplicitCastFromBigInteger(long value, BigInteger bigInteger) { Assert.Equal(value, (long)bigInteger); } private static void VerifySingleExplicitCastFromBigInteger(float value) { BigInteger bigInteger = new BigInteger(value); VerifySingleExplicitCastFromBigInteger(value, bigInteger); } private static void VerifySingleExplicitCastFromBigInteger(float value, BigInteger bigInteger) { Assert.Equal((float)Math.Truncate(value), (float)bigInteger); } private static void VerifyDoubleExplicitCastFromBigInteger(double value) { BigInteger bigInteger = new BigInteger(value); VerifyDoubleExplicitCastFromBigInteger(value, bigInteger); } private static void VerifyDoubleExplicitCastFromBigInteger(double value, BigInteger bigInteger) { Assert.Equal(Math.Truncate(value), (double)bigInteger); } private static void VerifyDecimalExplicitCastFromBigInteger(decimal value) { BigInteger bigInteger = new BigInteger(value); VerifyDecimalExplicitCastFromBigInteger(value, bigInteger); } private static void VerifyDecimalExplicitCastFromBigInteger(decimal value, BigInteger bigInteger) { Assert.Equal(value, (decimal)bigInteger); } public static byte[] ByteArrayMakeMinSize(byte[] input, int minSize) { if (input.Length >= minSize) { return input; } byte[] output = new byte[minSize]; byte filler = 0; if ((input[input.Length - 1] & 0x80) != 0) { filler = 0xff; } for (int i = 0; i < output.Length; i++) { output[i] = (i < input.Length) ? input[i] : filler; } return output; } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC 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; using System.Collections.Specialized; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Windows.Forms; using System.Drawing.Printing; using System.Text; using fyiReporting.RDL; namespace fyiReporting.RdlViewer { /// <summary> /// RdlViewerFind finds text inside of the RdlViewer control /// </summary> public class RdlViewerFind : System.Windows.Forms.UserControl { private Button bClose; private Button bFindNext; private Button bFindPrevious; private CheckBox ckHighlightAll; private CheckBox ckMatchCase; private Label lFind; private Label lStatus; private TextBox tbFind; private PageItem position = null; private RdlViewer _Viewer; public RdlViewer Viewer { get { return _Viewer; } set { _Viewer = value; } } public RdlViewerFind() { InitializeComponent(); } private void InitializeComponent() { this.bClose = new System.Windows.Forms.Button(); this.tbFind = new System.Windows.Forms.TextBox(); this.bFindNext = new System.Windows.Forms.Button(); this.bFindPrevious = new System.Windows.Forms.Button(); this.ckHighlightAll = new System.Windows.Forms.CheckBox(); this.ckMatchCase = new System.Windows.Forms.CheckBox(); this.lFind = new System.Windows.Forms.Label(); this.lStatus = new System.Windows.Forms.Label(); this.SuspendLayout(); // // bClose // this.bClose.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.bClose.FlatAppearance.BorderSize = 0; this.bClose.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bClose.Font = new System.Drawing.Font("Arial", 6.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bClose.Location = new System.Drawing.Point(2, 4); this.bClose.Margin = new System.Windows.Forms.Padding(0); this.bClose.Name = "bClose"; this.bClose.Size = new System.Drawing.Size(18, 18); this.bClose.TabIndex = 0; this.bClose.Text = "X"; this.bClose.UseVisualStyleBackColor = false; this.bClose.Click += new System.EventHandler(this.bClose_Click); // // tbFind // this.tbFind.Location = new System.Drawing.Point(53, 4); this.tbFind.Name = "tbFind"; this.tbFind.Size = new System.Drawing.Size(118, 20); this.tbFind.TabIndex = 1; this.tbFind.TextChanged += new System.EventHandler(this.tbFind_TextChanged); // // bFindNext // this.bFindNext.Location = new System.Drawing.Point(177, 2); this.bFindNext.Name = "bFindNext"; this.bFindNext.Size = new System.Drawing.Size(61, 23); this.bFindNext.TabIndex = 2; this.bFindNext.Text = "Find Next"; this.bFindNext.UseVisualStyleBackColor = true; this.bFindNext.Click += new System.EventHandler(this.bFindNext_Click); // // bFindPrevious // this.bFindPrevious.Location = new System.Drawing.Point(242, 2); this.bFindPrevious.Name = "bFindPrevious"; this.bFindPrevious.Size = new System.Drawing.Size(82, 23); this.bFindPrevious.TabIndex = 3; this.bFindPrevious.Text = "Find Previous"; this.bFindPrevious.UseVisualStyleBackColor = true; this.bFindPrevious.Click += new System.EventHandler(this.bFindPrevious_Click); // // ckHighlightAll // this.ckHighlightAll.AutoSize = true; this.ckHighlightAll.Location = new System.Drawing.Point(330, 6); this.ckHighlightAll.Name = "ckHighlightAll"; this.ckHighlightAll.Size = new System.Drawing.Size(81, 17); this.ckHighlightAll.TabIndex = 4; this.ckHighlightAll.Text = "Highlight All"; this.ckHighlightAll.UseVisualStyleBackColor = true; this.ckHighlightAll.CheckedChanged += new System.EventHandler(this.ckHighlightAll_CheckedChanged); // // ckMatchCase // this.ckMatchCase.AutoSize = true; this.ckMatchCase.Location = new System.Drawing.Point(410, 6); this.ckMatchCase.Name = "ckMatchCase"; this.ckMatchCase.Size = new System.Drawing.Size(83, 17); this.ckMatchCase.TabIndex = 5; this.ckMatchCase.Text = "Match Case"; this.ckMatchCase.UseVisualStyleBackColor = true; this.ckMatchCase.CheckedChanged += new System.EventHandler(this.ckMatchCase_CheckedChanged); // // lFind // this.lFind.AutoSize = true; this.lFind.Location = new System.Drawing.Point(20, 7); this.lFind.Name = "lFind"; this.lFind.Size = new System.Drawing.Size(30, 13); this.lFind.TabIndex = 6; this.lFind.Text = "Find:"; // // lStatus // this.lStatus.AutoSize = true; this.lStatus.ForeColor = System.Drawing.Color.Salmon; this.lStatus.Location = new System.Drawing.Point(501, 7); this.lStatus.Name = "lStatus"; this.lStatus.Size = new System.Drawing.Size(0, 13); this.lStatus.TabIndex = 7; // // RdlViewerFind // this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.Controls.Add(this.lStatus); this.Controls.Add(this.lFind); this.Controls.Add(this.ckMatchCase); this.Controls.Add(this.ckHighlightAll); this.Controls.Add(this.bFindPrevious); this.Controls.Add(this.bFindNext); this.Controls.Add(this.tbFind); this.Controls.Add(this.bClose); this.Name = "RdlViewerFind"; this.Size = new System.Drawing.Size(740, 27); this.VisibleChanged += new System.EventHandler(this.RdlViewerFind_VisibleChanged); this.ResumeLayout(false); this.PerformLayout(); } private void bClose_Click(object sender, EventArgs e) { this.Visible = false; } private void bFindNext_Click(object sender, EventArgs e) { FindNext(); } public void FindNext() { if (_Viewer == null) throw new ApplicationException("Viewer property must be set prior to issuing FindNext."); if (tbFind.Text.Length == 0) // must have something to find return; RdlViewerFinds findOptions = ckMatchCase.Checked ? RdlViewerFinds.MatchCase : RdlViewerFinds.None; bool begin = position == null; position = _Viewer.Find(tbFind.Text, position, findOptions); if (position == null) { if (!begin) // if we didn't start from beginning already; try from beginning position = _Viewer.Find(tbFind.Text, position, findOptions); lStatus.Text = position == null ? "Phrase not found" : "Reached end of report, continued from top"; _Viewer.HighlightPageItem = position; if (position != null) _Viewer.ScrollToPageItem(position); } else { lStatus.Text = ""; _Viewer.HighlightPageItem = position; _Viewer.ScrollToPageItem(position); } } private void bFindPrevious_Click(object sender, EventArgs e) { FindPrevious(); } public void FindPrevious() { if (_Viewer == null) throw new ApplicationException("Viewer property must be set prior to issuing FindPrevious."); if (tbFind.Text.Length == 0) // must have something to find return; RdlViewerFinds findOptions = RdlViewerFinds.Backward | (ckMatchCase.Checked ? RdlViewerFinds.MatchCase : RdlViewerFinds.None); bool begin = position == null; position = _Viewer.Find(tbFind.Text, position, findOptions); if (position == null) { if (!begin) // if we didn't start from beginning already; try from bottom position = _Viewer.Find(tbFind.Text, position, findOptions); lStatus.Text = position == null ? "Phrase not found" : "Reached top of report, continued from end"; _Viewer.HighlightPageItem = position; if (position != null) _Viewer.ScrollToPageItem(position); } else { lStatus.Text = ""; _Viewer.HighlightPageItem = position; _Viewer.ScrollToPageItem(position); } } private void RdlViewerFind_VisibleChanged(object sender, EventArgs e) { lStatus.Text = ""; if (this.Visible) { _Viewer.HighlightText = tbFind.Text; tbFind.Focus(); FindNext(); // and go find the contents of the textbox } else { // turn off any highlighting when find control not visible _Viewer.HighlightPageItem = position = null; _Viewer.HighlightText = null; _Viewer.HighlightAll = false; ckHighlightAll.Checked = false; } } private void tbFind_TextChanged(object sender, EventArgs e) { lStatus.Text = ""; position = null; // reset position when edit changes?? todo not really _Viewer.HighlightText = tbFind.Text; ckHighlightAll.Enabled = bFindNext.Enabled = bFindPrevious.Enabled = tbFind.Text.Length > 0; if (tbFind.Text.Length > 0) FindNext(); } private void ckHighlightAll_CheckedChanged(object sender, EventArgs e) { _Viewer.HighlightAll = ckHighlightAll.Checked; } private void ckMatchCase_CheckedChanged(object sender, EventArgs e) { _Viewer.HighlightCaseSensitive = ckMatchCase.Checked; } } }
// created on 8/16/2005 at 8:04 AM // My wrapper for the GTK Image to allow me per-pixel editing without using unsafe code // This also allows me to move to different image output systems without having to overly // mangle my code by using discreet pixel manipulation functions. // // Possibly try to get this working on windows using another toolkit like MSFT // through an image abstraction layer. using System; using Gtk; using Gdk; using MasterLogFile; using MasterDataStructureBase; using MasterTimeSpan; namespace MasterSuperImage { public class SuperImage { private int _Width; private int _Height; private int _ImageBufferCount; private int _CurrentImageBuffer; private bool _LockedDisplayImage; private Gdk.Pixbuf _ImageDisplayBuffer; //This adds a little overhead memory but is way faster and more efficient in the longrun than //instantiating a buffer every time we want to do a draw private Gdk.Pixbuf _ScratchDisplayBuffer; private Gdk.Pixmap _ScratchRenderBuffer; private bool _ScratchBufferAllocated; private Gdk.GC _ScratchPenContext; private Gdk.Colormap _ScratchColorMap; //This stuff pertains to the "selection" stuff private Gdk.Color _SelectionColor; private bool _SelectionLastSet; private int _SelectionLastX; private int _SelectionLastY; private int _SelectionLastWidth; private int _SelectionLastHeight; //If this guy is true, we can select something that isn't currently displayed. // private bool Allow_Out_Of_Bounds_Selections; private SuperImageBuffer[] _ImageBuffers; private Gtk.Image _ImageWidget; public SuperImage ( int pImageWidth, int Image_Height ) { this._Width = pImageWidth; this._Height = Image_Height; this._ImageBufferCount = 1; this._CurrentImageBuffer = 0; this._ImageBuffers = new SuperImageBuffer[this._ImageBufferCount]; for (int tmpCounter = 0; tmpCounter < this._ImageBufferCount; tmpCounter++ ) { this._ImageBuffers[tmpCounter] = new SuperImageBuffer( this._Width, this._Height ); } //Constructor: Pixbuf (Colorspace colorspace, bool has_alpha, int bits_per_sample, int width, int height) this._ImageDisplayBuffer = new Gdk.Pixbuf ( Gdk.Colorspace.Rgb, false, 8, this._Width, this._Height ); this._ImageWidget = new Gtk.Image( this._ImageDisplayBuffer ); } public SuperImage ( int pImageWidth, int pImageHeight, int pBufferCount ) { this._Width = pImageWidth; this._Height = pImageHeight; this._ImageBufferCount = pBufferCount; this._CurrentImageBuffer = 0; this._ImageBuffers = new SuperImageBuffer[this._ImageBufferCount]; for (int tmpCounter = 0; tmpCounter < this._ImageBufferCount; tmpCounter++ ) { this._ImageBuffers[tmpCounter] = new SuperImageBuffer( this._Width, this._Height ); } //Constructor: Pixbuf (Colorspace colorspace, bool has_alpha, int bits_per_sample, int width, int height) this._ImageDisplayBuffer = new Gdk.Pixbuf ( Gdk.Colorspace.Rgb, false, 8, this._Width, this._Height ); this._ImageWidget = new Gtk.Image( this._ImageDisplayBuffer ); } public Gtk.Image Image { get { return this._ImageWidget; } } public bool MainImageLock { get { return this._LockedDisplayImage; } set { this._LockedDisplayImage = value; } } public void BlitBuffer () { this.BlitBuffer( this._CurrentImageBuffer ); } public void BlitBuffer ( int pBufferNumber ) { this.BlitBuffer( this._CurrentImageBuffer, 0, 0, this._Width, this._Height ); } public void BlitBuffer ( int pBufferNumber, int pX, int pY, int pWidth, int pHeight ) { //Composite (Pixbuf dest, int dest_x, int dest_y, int dest_width, int dest_height, double offset_x, double offset_y, double scale_x, double scale_y, InterpType interp_type, int overall_alpha) // Gdk.InterpType.Nearest, Tiles, Bilinear, Hyper (worst to best) //this.Image_Buffers[Buffer_Number].Buffer.Composite( this.Image_Display_Buffer, 0, 0, this._Width, this.Height, 0.0, 0.0, 1.0, 1.0, Gdk.InterpType.Nearest, 255 ); //public void CopyArea (int src_x, int src_y, int width, int height, Pixbuf dest_pixbuf, int dest_x, int dest_y) if ( !this._LockedDisplayImage ) this._ImageBuffers[pBufferNumber].Buffer.CopyArea( pX, pY, pWidth, pHeight, this._ImageDisplayBuffer, pX, pY); } public void Refresh () { this._ImageWidget.QueueDraw(); } public void Refresh ( int pX, int pY, int pWidth, int pHeight ) { this._ImageWidget.QueueDrawArea( pX, pY, pWidth, pHeight ); } public void MarkPixelQuad ( int pX, int pY, SuperColor pColor ) { this._ImageBuffers[this._CurrentImageBuffer].MarkPixel ( pX, pY, pColor.Red, pColor.Green, pColor.Blue ); if ( pX < _Width-1 ) this._ImageBuffers[this._CurrentImageBuffer].MarkPixel ( pX+1, pY, pColor.Red, pColor.Green, pColor.Blue ); if ( pY < _Height-1 ) this._ImageBuffers[this._CurrentImageBuffer].MarkPixel ( pX, pY+1, pColor.Red, pColor.Green, pColor.Blue ); if ( pX < _Width-1 && pY < _Height-1 ) this._ImageBuffers[this._CurrentImageBuffer].MarkPixel ( pX+1, pY+1, pColor.Red, pColor.Green, pColor.Blue ); } public void MarkPixel ( int pX, int pY, SuperColor pColor ) { this._ImageBuffers[this._CurrentImageBuffer].MarkPixel ( pX, pY, pColor.Red, pColor.Green, pColor.Blue ); } public void MarkPixel ( int pX, int pY, byte pRed, byte pGreen, byte pBlue ) { this._ImageBuffers[this._CurrentImageBuffer].MarkPixel ( pX, pY, pRed, pGreen, pBlue ); } private void CheckScratchBuffers () { if ( !this._ScratchBufferAllocated ) { //Allocate a pixmap to be used for draw operations this._ScratchRenderBuffer = new Gdk.Pixmap ( null, this._Width, this._Height, Gdk.Visual.BestDepth ); this._ScratchDisplayBuffer = new Gdk.Pixbuf ( Gdk.Colorspace.Rgb, false, 8, this._Width, this._Height ); this._ScratchBufferAllocated = true; this._ScratchPenContext = new Gdk.GC ( this._ScratchRenderBuffer ); //Todo: This should be a property this._SelectionColor = new Gdk.Color ( 0xff, 0, 0 ); this._ScratchColorMap = Gdk.Colormap.System; this._ScratchColorMap.AllocColor (ref this._SelectionColor, true, true); this._ScratchPenContext.Foreground = this._SelectionColor; } } public void SetSelection ( int pX, int pY, int pWidth, int pHeight ) { //if ( !this.Allow_Out_Of_Bounds_Selections || ((X > 0) && (Y > 0) && ((Y+Height) < this.Height) && ((X+_Width) < this._Width) ) ) if ((pX > 0) && (pY > 0) && ((pY+pHeight) < this._Height) && ((pX+pWidth) < this._Width)) { this.CheckScratchBuffers(); this.ClearLastSelection(); int tmpX = Math.Max(pX, 0); int tmpY = Math.Max(pY, 0); int tmpWidth, tmpHeight; if ( tmpX + pWidth > this._Width ) tmpWidth = this._Width - tmpX; else tmpWidth = pWidth; if ( tmpY + pHeight > this._Height ) tmpHeight = this._Height - tmpY; else tmpHeight = pHeight; int tmpInvalidTopX = Math.Min(this._SelectionLastX, pX); int tmpInvalidTopY = Math.Min( this._SelectionLastY, pY); int tmpInvalidBottomX = Math.Max( this._SelectionLastX+this._SelectionLastWidth, pX+pWidth); int tmpInvalidBottomY = Math.Max( this._SelectionLastY+this._SelectionLastHeight, pY+pWidth); this._SelectionLastX = tmpX; this._SelectionLastY = tmpY; this._SelectionLastWidth = tmpWidth; this._SelectionLastHeight = tmpHeight; this._SelectionLastSet = true; // RenderToDrawable (Drawable drawable, GC gc, int src_x, int src_y, int dest_x, int dest_y, int width, int height, RgbDither dither, int x_dither, int y_dither) this._ImageBuffers[this._CurrentImageBuffer].Buffer.RenderToDrawable (_ScratchRenderBuffer, this._ScratchPenContext, tmpX, tmpY, tmpX, tmpY, tmpWidth, tmpHeight, Gdk.RgbDither.None, 0, 0); this._ScratchRenderBuffer.DrawRectangle (this._ScratchPenContext, false, pX, pY, pWidth - 1, pHeight - 1); //FromDrawable (Drawable src, Colormap cmap, int src_x, int src_y, int dest_x, int dest_y, int width, int height) //GetFromDrawable (Drawable drawable, Colormap cmap, int src_x, int src_y, int dest_x, int dest_y, int width, int height) this._ScratchDisplayBuffer.GetFromDrawable (this._ScratchRenderBuffer, this._ScratchColorMap, tmpX, tmpY, tmpX, tmpY, tmpWidth, tmpHeight); this._ScratchDisplayBuffer.CopyArea (tmpX, tmpY, tmpWidth, tmpHeight, this._ImageDisplayBuffer, tmpX, tmpY); this.Refresh (tmpInvalidTopX, tmpInvalidTopY, tmpInvalidBottomX-tmpInvalidTopX, tmpInvalidBottomY-tmpInvalidTopY); } } private void ClearLastSelection () { if ( this._SelectionLastSet ) { this.BlitBuffer( this._CurrentImageBuffer, this._SelectionLastX, this._SelectionLastY, this._SelectionLastWidth, this._SelectionLastHeight ); //this.Blit_Buffer(); } } public void HideSelection() { this.ClearLastSelection(); this.Refresh (this._SelectionLastX, this._SelectionLastY, this._SelectionLastWidth, this._SelectionLastHeight); } } //Would it not be neat if this had a masking layer as well? Also support for an Alpha Channel maybe public class SuperImageBuffer { //_Width and Height private int _Width; private int _Height; private int _RowSize; //Each buffer has a Rendering byte array and a Pixbuf buffer private byte[] _ImageBufferRenderer; private Gdk.Pixbuf _ImageBuffer; public SuperImageBuffer ( int pImageWidth, int pImageHeight ) { this._Width = pImageWidth; this._Height = pImageHeight; //Row_Size is 3*_Width (R, G, B) //Eventually we could do Images with more than 24 bits, although we'd have to downsample the colors to display them. this._RowSize = pImageWidth * 3; //The byte buffer needs to be Row_Size * Height bytes long this._ImageBufferRenderer = new byte[this._RowSize*this._Height]; //And now to create the buffer. //Constructor: Pixbuf (byte[] data, Colorspace colorspace, bool has_alpha, int bits_per_sample, int width, int height, int rowstride, PixbufDestroyNotify destroy_fn) this._ImageBuffer = new Gdk.Pixbuf( this._ImageBufferRenderer, Gdk.Colorspace.Rgb, false, 8, this._Width, this._Height, this._RowSize, null); } public Gdk.Pixbuf Buffer { get { return this._ImageBuffer; } } //Others: MarkRow, MarkColumn, ModifyRow (using a modifier function type! yeah), ModifyPixel, MarkBlock (with setable size?) public void MarkPixel (int pX, int pY, SuperColor pColor) { this.MarkPixel (pX, pY, pColor.Red, pColor.Green, pColor.Blue ); } public void MarkPixel (int pX, int pY, byte pRed, byte pGreen, byte pBlue ) { //The simple marking strategy //This may at some point be changed to having a "last written pixels" buffer deal //No validation yet for X and Y // Valid values: 0 .. Size-1 this._ImageBufferRenderer[(pY*this._RowSize)+(pX*3)] = pRed; this._ImageBufferRenderer[(pY*this._RowSize)+(pX*3)+1] = pGreen; this._ImageBufferRenderer[(pY*this._RowSize)+(pX*3)+2] = pBlue; } } }
//---------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.ServiceModel.Dispatcher; using System.ServiceModel.Description; using System.Globalization; using System.Text; struct ChannelRequirements { public bool usesInput; public bool usesReply; public bool usesOutput; public bool usesRequest; public SessionMode sessionMode; public static void ComputeContractRequirements(ContractDescription contractDescription, out ChannelRequirements requirements) { requirements = new ChannelRequirements(); requirements.usesInput = false; requirements.usesReply = false; requirements.usesOutput = false; requirements.usesRequest = false; requirements.sessionMode = contractDescription.SessionMode; for (int i = 0; i < contractDescription.Operations.Count; i++) { OperationDescription operation = contractDescription.Operations[i]; bool oneWay = (operation.IsOneWay); if (!operation.IsServerInitiated()) { if (oneWay) { requirements.usesInput = true; } else { requirements.usesReply = true; } } else { if (oneWay) { requirements.usesOutput = true; } else { requirements.usesRequest = true; } } } } public static Type[] ComputeRequiredChannels(ref ChannelRequirements requirements) { if (requirements.usesOutput || requirements.usesRequest) { switch (requirements.sessionMode) { case SessionMode.Allowed: return new Type[] { typeof(IDuplexChannel), typeof(IDuplexSessionChannel), }; case SessionMode.Required: return new Type[] { typeof(IDuplexSessionChannel), }; case SessionMode.NotAllowed: return new Type[] { typeof(IDuplexChannel), }; } } else if (requirements.usesInput && requirements.usesReply) { switch (requirements.sessionMode) { case SessionMode.Allowed: return new Type[] { typeof(IRequestChannel), typeof(IRequestSessionChannel), typeof(IDuplexChannel), typeof(IDuplexSessionChannel), }; case SessionMode.Required: return new Type[] { typeof(IRequestSessionChannel), typeof(IDuplexSessionChannel), }; case SessionMode.NotAllowed: return new Type[] { typeof(IRequestChannel), typeof(IDuplexChannel), }; } } else if (requirements.usesInput) { switch (requirements.sessionMode) { case SessionMode.Allowed: return new Type[] { typeof(IOutputChannel), typeof(IOutputSessionChannel), typeof(IRequestChannel), typeof(IRequestSessionChannel), typeof(IDuplexChannel), typeof(IDuplexSessionChannel), }; case SessionMode.Required: return new Type[] { typeof(IOutputSessionChannel), typeof(IRequestSessionChannel), typeof(IDuplexSessionChannel), }; case SessionMode.NotAllowed: return new Type[] { typeof(IOutputChannel), typeof(IRequestChannel), typeof(IDuplexChannel), }; } } else if (requirements.usesReply) { switch (requirements.sessionMode) { case SessionMode.Allowed: return new Type[] { typeof(IRequestChannel), typeof(IRequestSessionChannel), typeof(IDuplexChannel), typeof(IDuplexSessionChannel), }; case SessionMode.Required: return new Type[] { typeof(IRequestSessionChannel), typeof(IDuplexSessionChannel), }; case SessionMode.NotAllowed: return new Type[] { typeof(IRequestChannel), typeof(IDuplexChannel), }; } } else { switch (requirements.sessionMode) { case SessionMode.Allowed: return new Type[] { typeof(IOutputSessionChannel), typeof(IOutputChannel), typeof(IRequestSessionChannel), typeof(IRequestChannel), typeof(IDuplexChannel), typeof(IDuplexSessionChannel), }; case SessionMode.Required: return new Type[] { typeof(IOutputSessionChannel), typeof(IRequestSessionChannel), typeof(IDuplexSessionChannel), }; case SessionMode.NotAllowed: return new Type[] { typeof(IOutputChannel), typeof(IRequestChannel), typeof(IDuplexChannel), }; } } return null; } public static bool IsSessionful(Type channelType) { return (channelType == typeof(IDuplexSessionChannel) || channelType == typeof(IOutputSessionChannel) || channelType == typeof(IInputSessionChannel) || channelType == typeof(IReplySessionChannel) || channelType == typeof(IRequestSessionChannel)); } public static bool IsOneWay(Type channelType) { return (channelType == typeof(IOutputChannel) || channelType == typeof(IInputChannel) || channelType == typeof(IInputSessionChannel) || channelType == typeof(IOutputSessionChannel)); } public static bool IsRequestReply(Type channelType) { return (channelType == typeof(IRequestChannel) || channelType == typeof(IReplyChannel) || channelType == typeof(IReplySessionChannel) || channelType == typeof(IRequestSessionChannel)); } public static bool IsDuplex(Type channelType) { return (channelType == typeof(IDuplexChannel) || channelType == typeof(IDuplexSessionChannel)); } public static Exception CantCreateListenerException(IEnumerable<Type> supportedChannels, IEnumerable<Type> requiredChannels, string bindingName) { string contractChannelTypesString = ""; string bindingChannelTypesString = ""; Exception exception = ChannelRequirements.BindingContractMismatchException(supportedChannels, requiredChannels, bindingName, ref contractChannelTypesString, ref bindingChannelTypesString); if (exception == null) { // none of the obvious speculations about the failure holds, so we fall back to the generic error message exception = new InvalidOperationException(SR.GetString(SR.EndpointListenerRequirementsCannotBeMetBy3, bindingName, contractChannelTypesString, bindingChannelTypesString)); } return exception; } public static Exception CantCreateChannelException(IEnumerable<Type> supportedChannels, IEnumerable<Type> requiredChannels, string bindingName) { string contractChannelTypesString = ""; string bindingChannelTypesString = ""; Exception exception = ChannelRequirements.BindingContractMismatchException(supportedChannels, requiredChannels, bindingName, ref contractChannelTypesString, ref bindingChannelTypesString); if (exception == null) { // none of the obvious speculations about the failure holds, so we fall back to the generic error message exception = new InvalidOperationException(SR.GetString(SR.CouldnTCreateChannelForType2, bindingName, contractChannelTypesString)); } return exception; } public static Exception BindingContractMismatchException(IEnumerable<Type> supportedChannels, IEnumerable<Type> requiredChannels, string bindingName, ref string contractChannelTypesString, ref string bindingChannelTypesString) { StringBuilder contractChannelTypes = new StringBuilder(); bool contractRequiresOneWay = true; bool contractRequiresRequestReply = true; bool contractRequiresDuplex = true; bool contractRequiresTwoWay = true; // request-reply or duplex bool contractRequiresSession = true; bool contractRequiresDatagram = true; foreach (Type channelType in requiredChannels) { if (contractChannelTypes.Length > 0) { contractChannelTypes.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator); contractChannelTypes.Append(" "); } string typeString = channelType.ToString(); contractChannelTypes.Append(typeString.Substring(typeString.LastIndexOf('.') + 1)); if (!ChannelRequirements.IsOneWay(channelType)) { contractRequiresOneWay = false; } if (!ChannelRequirements.IsRequestReply(channelType)) { contractRequiresRequestReply = false; } if (!ChannelRequirements.IsDuplex(channelType)) { contractRequiresDuplex = false; } if (!(ChannelRequirements.IsRequestReply(channelType) || ChannelRequirements.IsDuplex(channelType))) { contractRequiresTwoWay = false; } if (!ChannelRequirements.IsSessionful(channelType)) { contractRequiresSession = false; } else { contractRequiresDatagram = false; } } StringBuilder bindingChannelTypes = new StringBuilder(); bool bindingSupportsOneWay = false; bool bindingSupportsRequestReply = false; bool bindingSupportsDuplex = false; bool bindingSupportsSession = false; bool bindingSupportsDatagram = false; bool bindingSupportsAtLeastOneChannelType = false; foreach (Type channelType in supportedChannels) { bindingSupportsAtLeastOneChannelType = true; if (bindingChannelTypes.Length > 0) { bindingChannelTypes.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator); bindingChannelTypes.Append(" "); } string typeString = channelType.ToString(); bindingChannelTypes.Append(typeString.Substring(typeString.LastIndexOf('.') + 1)); if (ChannelRequirements.IsOneWay(channelType)) { bindingSupportsOneWay = true; } if (ChannelRequirements.IsRequestReply(channelType)) { bindingSupportsRequestReply = true; } if (ChannelRequirements.IsDuplex(channelType)) { bindingSupportsDuplex = true; } if (ChannelRequirements.IsSessionful(channelType)) { bindingSupportsSession = true; } else { bindingSupportsDatagram = true; } } bool bindingSupportsTwoWay = bindingSupportsRequestReply || bindingSupportsDuplex; if (!bindingSupportsAtLeastOneChannelType) { return new InvalidOperationException(SR.GetString(SR.BindingDoesnTSupportAnyChannelTypes1, bindingName)); } if (contractRequiresSession && !bindingSupportsSession) { return new InvalidOperationException(SR.GetString(SR.BindingDoesnTSupportSessionButContractRequires1, bindingName)); } if (contractRequiresDatagram && !bindingSupportsDatagram) { return new InvalidOperationException(SR.GetString(SR.BindingDoesntSupportDatagramButContractRequires, bindingName)); } if (contractRequiresDuplex && !bindingSupportsDuplex) { return new InvalidOperationException(SR.GetString(SR.BindingDoesnTSupportDuplexButContractRequires1, bindingName)); } if (contractRequiresRequestReply && !bindingSupportsRequestReply) { return new InvalidOperationException(SR.GetString(SR.BindingDoesnTSupportRequestReplyButContract1, bindingName)); } if (contractRequiresOneWay && !bindingSupportsOneWay) { return new InvalidOperationException(SR.GetString(SR.BindingDoesnTSupportOneWayButContractRequires1, bindingName)); } if (contractRequiresTwoWay && !bindingSupportsTwoWay) { return new InvalidOperationException(SR.GetString(SR.BindingDoesnTSupportTwoWayButContractRequires1, bindingName)); } contractChannelTypesString = contractChannelTypes.ToString(); bindingChannelTypesString = bindingChannelTypes.ToString(); return null; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Reactive.Linq; using System.Text; using Newtonsoft.Json; using RabbitMQ.Client; using RabbitMQ.Client.Events; using RabbitMQ.Client.Framing; using Serilog; using Thinktecture.Relay.Server.Config; using Thinktecture.Relay.Server.OnPremise; namespace Thinktecture.Relay.Server.Communication.RabbitMq { public class RabbitMqMessageDispatcher : IMessageDispatcher, IDisposable { private const string _EXCHANGE_NAME = "RelayServer"; private const string _REQUEST_QUEUE_PREFIX = "Request "; private const string _RESPONSE_QUEUE_PREFIX = "Response "; private const string _ACKNOWLEDGE_QUEUE_PREFIX = "Acknowledge "; private readonly ILogger _logger; private readonly IConfiguration _configuration; private readonly IModel _model; private readonly UTF8Encoding _encoding; private readonly Guid _originId; public RabbitMqMessageDispatcher(ILogger logger, IConfiguration configuration, IConnection connection, IPersistedSettings persistedSettings) { _logger = logger; _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); if (connection == null) throw new ArgumentNullException(nameof(connection)); _model = connection.CreateModel(); _encoding = new UTF8Encoding(false, true); _originId = persistedSettings?.OriginId ?? throw new ArgumentNullException(nameof(persistedSettings)); DeclareExchange(_EXCHANGE_NAME); } public IObservable<IOnPremiseConnectorRequest> OnRequestReceived(Guid linkId, string connectionId, bool autoAck) { return CreateConsumerObservable<OnPremiseConnectorRequest>($"{_REQUEST_QUEUE_PREFIX}{linkId}", autoAck, (request, deliveryTag) => { if (autoAck) { return; } switch (request.AcknowledgmentMode) { case AcknowledgmentMode.Auto: lock (_model) { _model.BasicAck(deliveryTag, false); } _logger?.Debug("Request was automatically acknowledged. request-id={RequestId}", request.RequestId); break; case AcknowledgmentMode.Default: case AcknowledgmentMode.Manual: request.AcknowledgeId = deliveryTag.ToString(); request.AcknowledgeOriginId = _originId; _logger?.Verbose("Request acknowledge id was set. request-id={RequestId}, acknowledge-id={AcknowledgeId}", request.RequestId, request.AcknowledgeId); break; } }); } public IObservable<IOnPremiseConnectorResponse> OnResponseReceived() { return CreateConsumerObservable<OnPremiseConnectorResponse>($"{_RESPONSE_QUEUE_PREFIX}{_originId}"); } public IObservable<string> OnAcknowledgeReceived() { return CreateConsumerObservable<string>($"{_ACKNOWLEDGE_QUEUE_PREFIX}{_originId}"); } private IObservable<T> CreateConsumerObservable<T>(string queueName, bool autoAck = true, Action<T, ulong> callback = null) { return Observable.Create<T>(observer => { lock (_model) { DeclareQueue(queueName); _model.QueueBind(queueName, _EXCHANGE_NAME, queueName); } _logger?.Debug("Creating consumer. queue-name={QueueName}", queueName); var consumer = new EventingBasicConsumer(_model); string consumerTag; lock (_model) { consumerTag = _model.BasicConsume(queueName, autoAck, consumer); } void OnReceived(object sender, BasicDeliverEventArgs args) { try { var json = _encoding.GetString(args.Body); var message = JsonConvert.DeserializeObject<T>(json); callback?.Invoke(message, args.DeliveryTag); observer.OnNext(message); } catch (Exception ex) { _logger?.Error(ex, "Error during receiving a message via RabbitMQ"); if (!autoAck) { lock (_model) { _model.BasicAck(args.DeliveryTag, false); } } } } consumer.Received += OnReceived; return new DelegatingDisposable(_logger, () => { _logger?.Debug("Disposing consumer. queue-name={QueueName}", queueName); consumer.Received -= OnReceived; lock (_model) { _model.BasicCancel(consumerTag); } }); }); } public void AcknowledgeRequest(string acknowledgeId) { if (UInt64.TryParse(acknowledgeId, out var deliveryTag)) { _logger?.Debug("Acknowledging request. acknowledge-id={AcknowledgeId}", acknowledgeId); lock (_model) { _model.BasicAck(deliveryTag, false); } } } public void DispatchRequest(Guid linkId, IOnPremiseConnectorRequest request) { var content = Serialize(request, out var props); if (request.Expiration != TimeSpan.Zero) { _logger?.Verbose("Setting RabbitMQ message TTL. request-id={RequestId}, request-expiration={RequestExpiration}", request.RequestId, request.Expiration); props.Expiration = request.Expiration.TotalMilliseconds.ToString(CultureInfo.InvariantCulture); } lock (_model) { _model.BasicPublish(_EXCHANGE_NAME, $"{_REQUEST_QUEUE_PREFIX}{linkId}", false, props, content); } } public void DispatchResponse(Guid originId, IOnPremiseConnectorResponse response) { var content = Serialize(response, out var props); lock (_model) { _model.BasicPublish(_EXCHANGE_NAME, $"{_RESPONSE_QUEUE_PREFIX}{originId}", false, props, content); } } public void DispatchAcknowledge(Guid originId, string acknowledgeId) { var content = Serialize(acknowledgeId, out var props); lock (_model) { _model.BasicPublish(_EXCHANGE_NAME, $"{_ACKNOWLEDGE_QUEUE_PREFIX}{originId}", false, props, content); } } private byte[] Serialize<T>(T message, out BasicProperties props) { props = new BasicProperties() { ContentEncoding = "application/json", DeliveryMode = 2, }; return _encoding.GetBytes(JsonConvert.SerializeObject(message)); } private void DeclareExchange(string name) { _logger?.Verbose("Declaring exchange. name={ExchangeName}, type={ExchangeType}", name, ExchangeType.Direct); lock (_model) { _model.ExchangeDeclare(name, ExchangeType.Direct); } } private void DeclareQueue(string name) { Dictionary<string, object> arguments = null; if (_configuration.QueueExpiration == TimeSpan.Zero) { _logger?.Verbose("Declaring queue. name={QueueName}", name); } else { _logger?.Verbose("Declaring queue. name={QueueName}, expiration={QueueExpiration}", name, _configuration.QueueExpiration); arguments = new Dictionary<string, object>() { ["x-expires"] = (int)_configuration.QueueExpiration.TotalMilliseconds }; } try { lock (_model) { _model.QueueDeclare(name, true, false, false, arguments); } } catch (Exception ex) { _logger?.Error(ex, "Declaring queue failed - possible expiration change. name={QueueName}", name); throw; } } private void Dispose(bool disposing) { if (disposing) { lock (_model) { _model.Dispose(); } } } public void Dispose() { Dispose(true); } } }
#region File Description //----------------------------------------------------------------------------- // BingMapsSampleGame.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Disclaimer /****************************************************************************** * * * This sample is a data heavy application * * * * Make sure you have a data plan when deploy to phone * * * ******************************************************************************/ #endregion #region Using Statements using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using System.Device.Location; using System.Net; using System.Xml.Linq; using System.Xml; #endregion namespace BingMaps { /// <summary> /// This is the main type for your game /// </summary> public class BingMapsSampleGame : Game { #region Fields Texture2D blank; SpriteFont buttonFont; GraphicsDeviceManager graphics; SpriteBatch spriteBatch; GeoCoordinate startingCoordinate; BingMapsViewer bingMapsViewer; #error For the sample to work, you need to acquire a Bing Maps key. See http://www.bingmapsportal.com/ const string BingAppKey = "<Bing Maps API Key>"; Button switchViewButton; // Web client used to retrieve the coordinates of locations request by the user WebClient locationWebClient; string locationToFocusOn; #endregion #region Initialization public BingMapsSampleGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; locationWebClient = new WebClient(); locationWebClient.OpenReadCompleted += new OpenReadCompletedEventHandler(ReceivedLocationCoordinates); // Frame rate is 30 fps by default for Windows Phone. TargetElapsedTime = TimeSpan.FromTicks(333333); graphics.IsFullScreen = true; TouchPanel.EnabledGestures = GestureType.Tap | GestureType.FreeDrag | GestureType.DragComplete; } #endregion #region Loading /// <summary> /// Load Bing maps assets. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures spriteBatch = new SpriteBatch(GraphicsDevice); blank = Content.Load<Texture2D>("blank"); buttonFont = Content.Load<SpriteFont>("Font"); switchViewButton = new Button("Switch to\nRoad view", buttonFont, Color.White, new Rectangle(10, 10, 100, 60), Color.Black, blank, spriteBatch); switchViewButton.Click += switchViewButton_Click; startingCoordinate = new GeoCoordinate(47.639597, -122.12845); Texture2D defaultImage = Content.Load<Texture2D>("noImage"); Texture2D unavailableImage = Content.Load<Texture2D>("noImage"); bingMapsViewer = new BingMapsViewer(BingAppKey, defaultImage, unavailableImage, startingCoordinate, 5, 15, spriteBatch); } #endregion #region Update and Render /// <summary> /// Update the Bing maps application. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // If we have a pending focus request and the web client is not busy, perform it if (locationToFocusOn != null && !locationWebClient.IsBusy) { FocusOnLocationAsync(locationToFocusOn); locationToFocusOn = null; } // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { Exit(); } HandleInput(); base.Update(gameTime); } /// <summary> /// Handle the input of the sample. /// </summary> private void HandleInput() { // Read all gesture while (TouchPanel.IsGestureAvailable) { GestureSample sample = TouchPanel.ReadGesture(); if (switchViewButton.HandleInput(sample)) return; if (sample.GestureType == GestureType.Tap) { if (!Guide.IsVisible) Guide.BeginShowKeyboardInput(PlayerIndex.One, "Select location", "Type in a location to focus on.", String.Empty, LocationSelected, null); } else if (sample.GestureType == GestureType.FreeDrag) { // Move the map when dragging bingMapsViewer.MoveByOffset(sample.Delta); } } } /// <summary> /// Draw the map on the screen. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Gray); spriteBatch.Begin(); // Draw the map bingMapsViewer.Draw(); switchViewButton.Draw(); spriteBatch.End(); base.Draw(gameTime); } #endregion #region Non-Public Methods /// <summary> /// Sends an asynchronous web request to retrieve the coordinates of a location on which the user wishes to /// focus. /// </summary> /// <param name="locationToFocusOn">String describing the location to focus on.</param> private void FocusOnLocationAsync(string locationToFocusOn) { locationWebClient.OpenReadAsync( new Uri(String.Format(@"http://dev.virtualearth.net/REST/v1/Locations?o=xml&q={0}&key={1}", locationToFocusOn, BingAppKey), UriKind.Absolute)); } /// <summary> /// Handler called when the request for a location's coordinates returns. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ReceivedLocationCoordinates(object sender, OpenReadCompletedEventArgs e) { if (e.Cancelled) { return; } if (e.Error != null) { if (!Guide.IsVisible) Guide.BeginShowMessageBox("Error focusing on location", e.Error.Message, new string[] { "OK" }, 0, MessageBoxIcon.Error, null, null); return; } GeoCoordinate receivedCoordinate; try { // Parse the response XML to get the location's geo-coordinate XDocument locationResponseDoc = XDocument.Load(e.Result); XNamespace docNamespace = locationResponseDoc.Root.GetDefaultNamespace(); var locationNodes = locationResponseDoc.Descendants(XName.Get("Location", docNamespace.NamespaceName)); if (locationNodes.Count() == 0) { Guide.BeginShowMessageBox("Invalid location", "The requested location was not recognized by the system.", new string[] { "OK" }, 0, MessageBoxIcon.Error, null, null); return; } XElement pointNode = locationNodes.First().Descendants( XName.Get("Point", docNamespace.NamespaceName)).FirstOrDefault(); if (pointNode == null) { Guide.BeginShowMessageBox("Invalid location result", "The location result is missing data.", new string[] { "OK" }, 0, MessageBoxIcon.Error, null, null); return; } XElement longitudeNode = pointNode.Element(XName.Get("Longitude", docNamespace.NamespaceName)); XElement latitudeNode = pointNode.Element(XName.Get("Latitude", docNamespace.NamespaceName)); if (longitudeNode == null || latitudeNode == null) { Guide.BeginShowMessageBox("Invalid location result", "The location result is missing data.", new string[] { "OK" }, 0, MessageBoxIcon.Error, null, null); return; } receivedCoordinate = new GeoCoordinate(double.Parse(latitudeNode.Value), double.Parse(longitudeNode.Value)); } catch (Exception err) { Guide.BeginShowMessageBox("Error getting location coordinates", err.Message, new string[] { "OK" }, 0, MessageBoxIcon.Error, null, null); return; } bingMapsViewer.CenterOnLocation(receivedCoordinate); } /// <summary> /// Handler called when the user clicks the button to change the view type. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void switchViewButton_Click(object sender, EventArgs e) { if (bingMapsViewer != null) { BingMapsViewType previousType = bingMapsViewer.ViewType; switch (bingMapsViewer.ViewType) { case BingMapsViewType.Aerial: bingMapsViewer.ViewType = BingMapsViewType.Road; break; case BingMapsViewType.Road: bingMapsViewer.ViewType = BingMapsViewType.Aerial; break; default: break; } switchViewButton.Text = String.Format("Switch to\n{0} view", previousType); bingMapsViewer.RefreshImages(); } } /// <summary> /// Performs cleanup actions when exiting the game. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> protected override void OnExiting(object sender, EventArgs args) { bingMapsViewer.ActiveTiles.Dispose(); base.OnExiting(sender, args); } /// <summary> /// Handler launched once the user selects a location to zoom on. /// </summary> /// <param name="result">Asynchronous call result containing the text typed by the user.</param> private void LocationSelected(IAsyncResult result) { locationToFocusOn = Guide.EndShowKeyboardInput(result); if (String.IsNullOrEmpty(locationToFocusOn)) { return; } // Cancel any ongoing request, or do nothing if there was none locationWebClient.CancelAsync(); } #endregion } }
/* * Copyright (c) 2008, openmetaverse.org * 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. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Text; namespace OpenMetaverse { public static partial class Utils { /// <summary> /// Operating system /// </summary> public enum Platform { /// <summary>Unknown</summary> Unknown, /// <summary>Microsoft Windows</summary> Windows, /// <summary>Microsoft Windows CE</summary> WindowsCE, /// <summary>Linux</summary> Linux, /// <summary>Apple OSX</summary> OSX } /// <summary> /// Runtime platform /// </summary> public enum Runtime { /// <summary>.NET runtime</summary> Windows, /// <summary>Mono runtime: http://www.mono-project.com/</summary> Mono } public const float E = (float)Math.E; public const float LOG10E = 0.4342945f; public const float LOG2E = 1.442695f; public const float PI = (float)Math.PI; public const float TWO_PI = (float)(Math.PI * 2.0d); public const float PI_OVER_TWO = (float)(Math.PI / 2.0d); public const float PI_OVER_FOUR = (float)(Math.PI / 4.0d); /// <summary>Used for converting degrees to radians</summary> public const float DEG_TO_RAD = (float)(Math.PI / 180.0d); /// <summary>Used for converting radians to degrees</summary> public const float RAD_TO_DEG = (float)(180.0d / Math.PI); /// <summary>Provide a single instance of the CultureInfo class to /// help parsing in situations where the grid assumes an en-us /// culture</summary> public static readonly System.Globalization.CultureInfo EnUsCulture = new System.Globalization.CultureInfo("en-us"); /// <summary>UNIX epoch in DateTime format</summary> public static readonly DateTime Epoch = new DateTime(1970, 1, 1); public static readonly byte[] EmptyBytes = new byte[0]; /// <summary>Provide a single instance of the MD5 class to avoid making /// duplicate copies and handle thread safety</summary> private static readonly System.Security.Cryptography.MD5 MD5Builder = new System.Security.Cryptography.MD5CryptoServiceProvider(); /// <summary>Provide a single instance of the SHA-1 class to avoid /// making duplicate copies and handle thread safety</summary> private static readonly System.Security.Cryptography.SHA1 SHA1Builder = new System.Security.Cryptography.SHA1CryptoServiceProvider(); private static readonly System.Security.Cryptography.SHA256 SHA256Builder = new System.Security.Cryptography.SHA256Managed(); /// <summary>Provide a single instance of a random number generator /// to avoid making duplicate copies and handle thread safety</summary> private static readonly Random RNG = new Random(); #region Math /// <summary> /// Clamp a given value between a range /// </summary> /// <param name="value">Value to clamp</param> /// <param name="min">Minimum allowable value</param> /// <param name="max">Maximum allowable value</param> /// <returns>A value inclusively between lower and upper</returns> public static float Clamp(float value, float min, float max) { // First we check to see if we're greater than the max value = (value > max) ? max : value; // Then we check to see if we're less than the min. value = (value < min) ? min : value; // There's no check to see if min > max. return value; } /// <summary> /// Clamp a given value between a range /// </summary> /// <param name="value">Value to clamp</param> /// <param name="min">Minimum allowable value</param> /// <param name="max">Maximum allowable value</param> /// <returns>A value inclusively between lower and upper</returns> public static double Clamp(double value, double min, double max) { // First we check to see if we're greater than the max value = (value > max) ? max : value; // Then we check to see if we're less than the min. value = (value < min) ? min : value; // There's no check to see if min > max. return value; } /// <summary> /// Clamp a given value between a range /// </summary> /// <param name="value">Value to clamp</param> /// <param name="min">Minimum allowable value</param> /// <param name="max">Maximum allowable value</param> /// <returns>A value inclusively between lower and upper</returns> public static int Clamp(int value, int min, int max) { // First we check to see if we're greater than the max value = (value > max) ? max : value; // Then we check to see if we're less than the min. value = (value < min) ? min : value; // There's no check to see if min > max. return value; } /// <summary> /// Round a floating-point value to the nearest integer /// </summary> /// <param name="val">Floating point number to round</param> /// <returns>Integer</returns> public static int Round(float val) { return (int)Math.Floor(val + 0.5f); } /// <summary> /// Test if a single precision float is a finite number /// </summary> public static bool IsFinite(float value) { return !(Single.IsNaN(value) || Single.IsInfinity(value)); } /// <summary> /// Test if a double precision float is a finite number /// </summary> public static bool IsFinite(double value) { return !(Double.IsNaN(value) || Double.IsInfinity(value)); } /// <summary> /// Get the distance between two floating-point values /// </summary> /// <param name="value1">First value</param> /// <param name="value2">Second value</param> /// <returns>The distance between the two values</returns> public static float Distance(float value1, float value2) { return Math.Abs(value1 - value2); } public static float Hermite(float value1, float tangent1, float value2, float tangent2, float amount) { // All transformed to double not to lose precission // Otherwise, for high numbers of param:amount the result is NaN instead of Infinity double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result; double sCubed = s * s * s; double sSquared = s * s; if (amount == 0f) result = value1; else if (amount == 1f) result = value2; else result = (2d * v1 - 2d * v2 + t2 + t1) * sCubed + (3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared + t1 * s + v1; return (float)result; } public static double Hermite(double value1, double tangent1, double value2, double tangent2, double amount) { // All transformed to double not to lose precission // Otherwise, for high numbers of param:amount the result is NaN instead of Infinity double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result; double sCubed = s * s * s; double sSquared = s * s; if (amount == 0d) result = value1; else if (amount == 1f) result = value2; else result = (2d * v1 - 2d * v2 + t2 + t1) * sCubed + (3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared + t1 * s + v1; return result; } public static float Lerp(float value1, float value2, float amount) { return value1 + (value2 - value1) * amount; } public static double Lerp(double value1, double value2, double amount) { return value1 + (value2 - value1) * amount; } public static float SmoothStep(float value1, float value2, float amount) { // It is expected that 0 < amount < 1 // If amount < 0, return value1 // If amount > 1, return value2 float result = Utils.Clamp(amount, 0f, 1f); return Utils.Hermite(value1, 0f, value2, 0f, result); } public static double SmoothStep(double value1, double value2, double amount) { // It is expected that 0 < amount < 1 // If amount < 0, return value1 // If amount > 1, return value2 double result = Utils.Clamp(amount, 0f, 1f); return Utils.Hermite(value1, 0f, value2, 0f, result); } public static float ToDegrees(float radians) { // This method uses double precission internally, // though it returns single float // Factor = 180 / pi return (float)(radians * 57.295779513082320876798154814105); } public static float ToRadians(float degrees) { // This method uses double precission internally, // though it returns single float // Factor = pi / 180 return (float)(degrees * 0.017453292519943295769236907684886); } /// <summary> /// Compute the MD5 hash for a byte array /// </summary> /// <param name="data">Byte array to compute the hash for</param> /// <returns>MD5 hash of the input data</returns> public static byte[] MD5(byte[] data) { lock (MD5Builder) return MD5Builder.ComputeHash(data); } /// <summary> /// Compute the SHA1 hash for a byte array /// </summary> /// <param name="data">Byte array to compute the hash for</param> /// <returns>SHA1 hash of the input data</returns> public static byte[] SHA1(byte[] data) { lock (SHA1Builder) return SHA1Builder.ComputeHash(data); } /// <summary> /// Calculate the SHA1 hash of a given string /// </summary> /// <param name="value">The string to hash</param> /// <returns>The SHA1 hash as a string</returns> public static string SHA1String(string value) { StringBuilder digest = new StringBuilder(40); byte[] hash = SHA1(Encoding.UTF8.GetBytes(value)); // Convert the hash to a hex string foreach (byte b in hash) digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); return digest.ToString(); } /// <summary> /// Compute the SHA256 hash for a byte array /// </summary> /// <param name="data">Byte array to compute the hash for</param> /// <returns>SHA256 hash of the input data</returns> public static byte[] SHA256(byte[] data) { lock (SHA256Builder) return SHA256Builder.ComputeHash(data); } /// <summary> /// Calculate the SHA256 hash of a given string /// </summary> /// <param name="value">The string to hash</param> /// <returns>The SHA256 hash as a string</returns> public static string SHA256String(string value) { StringBuilder digest = new StringBuilder(64); byte[] hash = SHA256(Encoding.UTF8.GetBytes(value)); // Convert the hash to a hex string foreach (byte b in hash) digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); return digest.ToString(); } /// <summary> /// Calculate the MD5 hash of a given string /// </summary> /// <param name="password">The password to hash</param> /// <returns>An MD5 hash in string format, with $1$ prepended</returns> public static string MD5(string password) { StringBuilder digest = new StringBuilder(32); byte[] hash = MD5(ASCIIEncoding.Default.GetBytes(password)); // Convert the hash to a hex string foreach (byte b in hash) digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); return "$1$" + digest.ToString(); } /// <summary> /// Calculate the MD5 hash of a given string /// </summary> /// <param name="value">The string to hash</param> /// <returns>The MD5 hash as a string</returns> public static string MD5String(string value) { StringBuilder digest = new StringBuilder(32); byte[] hash = MD5(Encoding.UTF8.GetBytes(value)); // Convert the hash to a hex string foreach (byte b in hash) digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); return digest.ToString(); } /// <summary> /// Generate a random double precision floating point value /// </summary> /// <returns>Random value of type double</returns> public static double RandomDouble() { lock (RNG) return RNG.NextDouble(); } #endregion Math #region Platform /// <summary> /// Get the current running platform /// </summary> /// <returns>Enumeration of the current platform we are running on</returns> public static Platform GetRunningPlatform() { const string OSX_CHECK_FILE = "/Library/Extensions.kextcache"; if (Environment.OSVersion.Platform == PlatformID.WinCE) { return Platform.WindowsCE; } else { int plat = (int)Environment.OSVersion.Platform; if ((plat != 4) && (plat != 128)) { return Platform.Windows; } else { if (System.IO.File.Exists(OSX_CHECK_FILE)) return Platform.OSX; else return Platform.Linux; } } } /// <summary> /// Get the current running runtime /// </summary> /// <returns>Enumeration of the current runtime we are running on</returns> public static Runtime GetRunningRuntime() { Type t = Type.GetType("Mono.Runtime"); if (t != null) return Runtime.Mono; else return Runtime.Windows; } #endregion Platform } }
using System; using System.Diagnostics; using System.Drawing; using System.Runtime.InteropServices; using System.Web; using System.Windows.Forms; using GuruComponents.Netrix.ComInterop; using GuruComponents.Netrix.Events; using GuruComponents.Netrix.WebEditing.Behaviors; using GuruComponents.Netrix.WebEditing.Documents; using GuruComponents.Netrix.WebEditing.DragDrop; using GuruComponents.Netrix.WebEditing.Elements; using Control = System.Web.UI.Control; using HtmlWindow = GuruComponents.Netrix.WebEditing.Documents.HtmlWindow; using System.Runtime.InteropServices.ComTypes; using GuruComponents.Netrix.WebEditing.UndoRedo; namespace GuruComponents.Netrix { /// <summary> /// This is the basic implementation of the MSHTML host. /// </summary> /// <remarks> /// This class implements the interfaces building /// the base services and the basic editor host, which implements TAB key, table recognition and DEL /// key support. /// </remarks> [ClassInterface(ClassInterfaceType.None)] internal class MSHTMLSite : Interop.IOleClientSite, Interop.IOleContainer, Interop.IOleDocumentSite, Interop.IOleInPlaceSite, Interop.IOleInPlaceSiteEx, Interop.IOleInPlaceFrame, Interop.IDocHostUIHandler, Interop.IDocHostShowUI, Interop.IPropertyNotifySink, Interop.IAdviseSink, Interop.IOleServiceProvider, Interop.IHTMLEditDesigner, IDisposable { /// the Control used to host (and parent) the mshtml window private HtmlEditor htmlEditor; /// <summary> /// the mshtml instance and various related objects /// </summary> private Interop.IOleObject oleDocumentObject; private Interop.IHTMLDocument2 htmlbaseDocument; private Interop.IOleDocumentView interopDocumentView; private Interop.IOleInPlaceActiveObject activeObject; private string _readyStateString; /// <summary> /// Show UI on start? /// </summary> private bool WithUI; /// <summary> /// cookie representing our sink /// </summary> private ConnectionPointCookie propNotifyCookie; private int adviseSinkCookie; private IntPtr windowHandle = IntPtr.Zero; private DataObjectConverter _dataobjectconverter; // Delete Key Code private const int DEL = 46; /// <summary> /// </summary> public MSHTMLSite(HtmlEditor htmlEditor) { if ((htmlEditor == null))// || (htmlEditor.IsHandleCreated == false)) { throw new ArgumentException(); } WithUI = false; this.htmlEditor = htmlEditor; this._readyStateString = String.Empty; } #region Internal used methods internal bool PreTranslateMessage(Message msg) { Interop.COMMSG lpmsg = new Interop.COMMSG(); lpmsg.hwnd = msg.HWnd; lpmsg.lParam = msg.LParam; lpmsg.wParam = msg.WParam; lpmsg.message = msg.Msg; if (this.activeObject != null && this.activeObject.TranslateAccelerator(lpmsg) == Interop.S_OK) { return true; } else { return false; } } internal Interop.IOleObject OleDocument { get { return this.oleDocumentObject; } } public IntPtr DocumentHandle { get { return windowHandle; } } /// <summary> /// Access to drop information after dragdrop operations. The object /// converter contains the dropped element. /// </summary> public DataObjectConverter DataObjectConverter { get { if (_dataobjectconverter == null) { _dataobjectconverter = new DataObjectConverter(); } return _dataobjectconverter; } set { _dataobjectconverter = value; } } /// <summary> /// Access to current document. The set accessor should only set to null during cleanup. /// </summary> public Interop.IHTMLDocument2 MSHTMLDocument { get { return htmlbaseDocument; } set { htmlbaseDocument = value; } } /// <overloads/> /// <summary> /// Activate with UI activation. /// </summary> /// <remarks> /// UI activation means that the caret appears immediately after the designer surface appears, whether or not the /// control has the focus. /// </remarks> public void ActivateMSHTML() { ActivateMSHTML(true); } /// <summary> /// Activate the editor /// </summary> /// <param name="withUI">Activates the UI of the control immediately after start up.</param> /// <remarks> /// UI activation means that the caret appears immediately after the designer surface appears, whether or not the /// control has the focus. /// </remarks> public void ActivateMSHTML(bool withUI) { try { this.WithUI = withUI; Interop.RECT r = EditorRect; int result = OleDocument.DoVerb((int)Interop.OLE.OLEIVERB_UIACTIVATE, Interop.NullIntPtr, this, 0, EditorHandle, r); if (result == Interop.S_OK) { this.htmlEditor.NeedActivation = false; } else { throw new ApplicationException("Activate UI in ActivateMSHTML failed with result " + result); } htmlEditor.AddEditDesigner(this); } catch (Exception e) { Debug.Fail(e.ToString()); } } private IntPtr EditorHandle { get { try { if (htmlEditor.IsDisposed) return IntPtr.Zero; else return htmlEditor.PanelHandle; } catch (Exception) { // Object disposed? } return IntPtr.Zero; } } private Interop.RECT EditorRect { get { Interop.RECT r = new Interop.RECT(); Win32.GetClientRect(EditorHandle, r); return r; } } /// <summary> /// </summary> public void Dispose() { try { int RefCount; if (propNotifyCookie != null) { propNotifyCookie.Dispose(); propNotifyCookie = null; } if (winEvents != null) { winEvents.Dispose(); winEvents = null; } try { Marshal.ReleaseComObject(window); } catch { } try { if (interopDocumentView != null) { try { interopDocumentView.Show(0); } catch { } try { interopDocumentView.UIActivate(0); } catch { } try { interopDocumentView.SetInPlaceSite(null); } catch { } long nullParam = 0L; try { interopDocumentView.Close(nullParam); do { RefCount = Marshal.ReleaseComObject(interopDocumentView); } while (RefCount >= 0); } catch { } finally { Marshal.FinalReleaseComObject(interopDocumentView); interopDocumentView = null; } } } catch { } if (oleDocumentObject != null) { try { if (htmlEditor.Site == null || !htmlEditor.Site.DesignMode) { Marshal.FinalReleaseComObject(oleDocumentObject); oleDocumentObject = null; } } catch { } } if (htmlbaseDocument != null) { do { RefCount = Marshal.ReleaseComObject(htmlbaseDocument); } while (RefCount >= 0); Marshal.FinalReleaseComObject(htmlbaseDocument); htmlbaseDocument = null; } if (interopDocumentView != null) { do { RefCount = Marshal.ReleaseComObject(interopDocumentView); } while (RefCount >= 0); } if (activeObject != null) { do { RefCount = Marshal.ReleaseComObject(activeObject); } while (RefCount >= 0); Marshal.FinalReleaseComObject(activeObject); activeObject = null; } interopDocumentView = null; htmlbaseDocument = null; activeObject = null; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } /// <summary> /// </summary> public void CreateMSHTML() { bool created = false; try { // create our base instance this.htmlbaseDocument = (Interop.IHTMLDocument2)new Interop.HTMLDocument(); this.activeObject = (Interop.IOleInPlaceActiveObject)htmlbaseDocument; this.windowHandle = new IntPtr(); this.activeObject.GetWindow(out this.windowHandle); oleDocumentObject = (Interop.IOleObject)htmlbaseDocument; if (oleDocumentObject == null) { throw new ApplicationException("InteropOleObject not created. No document available."); } // hand it our Interop.IOleClientSite implementation Win32.OleRun(htmlbaseDocument); oleDocumentObject.SetClientSite(this); Win32.OleLockRunning(htmlbaseDocument, true, false); created = true; // attach document and window base events propNotifyCookie = new ConnectionPointCookie(htmlbaseDocument, this, typeof(Interop.IPropertyNotifySink), false); // set document properties oleDocumentObject.SetHostNames("NetRix", "NetRix"); // set ole events oleDocumentObject.Advise(this, out adviseSinkCookie); // set IConnectionPointContainer icpc = (IConnectionPointContainer)htmlbaseDocument; //find the source interface ////get IPropertyNotifySink interface //Guid g = new Guid("9BFBBC02-EFF1-101A-84ED-00AA00341D07"); //icpc.FindConnectionPoint(ref g, out icp); ////pass a pointer to the host to the connection point //icp.Advise(this._site, out this._cookie); } catch (Exception ex) { Debug.Fail("CreateHtml failed", ex.Message); } finally { if (created == false) { htmlbaseDocument = null; oleDocumentObject = null; } } } internal void SetFocus() { if (activeObject != null) { IntPtr hWnd; if (activeObject.GetWindow(out hWnd) == Interop.S_OK) { Win32.SetFocus(hWnd); } } } #endregion #region Internal used event fire methods /// <summary> /// </summary> internal void ParentResize() { if (interopDocumentView != null) { Interop.RECT r = EditorRect; interopDocumentView.SetRect(r); } } internal void ExpandView(Rectangle r) { Interop.RECT rect = new Interop.RECT(); rect.right = r.Right; rect.bottom = r.Bottom; interopDocumentView.SetRect(rect); } #endregion #region Interop.IOleClientSite Implementation public int SaveObject() { return Interop.S_OK; } public int GetMoniker(int dwAssign, int dwWhichMoniker, out object ppmk) { ppmk = null; return Interop.E_NOTIMPL; } public int GetContainer(out Interop.IOleContainer ppContainer) { ppContainer = (Interop.IOleContainer)this; return Interop.S_OK; } public int ShowObject() { return Interop.S_OK; } public int OnShowWindow(int fShow) { return Interop.S_OK; } public int RequestNewObjectLayout() { return Interop.S_OK; } #endregion #region Interop.IOleContainer Implementation public void ParseDisplayName(object pbc, string pszDisplayName, int[] pchEaten, object[] ppmkOut) { Debug.Fail("ParseDisplayName - " + pszDisplayName); throw new COMException(String.Empty, Interop.E_NOTIMPL); } public void EnumObjects(int grfFlags, out Interop.IEnumUnknown ppenum) { ppenum = null; throw new COMException(String.Empty, Interop.E_NOTIMPL); } // public void EnumObjects(int grfFlags, object[] ppenum) // { // throw new COMException(String.Empty, Interop.E_NOTIMPL); // } public void LockContainer(int fLock) { } #endregion #region Interop.IOleDocumentSite Implementation public int ActivateMe(Interop.IOleDocumentView pViewToActivate) { if (pViewToActivate == null) return Interop.E_INVALIDARG; Interop.RECT r = EditorRect; interopDocumentView = pViewToActivate; interopDocumentView.SetInPlaceSite(this); interopDocumentView.UIActivate(WithUI ? 1 : 0); interopDocumentView.SetRect(r); interopDocumentView.Show(1); return Interop.S_OK; } #endregion internal void HideCaret() { Win32.HideCaret(windowHandle); } internal void ShowCaret() { Win32.ShowCaret(windowHandle); } #region Interop.IOleInPlaceSiteEx Implementation int Interop.IOleInPlaceSiteEx.CanInPlaceActivate() { return Interop.S_OK; } int Interop.IOleInPlaceSiteEx.OnInPlaceActivate() { return Interop.S_OK; } int Interop.IOleInPlaceSiteEx.ContextSensitiveHelp(bool fEnterMode) { return Interop.E_NOTIMPL; } int Interop.IOleInPlaceSiteEx.GetWindow(ref IntPtr hwnd) { hwnd = IntPtr.Zero; if (this.htmlEditor != null) { hwnd = EditorHandle; return Interop.S_OK; } else { return Interop.E_FAIL; } } int Interop.IOleInPlaceSiteEx.OnInPlaceActivateEx(out bool pfNoRedraw, int dwFlags) { pfNoRedraw = false; //false means object needs to redraw return Interop.S_OK; } int Interop.IOleInPlaceSiteEx.OnInPlaceDeactivateEx(bool fNoRedraw) { //Debug.WriteLine(fNoRedraw, "OnInPlaceDeactivateEx::Enter"); if (!fNoRedraw) { //redraw container this.htmlEditor.Invalidate(); } Debug.WriteLine("OnInPlaceDeactivateEx::Leave"); return Interop.S_OK; } int Interop.IOleInPlaceSiteEx.RequestUIActivate() { //Debug.WriteLine("RequestUIActivate::Enter"); if (this.htmlEditor.Visible && this.htmlEditor.ActivationEnabled && !this.htmlEditor.StopFocusOnLoad || htmlEditor.IsReady) { return Interop.S_OK; } else { return Interop.S_FALSE; } } int Interop.IOleInPlaceSiteEx.OnUIActivate() { //Debug.WriteLine("OnUIActivate::Enter"); //return HESULT.S_FALSE prevents focus grab //but means no caret if (this.htmlEditor.Visible && this.htmlEditor.ActivationEnabled && !this.htmlEditor.StopFocusOnLoad) { return Interop.S_OK; } else { return Interop.S_FALSE; } } int Interop.IOleInPlaceSiteEx.GetWindowContext(out Interop.IOleInPlaceFrame ppFrame, out Interop.IOleInPlaceUIWindow ppDoc, Interop.RECT lprcPosRect, Interop.RECT lprcClipRect, Interop.tagOIFI lpFrameInfo) { //Debug.WriteLine("GetWindowContext::Enter"); ppDoc = null; //XX set to null because same as Frame window ppFrame = this; if (lprcPosRect != null) { Win32.GetClientRect(EditorHandle, lprcPosRect); } if (lprcClipRect != null) { Win32.GetClientRect(EditorHandle, lprcClipRect); } //lpFrameInfo.cb = Marshal.SizeOf(typeof(tagOIFI)); //This value is set by the caller lpFrameInfo.fMDIApp = 0; lpFrameInfo.hwndFrame = EditorHandle; lpFrameInfo.hAccel = IntPtr.Zero; lpFrameInfo.cAccelEntries = 0; //Debug.WriteLine("GetWindowContext::Leave"); return Interop.S_OK; } int Interop.IOleInPlaceSiteEx.Scroll(Interop.tagSIZE scrollExtant) { return Interop.E_NOTIMPL; } int Interop.IOleInPlaceSiteEx.OnUIDeactivate(int fUndoable) { return Interop.S_OK; } int Interop.IOleInPlaceSiteEx.OnInPlaceDeactivate() { activeObject = null; return Interop.S_OK; } int Interop.IOleInPlaceSiteEx.DiscardUndoState() { return Interop.E_NOTIMPL; } int Interop.IOleInPlaceSiteEx.DeactivateAndUndo() { return Interop.S_OK; } int Interop.IOleInPlaceSiteEx.OnPosRectChange(ref Interop.RECT lprcPosRect) { return Interop.S_OK; } #endregion #region Interop.IOleInPlaceSite Implementation int Interop.IOleInPlaceSite.DiscardUndoState() { return Interop.E_NOTIMPL; } int Interop.IOleInPlaceSite.DeactivateAndUndo() { return Interop.S_OK; } int Interop.IOleInPlaceSite.OnInPlaceDeactivate() { activeObject = null; return Interop.S_OK; } int Interop.IOleInPlaceSite.OnUIDeactivate(int fUndoable) { return Interop.S_OK; } IntPtr Interop.IOleInPlaceSite.GetWindow() { IntPtr hwnd = IntPtr.Zero; if (this.htmlEditor != null) { hwnd = EditorHandle; } return hwnd; } int Interop.IOleInPlaceSite.ContextSensitiveHelp(int fEnterMode) { return Interop.E_NOTIMPL; } int Interop.IOleInPlaceSite.CanInPlaceActivate() { return Interop.S_OK; } int Interop.IOleInPlaceSite.OnInPlaceActivate() { return Interop.S_OK; } int Interop.IOleInPlaceSite.OnUIActivate() { return Interop.S_OK; } int Interop.IOleInPlaceSite.GetWindowContext(out Interop.IOleInPlaceFrame ppFrame, out Interop.IOleInPlaceUIWindow ppDoc, Interop.RECT lprcPosRect, Interop.RECT lprcClipRect, Interop.tagOIFI lpFrameInfo) { Debug.WriteLine("GetWindowContext2::Enter"); ppFrame = this; ppDoc = null; Win32.GetClientRect(EditorHandle, lprcPosRect); Win32.GetClientRect(EditorHandle, lprcClipRect); lpFrameInfo.cb = Marshal.SizeOf(typeof(Interop.tagOIFI)); lpFrameInfo.fMDIApp = 0; lpFrameInfo.hwndFrame = EditorHandle; lpFrameInfo.hAccel = Interop.NullIntPtr; lpFrameInfo.cAccelEntries = 0; Debug.WriteLine("GetWindowContext2::Leave"); return Interop.S_OK; } int Interop.IOleInPlaceSite.Scroll(Interop.tagSIZE scrollExtant) { return Interop.E_NOTIMPL; } int Interop.IOleInPlaceSite.OnPosRectChange(Interop.RECT lprcPosRect) { return Interop.S_OK; } #endregion #region Interop.IOleInPlaceFrame Implementation IntPtr Interop.IOleInPlaceFrame.GetWindow() { return EditorHandle; } void Interop.IOleInPlaceFrame.ContextSensitiveHelp(int fEnterMode) { throw new COMException(String.Empty, Interop.E_NOTIMPL); } void Interop.IOleInPlaceFrame.GetBorder(Interop.RECT lprectBorder) { throw new COMException(String.Empty, Interop.E_NOTIMPL); } void Interop.IOleInPlaceFrame.RequestBorderSpace(Interop.RECT pborderwidths) { throw new COMException(String.Empty, Interop.E_NOTIMPL); } void Interop.IOleInPlaceFrame.SetBorderSpace(Interop.RECT pborderwidths) { throw new COMException(String.Empty, Interop.E_NOTIMPL); } void Interop.IOleInPlaceFrame.SetActiveObject(Interop.IOleInPlaceActiveObject pActiveObject, string pszObjName) { try { if (pActiveObject == null) { if (this.activeObject != null) { Marshal.ReleaseComObject(this.activeObject); } this.activeObject = null; this.windowHandle = IntPtr.Zero; } else { this.activeObject = pActiveObject; this.windowHandle = new IntPtr(); pActiveObject.GetWindow(out this.windowHandle); } } catch { } } public void InsertMenus(IntPtr hmenuShared, Interop.tagOleMenuGroupWidths lpMenuWidths) { throw new COMException(String.Empty, Interop.E_NOTIMPL); } public void SetMenu(IntPtr hmenuShared, IntPtr holemenu, IntPtr hwndActiveObject) { throw new COMException(String.Empty, Interop.E_NOTIMPL); } public void RemoveMenus(IntPtr hmenuShared) { throw new COMException(String.Empty, Interop.E_NOTIMPL); } public void SetStatusText(string pszStatusText) { } public void EnableModeless(int fEnable) { } public int TranslateAccelerator(Interop.COMMSG lpmsg, short wID) { return Interop.S_FALSE; } #endregion #region IDocHostUIHandler Implementation public int ShowContextMenu(int dwID, ref Interop.POINT pt, object pcmdtReserved, object pdispReserved) { Point location = htmlEditor.PointToClient(new Point(pt.x, pt.y)); Interop.IHTMLElement element = this.MSHTMLDocument.ElementFromPoint(location.X, location.Y); Control ielement = this.htmlEditor.GenericElementFactory.CreateElement(element); ShowContextMenuEventArgs e = new ShowContextMenuEventArgs(location, false, dwID, ielement); try { htmlEditor.OnShowContextMenu(e); } catch { // Make sure we return Interop.S_OK } return Interop.S_OK; } public int GetHostInfo(Interop.DOCHOSTUIINFO info) { info.dwDoubleClick = (int)Interop.DOCHOSTUIDBLCLICK.DEFAULT; int flags = 0; if (htmlEditor.NoTextSelection) { flags |= (int)Interop.DOCHOSTUIFLAG.DIALOG; } if (htmlEditor.AllowInPlaceNavigation) { flags |= (int)Interop.DOCHOSTUIFLAG.ENABLE_INPLACE_NAVIGATION; } if (htmlEditor.ImeReconversion) { flags |= (int)Interop.DOCHOSTUIFLAG.IME_ENABLE_RECONVERSION; } if (!htmlEditor.Border3d) { flags |= (int)Interop.DOCHOSTUIFLAG.NO3DBORDER; } if (!htmlEditor.ScriptEnabled) { flags |= (int)Interop.DOCHOSTUIFLAG.DISABLE_SCRIPT_INACTIVE; } if (!htmlEditor.ScrollBarsEnabled) { flags |= (int)Interop.DOCHOSTUIFLAG.SCROLL_NO; } if (htmlEditor.FlatScrollBars) { flags |= (int)Interop.DOCHOSTUIFLAG.FLAT_SCROLLBAR; } if (htmlEditor.BlockDefault == BlockDefaultType.DIV) { flags |= (int)Interop.DOCHOSTUIFLAG.DIV_BLOCKDEFAULT; } if (htmlEditor.XPTheming) { flags |= (int)Interop.DOCHOSTUIFLAG.THEME; } else { flags |= (int)Interop.DOCHOSTUIFLAG.NOTHEME; } // IE 6 Enhancements flags |= (int)Interop.DOCHOSTUIFLAG.DISABLE_EDIT_NS_FIXUP; flags |= (int)Interop.DOCHOSTUIFLAG.DISABLE_UNTRUSTEDPROTOCOL; // IE 7 Enhancements flags |= (int)Interop.DOCHOSTUIFLAG.USE_WINDOWLESS_SELECTCONTROL; // IE 8 Enhancements if (htmlEditor.AutoWordSelection) { //flags |= (int)Interop.DOCHOSTUIFLAG.AUTOWORD; } info.dwFlags = flags; return Interop.S_OK; } public int EnableModeless(bool fEnable) { return fEnable ? Interop.S_OK : Interop.S_FALSE; } public int ShowUI(int dwID, Interop.IOleInPlaceActiveObject activeObject, Interop.IOleCommandTarget commandTarget, Interop.IOleInPlaceFrame frame, Interop.IOleInPlaceUIWindow doc) { return Interop.S_FALSE; } public int HideUI() { return Interop.S_OK; } public int UpdateUI() { this.htmlEditor.OnUpdateUI(lastEventType); return Interop.S_OK; } public int OnDocWindowActivate(bool fActivate) { return Interop.E_NOTIMPL; } public int OnFrameWindowActivate(bool fActivate) { return Interop.E_NOTIMPL; } public int ResizeBorder(Interop.RECT rect, Interop.IOleInPlaceUIWindow doc, bool fFrameWindow) { return Interop.E_NOTIMPL; } public int GetOptionKeyPath(string[] pbstrKey, int dw) { pbstrKey[0] = null; return Interop.S_OK; } public int GetDropTarget(Interop.IOleDropTarget pDropTarget, out Interop.IOleDropTarget ppDropTarget) { if (this.htmlEditor._dropTarget == null) { this.htmlEditor._dropTarget = new DropTarget(this.htmlEditor, DataObjectConverter, pDropTarget); ppDropTarget = this.htmlEditor._dropTarget; return Interop.S_OK; } else { ppDropTarget = null; //pDropTarget; return Interop.S_FALSE; } } /// <summary> /// Called if in JScript windows.external.WhatEver is being executed. /// </summary> /// <remarks> /// E_NOTIMPL = fires native error window /// E_DEFAULTACTION = security exception /// E_FAIL = unspecified error /// E_ABORT = suppress an native window /// E_HANDLE = provide valid handle to invoke code /// E_UNEXPECTED = unexpected error /// E_POINTER = pointer expected /// E_NOINTERFACE = null or not object /// E_ACCESSDENIED = security error /// E_OUTOFMEMORY = out of mem error /// </remarks> /// <param name="ppDispatch"></param> /// <returns></returns> public int GetExternal(out object ppDispatch) { ppDispatch = ((HtmlWindow)htmlEditor.Window).ObjectForScripting; ScriptExternalEventArgs args = new ScriptExternalEventArgs(); if (ppDispatch == null) { args.ExternalError = ScriptExternalEventArgs.ExternalErrorCode.E_ABORT; } else { args.ExternalError = ScriptExternalEventArgs.ExternalErrorCode.S_OK; } ((HtmlWindow)htmlEditor.Window).OnScriptExternal(args); return (int)args.ExternalError; } public int TranslateAccelerator(Interop.COMMSG msg, ref Guid group, int nCmdID) { return Interop.S_FALSE; } public int TranslateUrl(int dwTranslate, string strURLIn, out string pstrURLOut) { BeforeNavigateEventArgs args = new BeforeNavigateEventArgs(strURLIn); this.htmlEditor.OnBeforeNavigate(args); if (args.Cancel) { // This is how we cancel it, a bit weird to provide a blank, but String.Empty will not work! pstrURLOut = " "; } else { pstrURLOut = args.Url; } return pstrURLOut.Equals(strURLIn) ? Interop.S_FALSE : Interop.S_OK; } public int FilterDataObject(Interop.IOleDataObject pDO, out Interop.IOleDataObject ppDORet) { ppDORet = null; return Interop.E_NOTIMPL; } #endregion #region IAdviseSink Implementation public void OnDataChange(Interop.FORMATETC pFormat, Interop.STGMEDIUM pStg) { } public void OnViewChange(int dwAspect, int index) { } public void OnRename(object pmk) { } public void OnSave() { } public void OnClose() { } #endregion #region Interop.IOleServiceProvider public int QueryService(ref Guid sid, ref Guid iid, out IntPtr ppvObject) { int hr = Interop.E_NOINTERFACE; ppvObject = Interop.NullIntPtr; // ask our explicit services container Type type = GetTypeFromIID(sid); if (type != null && htmlEditor.ServiceProvider != null) { object service = htmlEditor.ServiceProvider.GetService(type); if (service != null) { if (iid.Equals(Interop.IID_IUnknown)) { ppvObject = Marshal.GetIUnknownForObject(service); } else { IntPtr pUnk = Marshal.GetIUnknownForObject(service); Marshal.QueryInterface(pUnk, ref iid, out ppvObject); Marshal.Release(pUnk); return Interop.S_OK; } } } return hr; } private static readonly Guid IUnknowGuid = new Guid("00000118-0000-0000-C000-000000000046"); private static readonly Guid IHTMLEditDesignerGuid = new Guid("3050f662-98b5-11cf-bb82-00aa00bdce0b"); private static readonly Guid IHTMLEditHostGuid = new Guid("3050f6a0-98b5-11cf-bb82-00aa00bdce0b"); private static readonly Guid IAuthenticateGuid = new Guid("79EAC9D0-BAF9-11CE-8C82-00AA004BA90B"); private static readonly Guid IHttpSecurityGuid = new Guid("79eac9d7-bafa-11ce-8c82-00aa004ba90b"); //private static readonly Guid IOleCommandTargetGuid = new Guid("b722bccb-4e68-101b-a2bc-00aa00404770"); private static readonly Guid IOleCommandTargetGuid = new Guid("3050f4b5-98b5-11cf-bb82-00aa00bdce0b"); private static readonly Guid IOleUndoManagerGuid = new Guid("d001f200-ef97-11ce-9bc9-00aa00608e01"); private static readonly Guid IInternetSecurityManagerGuid = new Guid("79eac9ee-baf9-11ce-8c82-00aa004ba90b"); private Type GetTypeFromIID(Guid iid) { if (iid.Equals(IUnknowGuid)) return null; if (iid.Equals(IHTMLEditDesignerGuid)) return typeof(Interop.IHTMLEditDesigner); if (iid.Equals(IHTMLEditHostGuid)) return typeof(Interop.IHTMLEditHost); if (iid.Equals(IAuthenticateGuid)) return typeof(Interop.IAuthenticate); if (iid.Equals(IHttpSecurityGuid)) return typeof(Interop.IHttpSecurity); if (iid.Equals(IOleCommandTargetGuid)) return typeof(Interop.IOleCommandTarget); if (iid.Equals(IOleUndoManagerGuid)) return typeof(Interop.IOleUndoManager); if (iid.Equals(IInternetSecurityManagerGuid)) return typeof(Interop.IInternetSecurityManager); return null; } #endregion #region Interop.IPropertyNotifySink Implementation bool _firstChanged = false; public int OnChanged(int dispID) { try { switch (dispID) { case 1005 /*DISPID_FRAMECHANGE*/: if (!_firstChanged) { _firstChanged = true; } // string readyState = MSHTMLDocument.GetReadyState(); // // the method will called after initialisation, this activates the site // // for the first time. Subsequent calls does not fire the ready event again. break; case DispId.READYSTATE: string newReadyState = this.MSHTMLDocument.GetReadyState(); if (newReadyState != this._readyStateString) { _readyStateString = newReadyState; if (_readyStateString.Equals("complete")) { if (winEvents != null) { winEvents.Dispose(); winEvents = null; } // global events window = htmlbaseDocument.GetParentWindow(); winEvents = new WindowsEvents(window, htmlEditor, htmlEditor.Window); } this.htmlEditor.OnReadyStateChanged(newReadyState); } break; } } catch { return Interop.S_FALSE; } return Interop.S_OK; } public int OnRequestEdit(int dispID) { return Interop.S_OK; } #endregion #region IHtmlEditDesigner internal HtmlFrameSet.FrameWindow RelatedFrameWindow = null; private string lastFrameName = String.Empty; private Interop.IHTMLWindow2 window = null; private int returnCode = Interop.S_FALSE; private WindowsEvents winEvents; private string lastEventType; public int PreHandleEvent(int dispId, Interop.IHTMLEventObj e) { returnCode = Interop.S_FALSE; Interop.IHTMLElement el = e.srcElement; if (e.srcElement != null) { lastEventType = e.type; Control element = htmlEditor.GenericElementFactory.CreateElement(el); returnCode = this.htmlEditor.InvokeHtmlEvent(e, element); if (returnCode == Interop.S_OK || (element is IElement && !htmlEditor.DesignModeEnabled)) { e.cancelBubble = true; e.returnValue = Interop.S_OK; } else { if (returnCode == Interop.S_FALSE && dispId == DispId.KEYDOWN && htmlEditor.DesignModeEnabled) { switch (e.keyCode) { case DEL: if (this.htmlEditor.InternalShortcutKeys) { try { this.htmlEditor.Exec(Interop.IDM.DELETE); } finally { returnCode = Interop.S_OK; } } break; default: break; } } } } return returnCode; } public int PostHandleEvent(int dispId, Interop.IHTMLEventObj e) { return returnCode; } public int TranslateAccelerator(int dispId, Interop.IHTMLEventObj e) { return Interop.S_FALSE; } public int PostEditorEventNotify(int dispId, Interop.IHTMLEventObj e) { HandlePostEvents(dispId, e); return Interop.S_FALSE; } private void HandlePostEvents(int dispId, Interop.IHTMLEventObj e) { // For spellchecker and other late bound event sinks htmlEditor.InvokePostEditorEvent(new PostEditorEventArgs(e)); if (e.srcElement != null) { if (dispId == DispId.KEYDOWN || dispId == DispId.MOUSEUP) { // We check the current scope only if the caret is visible for the user if (dispId == DispId.KEYDOWN) { //Application.DoEvents(); IElement currentElement = this.htmlEditor.Window.GetElementFromCaret() as IElement; if (currentElement != null) { this.htmlEditor.InvokeHtmlElementChanged(currentElement.GetBaseElement(), HtmlElementChangedType.Key); } else { this.htmlEditor.InvokeHtmlElementChanged(htmlEditor.GetBodyElement().GetBaseElement(), HtmlElementChangedType.Key); } } // if a mouse click was handled the event source has the element if (dispId == DispId.MOUSEUP) { this.htmlEditor.InvokeHtmlElementChanged(e.srcElement, HtmlElementChangedType.Mouse); } } } } #endregion #region IDocHostShowUI Members int Interop.IDocHostShowUI.ShowMessage(IntPtr hwnd, string lpStrText, string lpstrCaption, uint dwType, string lpStrHelpFile, uint dwHelpContext, out uint lpresult) { // dwType 48 == Alert() // 33 == confirm() lpresult = (uint)Interop.MBID.OK; ShowMessageEventArgs e = new ShowMessageEventArgs(lpStrText, lpstrCaption, dwType); ((HtmlWindow)htmlEditor.Window).OnScriptMessage(e); if (e.Cancel) return Interop.S_OK; else return Interop.S_FALSE; } int Interop.IDocHostShowUI.ShowHelp(IntPtr hwnd, string lpHelpFile, uint uCommand, uint dwData, Interop.POINT ptMouse, object pDispatchObjectHit) { return Interop.S_OK; } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.Azure.Search.Models; namespace Microsoft.Azure.Search.Models { /// <summary> /// Parameters for filtering, sorting, faceting, paging, and other search /// query behaviors. /// </summary> public partial class SearchParameters { private string _filter; /// <summary> /// Optional. Gets or sets the OData $filter expression to apply to the /// search query. (see /// https://msdn.microsoft.com/library/azure/dn798921.aspx for more /// information) /// </summary> public string Filter { get { return this._filter; } set { this._filter = value; } } private IList<string> _highlightFields; /// <summary> /// Optional. Gets or sets the list of field names to use for hit /// highlights. Only searchable fields can be used for hit /// highlighting. /// </summary> public IList<string> HighlightFields { get { return this._highlightFields; } set { this._highlightFields = value; } } private string _highlightPostTag; /// <summary> /// Optional. Gets or sets a string tag that is appended to hit /// highlights. Must be set with HighlightPreTag. Default is /// &lt;/em&gt;. /// </summary> public string HighlightPostTag { get { return this._highlightPostTag; } set { this._highlightPostTag = value; } } private string _highlightPreTag; /// <summary> /// Optional. Gets or sets a string tag that is prepended to hit /// highlights. Must be set with HighlightPostTag. Default is /// &lt;em&gt;. /// </summary> public string HighlightPreTag { get { return this._highlightPreTag; } set { this._highlightPreTag = value; } } private bool _includeTotalResultCount; /// <summary> /// Optional. Gets or sets a value that specifies whether to fetch the /// total count of results. Default is false. Setting this value to /// true may have a performance impact. Note that the count returned /// is an approximation. /// </summary> public bool IncludeTotalResultCount { get { return this._includeTotalResultCount; } set { this._includeTotalResultCount = value; } } private double? _minimumCoverage; /// <summary> /// Optional. Gets or sets a number between 0 and 100 indicating the /// percentage of the index that must be covered by a search query in /// order for the query to be reported as a success. This parameter /// can be useful for ensuring search availability even for services /// with only one replica. The default is 100. /// </summary> public double? MinimumCoverage { get { return this._minimumCoverage; } set { this._minimumCoverage = value; } } private IList<string> _orderBy; /// <summary> /// Optional. Gets or sets the list of OData $orderby expressions by /// which to sort the results. Each expression can be either a field /// name or a call to the geo.distance() function. Each expression can /// be followed by asc to indicate ascending, and desc to indicate /// descending. The default is ascending order. Ties will be broken by /// the match scores of documents. If no OrderBy is specified, the /// default sort order is descending by document match score. There /// can be at most 32 Orderby clauses. /// </summary> public IList<string> OrderBy { get { return this._orderBy; } set { this._orderBy = value; } } private IList<string> _scoringParameters; /// <summary> /// Optional. Gets or sets the list of parameter values to be used in /// scoring functions (for example, referencePointParameter) using the /// format name:value. For example, if the scoring profile defines a /// function with a parameter called 'mylocation' the parameter string /// would be "mylocation:-122.2,44.8"(without the quotes). /// </summary> public IList<string> ScoringParameters { get { return this._scoringParameters; } set { this._scoringParameters = value; } } private string _scoringProfile; /// <summary> /// Optional. Gets or sets the name of a scoring profile to evaluate /// match scores for matching documents in order to sort the results. /// </summary> public string ScoringProfile { get { return this._scoringProfile; } set { this._scoringProfile = value; } } private IList<string> _searchFields; /// <summary> /// Optional. Gets or sets the list of field names to include in the /// full-text search. /// </summary> public IList<string> SearchFields { get { return this._searchFields; } set { this._searchFields = value; } } private SearchMode _searchMode; /// <summary> /// Optional. Gets or sets a value that specifies whether any or all of /// the search terms must be matched in order to count the document as /// a match. /// </summary> public SearchMode SearchMode { get { return this._searchMode; } set { this._searchMode = value; } } private IList<string> _select; /// <summary> /// Optional. Gets or sets the list of fields to retrieve. If /// unspecified, all fields marked as retrievable in the schema are /// included. /// </summary> public IList<string> Select { get { return this._select; } set { this._select = value; } } private int? _skip; /// <summary> /// Optional. Gets or sets the number of search results to skip. This /// value cannot be greater than 100,000. If you need to scan /// documents in sequence, but cannot use Skip due to this limitation, /// consider using OrderBy on a totally-ordered key and Filter with a /// range query instead. /// </summary> public int? Skip { get { return this._skip; } set { this._skip = value; } } private int? _top; /// <summary> /// Optional. Gets or sets the number of search results to retrieve. /// This can be used in conjunction with Skip to implement client-side /// paging of search results. If results are truncated due to /// server-side paging, the response will include a continuation token /// that can be passed to ContinueSearch to retrieve the next page of /// results. See DocumentSearchResponse.ContinuationToken for more /// information. (see /// https://msdn.microsoft.com/en-us/library/azure/dn798927.aspx for /// more information) /// </summary> public int? Top { get { return this._top; } set { this._top = value; } } /// <summary> /// Initializes a new instance of the SearchParameters class. /// </summary> public SearchParameters() { this.HighlightFields = new LazyList<string>(); this.OrderBy = new LazyList<string>(); this.ScoringParameters = new LazyList<string>(); this.SearchFields = new LazyList<string>(); this.Select = new LazyList<string>(); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using Aurora.Framework; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Services.Interfaces { public class UserAccount : AllScopeIDImpl, BaseCacheAccount { public int Created; public string Email; public string Name { get; set;} public OSDMap GenericData = new OSDMap(); public UUID PrincipalID { get; set; } public Dictionary<string, object> ServiceURLs; public int UserFlags; public int UserLevel; public string UserTitle; public UserAccount() { } public UserAccount(UUID principalID) { PrincipalID = principalID; } public UserAccount(UUID scopeID, string name, string email) { PrincipalID = UUID.Random(); ScopeID = scopeID; Name = name; Email = email; ServiceURLs = new Dictionary<string, object>(); Created = Util.UnixTimeSinceEpoch(); } public UserAccount(UUID scopeID, UUID principalID, string name, string email) { PrincipalID = principalID; ScopeID = scopeID; Name = name; Email = email; ServiceURLs = new Dictionary<string, object>(); Created = Util.UnixTimeSinceEpoch(); } public string FirstName { get { return Name.Split(' ')[0]; } } public string LastName { get { string[] split = Name.Split(' '); if (split.Length > 1) return Name.Split(' ')[1]; else return ""; } } public override Dictionary<string, object> ToKVP() { Dictionary<string, object> result = new Dictionary<string, object>(); result["FirstName"] = FirstName; result["LastName"] = LastName; result["Email"] = Email; result["PrincipalID"] = PrincipalID.ToString(); result["ScopeID"] = ScopeID.ToString(); result["Created"] = Created.ToString(); result["UserLevel"] = UserLevel.ToString(); result["UserFlags"] = UserFlags.ToString(); result["UserTitle"] = UserTitle; string str = ServiceURLs.Aggregate(string.Empty, (current, kvp) => current + (kvp.Key + "*" + (kvp.Value ?? "") + ";")); result["ServiceURLs"] = str; return result; } public override void FromKVP(Dictionary<string, object> kvp) { if (kvp.ContainsKey("FirstName") && kvp.ContainsKey("LastName")) Name = kvp["FirstName"] + " " + kvp["LastName"]; if (kvp.ContainsKey("Name")) Name = kvp["Name"].ToString(); if (kvp.ContainsKey("Email")) Email = kvp["Email"].ToString(); if (kvp.ContainsKey("PrincipalID")) { UUID id; if (UUID.TryParse(kvp["PrincipalID"].ToString(), out id)) PrincipalID = id; } if (kvp.ContainsKey("ScopeID")) UUID.TryParse(kvp["ScopeID"].ToString(), out ScopeID); if (kvp.ContainsKey("UserLevel")) UserLevel = Convert.ToInt32(kvp["UserLevel"].ToString()); if (kvp.ContainsKey("UserFlags")) UserFlags = Convert.ToInt32(kvp["UserFlags"].ToString()); if (kvp.ContainsKey("UserTitle")) UserTitle = kvp["UserTitle"].ToString(); if (kvp.ContainsKey("Created")) Created = Convert.ToInt32(kvp["Created"].ToString()); if (kvp.ContainsKey("ServiceURLs") && kvp["ServiceURLs"] != null) { ServiceURLs = new Dictionary<string, object>(); string str = kvp["ServiceURLs"].ToString(); if (str != string.Empty) { string[] parts = str.Split(new[] { ';' }); foreach (string[] parts2 in parts.Select(s => s.Split(new[] {'*'})).Where(parts2 => parts2.Length == 2)) { ServiceURLs[parts2[0]] = parts2[1]; } } } } public override OSDMap ToOSD() { OSDMap result = new OSDMap(); result["FirstName"] = FirstName; result["LastName"] = LastName; result["Name"] = Name; result["Email"] = Email; result["PrincipalID"] = PrincipalID; result["ScopeID"] = ScopeID; result["AllScopeIDs"] = AllScopeIDs.ToOSDArray(); result["Created"] = Created; result["UserLevel"] = UserLevel; result["UserFlags"] = UserFlags; result["UserTitle"] = UserTitle; string str = ServiceURLs.Aggregate(string.Empty, (current, kvp) => current + (kvp.Key + "*" + (kvp.Value ?? "") + ";")); result["ServiceURLs"] = str; return result; } public override void FromOSD(OSDMap map) { Name = map["FirstName"] + " " + map["LastName"]; if (map.ContainsKey("Name")) Name = map["Name"].AsString(); Email = map["Email"].AsString(); if (map.ContainsKey("PrincipalID")) PrincipalID = map["PrincipalID"]; if (map.ContainsKey("ScopeID")) ScopeID = map["ScopeID"]; if (map.ContainsKey("AllScopeIDs")) AllScopeIDs = ((OSDArray)map["AllScopeIDs"]).ConvertAll<UUID>(o => o); if (map.ContainsKey("UserLevel")) UserLevel = map["UserLevel"]; if (map.ContainsKey("UserFlags")) UserFlags = map["UserFlags"]; if (map.ContainsKey("UserTitle")) UserTitle = map["UserTitle"]; if (map.ContainsKey("Created")) Created = map["Created"]; ServiceURLs = new Dictionary<string, object>(); if (map.ContainsKey("ServiceURLs") && map["ServiceURLs"] != null) { string str = map["ServiceURLs"].ToString(); if (str != string.Empty) { string[] parts = str.Split(new[] { ';' }); foreach (string[] parts2 in parts.Select(s => s.Split(new[] {'*'})).Where(parts2 => parts2.Length == 2)) { ServiceURLs[parts2[0]] = parts2[1]; } } } } } public interface IUserAccountService { IUserAccountService InnerService { get; } /// <summary> /// Get a user given by UUID /// </summary> /// <param name = "scopeID"></param> /// <param name = "userID"></param> /// <returns></returns> UserAccount GetUserAccount(List<UUID> scopeIDs, UUID userID); /// <summary> /// Get a user given by a first and last name /// </summary> /// <param name = "scopeID"></param> /// <param name = "FirstName"></param> /// <param name = "LastName"></param> /// <returns></returns> UserAccount GetUserAccount(List<UUID> scopeIDs, string FirstName, string LastName); /// <summary> /// Get a user given by its full name /// </summary> /// <param name = "scopeID"></param> /// <param name = "Email"></param> /// <returns></returns> UserAccount GetUserAccount(List<UUID> scopeIDs, string Name); /// <summary> /// Returns the list of avatars that matches both the search criterion and the scope ID passed /// </summary> /// <param name = "scopeID"></param> /// <param name = "query"></param> /// <returns></returns> List<UserAccount> GetUserAccounts(List<UUID> scopeIDs, string query); /// <summary> /// Returns a paginated list of avatars that matches both the search criteriion and the scope ID passed /// </summary> /// <param name="scopeID"></param> /// <param name="query"></param> /// <param name="start"></param> /// <param name="count"></param> /// <returns></returns> List<UserAccount> GetUserAccounts(List<UUID> scopeIDs, string query, uint? start, uint? count); /// <summary> /// Returns a paginated list of avatars that matches both the search criteriion and the scope ID passed /// </summary> /// <param name="scopeID"></param> /// <param name="level">greater than or equal to clause is used</param> /// <param name="flags">bit mask clause is used</param> /// <returns></returns> List<UserAccount> GetUserAccounts(List<UUID> scopeIDs, int level, int flags); /// <summary> /// Returns the number of avatars that match both the search criterion and the scope ID passed /// </summary> /// <param name="scopeID"></param> /// <param name="query"></param> /// <returns></returns> uint NumberOfUserAccounts(List<UUID> scopeIDs, string query); /// <summary> /// Store the data given, wich replaces the stored data, therefore must be complete. /// </summary> /// <param name = "data"></param> /// <returns></returns> bool StoreUserAccount(UserAccount data); /// <summary> /// Cache the given userAccount so that it doesn't have to be queried later /// </summary> /// <param name="account"></param> void CacheAccount(UserAccount account); /// <summary> /// Create the user with the given info /// </summary> /// <param name = "name"></param> /// <param name = "md5password">MD5 hashed password</param> /// <param name = "email"></param> void CreateUser(string name, string md5password, string email); /// <summary> /// Create the user with the given info /// </summary> /// <param name = "name"></param> /// <param name = "md5password">MD5 hashed password</param> /// <param name = "email"></param> /// <returns>The error message (if one exists)</returns> string CreateUser(UUID userID, UUID scopeID, string name, string md5password, string email); /// <summary> /// Create the user with the given info /// </summary> /// <param name = "account"></param> /// <param name = "password"></param> /// <returns>The error message (if one exists)</returns> string CreateUser(UserAccount account, string password); /// <summary> /// Delete a user from the database permanently /// </summary> /// <param name="userID">The user's ID</param> /// <param name="password">The user's password</param> /// <param name="archiveInformation">Whether or not we should store the account's name and account information so that the user's information inworld does not go null</param> /// <param name="wipeFromDatabase">Whether or not we should remove all of the user's data from other locations in the database</param> void DeleteUser(UUID userID, string password, bool archiveInformation, bool wipeFromDatabase); } /// <summary> /// An interface for connecting to the user accounts datastore /// </summary> public interface IUserAccountData : IAuroraDataPlugin { string Realm { get; } UserAccount[] Get(List<UUID> scopeIDs, string[] fields, string[] values); bool Store(UserAccount data); bool DeleteAccount(UUID userID, bool archiveInformation); UserAccount[] GetUsers(List<UUID> scopeIDs, string query); UserAccount[] GetUsers(List<UUID> scopeIDs, string query, uint? start, uint? count); UserAccount[] GetUsers(List<UUID> scopeIDs, int level, int flags); uint NumberOfUsers(List<UUID> scopeIDs, string query); } }
#if !UNITY_WSA && !UNITY_WP8 using System; using UnityEngine; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading; using PlayFab.SharedModels; #if !DISABLE_PLAYFABCLIENT_API using PlayFab.ClientModels; #endif using PlayFab.Json; namespace PlayFab.Internal { public class PlayFabWebRequest : IPlayFabHttp { private static readonly Queue<Action> ResultQueue = new Queue<Action>(); private static readonly Queue<Action> _tempActions = new Queue<Action>(); private static readonly List<CallRequestContainer> ActiveRequests = new List<CallRequestContainer>(); private static Thread _requestQueueThread; private static readonly object _ThreadLock = new object(); private static readonly TimeSpan ThreadKillTimeout = TimeSpan.FromSeconds(60); private static DateTime _threadKillTime = DateTime.UtcNow + ThreadKillTimeout; // Kill the thread after 1 minute of inactivity private static bool _isApplicationPlaying; private static int _activeCallCount; private static string _unityVersion; private static string _authKey; private static bool _sessionStarted; public bool SessionStarted { get { return _sessionStarted; } set { _sessionStarted = value; } } public string AuthKey { get { return _authKey; } set { _authKey = value; } } public void InitializeHttp() { SetupCertificates(); _isApplicationPlaying = true; _unityVersion = Application.unityVersion; } public void OnDestroy() { _isApplicationPlaying = false; lock (ResultQueue) { ResultQueue.Clear(); } lock (ActiveRequests) { ActiveRequests.Clear(); } lock (_ThreadLock) { _requestQueueThread = null; } } private void SetupCertificates() { // These are performance Optimizations for HttpWebRequests. ServicePointManager.DefaultConnectionLimit = 10; ServicePointManager.Expect100Continue = false; //Support for SSL var rcvc = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); //(sender, cert, chain, ssl) => true ServicePointManager.ServerCertificateValidationCallback = rcvc; } private static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; } public void MakeApiCall(CallRequestContainer reqContainer) { reqContainer.HttpState = HttpRequestState.Idle; lock (ActiveRequests) { ActiveRequests.Insert(0, reqContainer); } ActivateThreadWorker(); } private static void ActivateThreadWorker() { lock (_ThreadLock) { if (_requestQueueThread != null) { return; } _requestQueueThread = new Thread(WorkerThreadMainLoop); _requestQueueThread.Start(); } } private static void WorkerThreadMainLoop() { try { bool active; lock (_ThreadLock) { // Kill the thread after 1 minute of inactivity _threadKillTime = DateTime.UtcNow + ThreadKillTimeout; } List<CallRequestContainer> localActiveRequests = new List<CallRequestContainer>(); do { //process active requests lock (ActiveRequests) { localActiveRequests.AddRange(ActiveRequests); ActiveRequests.Clear(); _activeCallCount = localActiveRequests.Count; } var activeCalls = localActiveRequests.Count; for (var i = activeCalls - 1; i >= 0; i--) // We must iterate backwards, because we remove at index i in some cases { switch (localActiveRequests[i].HttpState) { case HttpRequestState.Error: localActiveRequests.RemoveAt(i); break; case HttpRequestState.Idle: Post(localActiveRequests[i]); break; case HttpRequestState.Sent: if (localActiveRequests[i].HttpRequest.HaveResponse) // Else we'll try again next tick ProcessHttpResponse(localActiveRequests[i]); break; case HttpRequestState.Received: ProcessJsonResponse(localActiveRequests[i]); localActiveRequests.RemoveAt(i); break; } } #region Expire Thread. // Check if we've been inactive lock (_ThreadLock) { var now = DateTime.UtcNow; if (activeCalls > 0 && _isApplicationPlaying) { // Still active, reset the _threadKillTime _threadKillTime = now + ThreadKillTimeout; } // Kill the thread after 1 minute of inactivity active = now <= _threadKillTime; if (!active) { _requestQueueThread = null; } // This thread will be stopped, so null this now, inside lock (_threadLock) } #endregion Thread.Sleep(1); } while (active); } catch (Exception e) { Debug.LogException(e); _requestQueueThread = null; } } private static void Post(CallRequestContainer reqContainer) { try { reqContainer.HttpRequest = (HttpWebRequest)WebRequest.Create(reqContainer.FullUrl); reqContainer.HttpRequest.UserAgent = "UnityEngine-Unity; Version: " + _unityVersion; reqContainer.HttpRequest.SendChunked = false; reqContainer.HttpRequest.Proxy = null; // Prevents hitting a proxy if no proxy is available. TODO: Add support for proxy's. reqContainer.HttpRequest.Headers.Add("X-ReportErrorAsSuccess", "true"); // Without this, we have to catch WebException instead, and manually decode the result reqContainer.HttpRequest.Headers.Add("X-PlayFabSDK", PlayFabSettings.VersionString); switch (reqContainer.AuthKey) { #if ENABLE_PLAYFABSERVER_API || ENABLE_PLAYFABADMIN_API case AuthType.DevSecretKey: reqContainer.HttpRequest.Headers.Add("X-SecretKey", PlayFabSettings.DeveloperSecretKey); break; #endif case AuthType.LoginSession: reqContainer.HttpRequest.Headers.Add("X-Authorization", _authKey); break; } reqContainer.HttpRequest.ContentType = "application/json"; reqContainer.HttpRequest.Method = "POST"; reqContainer.HttpRequest.KeepAlive = PlayFabSettings.RequestKeepAlive; reqContainer.HttpRequest.Timeout = PlayFabSettings.RequestTimeout; reqContainer.HttpRequest.AllowWriteStreamBuffering = false; reqContainer.HttpRequest.Proxy = null; reqContainer.HttpRequest.ContentLength = reqContainer.Payload.LongLength; reqContainer.HttpRequest.ReadWriteTimeout = PlayFabSettings.RequestTimeout; //Debug.Log("Get Stream"); // Get Request Stream and send data in the body. using (var stream = reqContainer.HttpRequest.GetRequestStream()) { //Debug.Log("Post Stream"); stream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length); //Debug.Log("After Post stream"); } reqContainer.HttpState = HttpRequestState.Sent; } catch (WebException e) { reqContainer.JsonResponse = ResponseToString(e.Response) ?? e.Status + ": WebException making http request to: " + reqContainer.FullUrl; var enhancedError = new WebException(reqContainer.JsonResponse, e); Debug.LogException(enhancedError); QueueRequestError(reqContainer); } catch (Exception e) { reqContainer.JsonResponse = "Unhandled exception in Post : " + reqContainer.FullUrl; var enhancedError = new Exception(reqContainer.JsonResponse, e); Debug.LogException(enhancedError); QueueRequestError(reqContainer); } } private static void ProcessHttpResponse(CallRequestContainer reqContainer) { try { #if PLAYFAB_REQUEST_TIMING reqContainer.Timing.WorkerRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds; #endif // Get and check the response var httpResponse = (HttpWebResponse)reqContainer.HttpRequest.GetResponse(); if (httpResponse.StatusCode == HttpStatusCode.OK) { reqContainer.JsonResponse = ResponseToString(httpResponse); } if (httpResponse.StatusCode != HttpStatusCode.OK || string.IsNullOrEmpty(reqContainer.JsonResponse)) { reqContainer.JsonResponse = reqContainer.JsonResponse ?? "No response from server"; QueueRequestError(reqContainer); return; } else { // Response Recieved Successfully, now process. } reqContainer.HttpState = HttpRequestState.Received; } catch (Exception e) { var msg = "Unhandled exception in ProcessHttpResponse : " + reqContainer.FullUrl; reqContainer.JsonResponse = reqContainer.JsonResponse ?? msg; var enhancedError = new Exception(msg, e); Debug.LogException(enhancedError); QueueRequestError(reqContainer); } } /// <summary> /// Set the reqContainer into an error state, and queue it to invoke the ErrorCallback for that request /// </summary> private static void QueueRequestError(CallRequestContainer reqContainer) { reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.JsonResponse, reqContainer.CustomData); // Decode the server-json error reqContainer.HttpState = HttpRequestState.Error; lock (ResultQueue) { //Queue The result callbacks to run on the main thread. ResultQueue.Enqueue(() => { PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error); if (reqContainer.ErrorCallback != null) reqContainer.ErrorCallback(reqContainer.Error); }); } } private static void ProcessJsonResponse(CallRequestContainer reqContainer) { try { var httpResult = JsonWrapper.DeserializeObject<HttpResponseObject>(reqContainer.JsonResponse, PlayFabUtil.ApiSerializerStrategy); #if PLAYFAB_REQUEST_TIMING reqContainer.Timing.WorkerRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds; #endif //This would happen if playfab returned a 500 internal server error or a bad json response. if (httpResult == null || httpResult.code != 200) { QueueRequestError(reqContainer); return; } reqContainer.JsonResponse = JsonWrapper.SerializeObject(httpResult.data, PlayFabUtil.ApiSerializerStrategy); reqContainer.DeserializeResultJson(); // Assigns Result with a properly typed object reqContainer.ApiResult.Request = reqContainer.ApiRequest; reqContainer.ApiResult.CustomData = reqContainer.CustomData; #if !DISABLE_PLAYFABCLIENT_API ClientModels.UserSettings userSettings = null; var res = reqContainer.ApiResult as ClientModels.LoginResult; var regRes = reqContainer.ApiResult as ClientModels.RegisterPlayFabUserResult; if (res != null) { userSettings = res.SettingsForUser; _authKey = res.SessionTicket; } else if (regRes != null) { userSettings = regRes.SettingsForUser; _authKey = regRes.SessionTicket; } if (userSettings != null && _authKey != null && userSettings.NeedsAttribution) { lock (ResultQueue) { ResultQueue.Enqueue(PlayFabIdfa.OnPlayFabLogin); } } var cloudScriptUrl = reqContainer.ApiResult as ClientModels.GetCloudScriptUrlResult; if (cloudScriptUrl != null) { PlayFabSettings.LogicServerUrl = cloudScriptUrl.Url; } #endif lock (ResultQueue) { //Queue The result callbacks to run on the main thread. ResultQueue.Enqueue(() => { #if PLAYFAB_REQUEST_TIMING reqContainer.Stopwatch.Stop(); reqContainer.Timing.MainThreadRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds; PlayFabHttp.SendRequestTiming(reqContainer.Timing); #endif try { PlayFabHttp.SendEvent(reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post); reqContainer.InvokeSuccessCallback(); } catch (Exception e) { Debug.LogException(e); // Log the user's callback exception back to them without halting PlayFabHttp } }); } } catch (Exception e) { var msg = "Unhandled exception in ProcessJsonResponse : " + reqContainer.FullUrl; reqContainer.JsonResponse = reqContainer.JsonResponse ?? msg; var enhancedError = new Exception(msg, e); Debug.LogException(enhancedError); QueueRequestError(reqContainer); } } public void Update() { lock (ResultQueue) { while (ResultQueue.Count > 0) { var actionToQueue = ResultQueue.Dequeue(); _tempActions.Enqueue(actionToQueue); } } while (_tempActions.Count > 0) { var finishedRequest = _tempActions.Dequeue(); finishedRequest(); } } private static string ResponseToString(WebResponse webResponse) { if (webResponse == null) return null; try { using (var responseStream = webResponse.GetResponseStream()) { if (responseStream == null) return null; using (var stream = new StreamReader(responseStream)) { return stream.ReadToEnd(); } } } catch (WebException webException) { try { using (var responseStream = webException.Response.GetResponseStream()) { if (responseStream == null) return null; using (var stream = new StreamReader(responseStream)) { return stream.ReadToEnd(); } } } catch (Exception e) { Debug.LogException(e); return null; } } catch (Exception e) { Debug.LogException(e); return null; } } public int GetPendingMessages() { var count = 0; lock (ActiveRequests) count += ActiveRequests.Count + _activeCallCount; lock (ResultQueue) count += ResultQueue.Count; return count; } } } #endif
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp.Swizzle { /// <summary> /// Temporary vector of type double with 3 components, used for implementing swizzling for dvec3. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct swizzle_dvec3 { #region Fields /// <summary> /// x-component /// </summary> internal readonly double x; /// <summary> /// y-component /// </summary> internal readonly double y; /// <summary> /// z-component /// </summary> internal readonly double z; #endregion #region Constructors /// <summary> /// Constructor for swizzle_dvec3. /// </summary> internal swizzle_dvec3(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } #endregion #region Properties /// <summary> /// Returns dvec3.xx swizzling. /// </summary> public dvec2 xx => new dvec2(x, x); /// <summary> /// Returns dvec3.rr swizzling (equivalent to dvec3.xx). /// </summary> public dvec2 rr => new dvec2(x, x); /// <summary> /// Returns dvec3.xxx swizzling. /// </summary> public dvec3 xxx => new dvec3(x, x, x); /// <summary> /// Returns dvec3.rrr swizzling (equivalent to dvec3.xxx). /// </summary> public dvec3 rrr => new dvec3(x, x, x); /// <summary> /// Returns dvec3.xxxx swizzling. /// </summary> public dvec4 xxxx => new dvec4(x, x, x, x); /// <summary> /// Returns dvec3.rrrr swizzling (equivalent to dvec3.xxxx). /// </summary> public dvec4 rrrr => new dvec4(x, x, x, x); /// <summary> /// Returns dvec3.xxxy swizzling. /// </summary> public dvec4 xxxy => new dvec4(x, x, x, y); /// <summary> /// Returns dvec3.rrrg swizzling (equivalent to dvec3.xxxy). /// </summary> public dvec4 rrrg => new dvec4(x, x, x, y); /// <summary> /// Returns dvec3.xxxz swizzling. /// </summary> public dvec4 xxxz => new dvec4(x, x, x, z); /// <summary> /// Returns dvec3.rrrb swizzling (equivalent to dvec3.xxxz). /// </summary> public dvec4 rrrb => new dvec4(x, x, x, z); /// <summary> /// Returns dvec3.xxy swizzling. /// </summary> public dvec3 xxy => new dvec3(x, x, y); /// <summary> /// Returns dvec3.rrg swizzling (equivalent to dvec3.xxy). /// </summary> public dvec3 rrg => new dvec3(x, x, y); /// <summary> /// Returns dvec3.xxyx swizzling. /// </summary> public dvec4 xxyx => new dvec4(x, x, y, x); /// <summary> /// Returns dvec3.rrgr swizzling (equivalent to dvec3.xxyx). /// </summary> public dvec4 rrgr => new dvec4(x, x, y, x); /// <summary> /// Returns dvec3.xxyy swizzling. /// </summary> public dvec4 xxyy => new dvec4(x, x, y, y); /// <summary> /// Returns dvec3.rrgg swizzling (equivalent to dvec3.xxyy). /// </summary> public dvec4 rrgg => new dvec4(x, x, y, y); /// <summary> /// Returns dvec3.xxyz swizzling. /// </summary> public dvec4 xxyz => new dvec4(x, x, y, z); /// <summary> /// Returns dvec3.rrgb swizzling (equivalent to dvec3.xxyz). /// </summary> public dvec4 rrgb => new dvec4(x, x, y, z); /// <summary> /// Returns dvec3.xxz swizzling. /// </summary> public dvec3 xxz => new dvec3(x, x, z); /// <summary> /// Returns dvec3.rrb swizzling (equivalent to dvec3.xxz). /// </summary> public dvec3 rrb => new dvec3(x, x, z); /// <summary> /// Returns dvec3.xxzx swizzling. /// </summary> public dvec4 xxzx => new dvec4(x, x, z, x); /// <summary> /// Returns dvec3.rrbr swizzling (equivalent to dvec3.xxzx). /// </summary> public dvec4 rrbr => new dvec4(x, x, z, x); /// <summary> /// Returns dvec3.xxzy swizzling. /// </summary> public dvec4 xxzy => new dvec4(x, x, z, y); /// <summary> /// Returns dvec3.rrbg swizzling (equivalent to dvec3.xxzy). /// </summary> public dvec4 rrbg => new dvec4(x, x, z, y); /// <summary> /// Returns dvec3.xxzz swizzling. /// </summary> public dvec4 xxzz => new dvec4(x, x, z, z); /// <summary> /// Returns dvec3.rrbb swizzling (equivalent to dvec3.xxzz). /// </summary> public dvec4 rrbb => new dvec4(x, x, z, z); /// <summary> /// Returns dvec3.xy swizzling. /// </summary> public dvec2 xy => new dvec2(x, y); /// <summary> /// Returns dvec3.rg swizzling (equivalent to dvec3.xy). /// </summary> public dvec2 rg => new dvec2(x, y); /// <summary> /// Returns dvec3.xyx swizzling. /// </summary> public dvec3 xyx => new dvec3(x, y, x); /// <summary> /// Returns dvec3.rgr swizzling (equivalent to dvec3.xyx). /// </summary> public dvec3 rgr => new dvec3(x, y, x); /// <summary> /// Returns dvec3.xyxx swizzling. /// </summary> public dvec4 xyxx => new dvec4(x, y, x, x); /// <summary> /// Returns dvec3.rgrr swizzling (equivalent to dvec3.xyxx). /// </summary> public dvec4 rgrr => new dvec4(x, y, x, x); /// <summary> /// Returns dvec3.xyxy swizzling. /// </summary> public dvec4 xyxy => new dvec4(x, y, x, y); /// <summary> /// Returns dvec3.rgrg swizzling (equivalent to dvec3.xyxy). /// </summary> public dvec4 rgrg => new dvec4(x, y, x, y); /// <summary> /// Returns dvec3.xyxz swizzling. /// </summary> public dvec4 xyxz => new dvec4(x, y, x, z); /// <summary> /// Returns dvec3.rgrb swizzling (equivalent to dvec3.xyxz). /// </summary> public dvec4 rgrb => new dvec4(x, y, x, z); /// <summary> /// Returns dvec3.xyy swizzling. /// </summary> public dvec3 xyy => new dvec3(x, y, y); /// <summary> /// Returns dvec3.rgg swizzling (equivalent to dvec3.xyy). /// </summary> public dvec3 rgg => new dvec3(x, y, y); /// <summary> /// Returns dvec3.xyyx swizzling. /// </summary> public dvec4 xyyx => new dvec4(x, y, y, x); /// <summary> /// Returns dvec3.rggr swizzling (equivalent to dvec3.xyyx). /// </summary> public dvec4 rggr => new dvec4(x, y, y, x); /// <summary> /// Returns dvec3.xyyy swizzling. /// </summary> public dvec4 xyyy => new dvec4(x, y, y, y); /// <summary> /// Returns dvec3.rggg swizzling (equivalent to dvec3.xyyy). /// </summary> public dvec4 rggg => new dvec4(x, y, y, y); /// <summary> /// Returns dvec3.xyyz swizzling. /// </summary> public dvec4 xyyz => new dvec4(x, y, y, z); /// <summary> /// Returns dvec3.rggb swizzling (equivalent to dvec3.xyyz). /// </summary> public dvec4 rggb => new dvec4(x, y, y, z); /// <summary> /// Returns dvec3.xyz swizzling. /// </summary> public dvec3 xyz => new dvec3(x, y, z); /// <summary> /// Returns dvec3.rgb swizzling (equivalent to dvec3.xyz). /// </summary> public dvec3 rgb => new dvec3(x, y, z); /// <summary> /// Returns dvec3.xyzx swizzling. /// </summary> public dvec4 xyzx => new dvec4(x, y, z, x); /// <summary> /// Returns dvec3.rgbr swizzling (equivalent to dvec3.xyzx). /// </summary> public dvec4 rgbr => new dvec4(x, y, z, x); /// <summary> /// Returns dvec3.xyzy swizzling. /// </summary> public dvec4 xyzy => new dvec4(x, y, z, y); /// <summary> /// Returns dvec3.rgbg swizzling (equivalent to dvec3.xyzy). /// </summary> public dvec4 rgbg => new dvec4(x, y, z, y); /// <summary> /// Returns dvec3.xyzz swizzling. /// </summary> public dvec4 xyzz => new dvec4(x, y, z, z); /// <summary> /// Returns dvec3.rgbb swizzling (equivalent to dvec3.xyzz). /// </summary> public dvec4 rgbb => new dvec4(x, y, z, z); /// <summary> /// Returns dvec3.xz swizzling. /// </summary> public dvec2 xz => new dvec2(x, z); /// <summary> /// Returns dvec3.rb swizzling (equivalent to dvec3.xz). /// </summary> public dvec2 rb => new dvec2(x, z); /// <summary> /// Returns dvec3.xzx swizzling. /// </summary> public dvec3 xzx => new dvec3(x, z, x); /// <summary> /// Returns dvec3.rbr swizzling (equivalent to dvec3.xzx). /// </summary> public dvec3 rbr => new dvec3(x, z, x); /// <summary> /// Returns dvec3.xzxx swizzling. /// </summary> public dvec4 xzxx => new dvec4(x, z, x, x); /// <summary> /// Returns dvec3.rbrr swizzling (equivalent to dvec3.xzxx). /// </summary> public dvec4 rbrr => new dvec4(x, z, x, x); /// <summary> /// Returns dvec3.xzxy swizzling. /// </summary> public dvec4 xzxy => new dvec4(x, z, x, y); /// <summary> /// Returns dvec3.rbrg swizzling (equivalent to dvec3.xzxy). /// </summary> public dvec4 rbrg => new dvec4(x, z, x, y); /// <summary> /// Returns dvec3.xzxz swizzling. /// </summary> public dvec4 xzxz => new dvec4(x, z, x, z); /// <summary> /// Returns dvec3.rbrb swizzling (equivalent to dvec3.xzxz). /// </summary> public dvec4 rbrb => new dvec4(x, z, x, z); /// <summary> /// Returns dvec3.xzy swizzling. /// </summary> public dvec3 xzy => new dvec3(x, z, y); /// <summary> /// Returns dvec3.rbg swizzling (equivalent to dvec3.xzy). /// </summary> public dvec3 rbg => new dvec3(x, z, y); /// <summary> /// Returns dvec3.xzyx swizzling. /// </summary> public dvec4 xzyx => new dvec4(x, z, y, x); /// <summary> /// Returns dvec3.rbgr swizzling (equivalent to dvec3.xzyx). /// </summary> public dvec4 rbgr => new dvec4(x, z, y, x); /// <summary> /// Returns dvec3.xzyy swizzling. /// </summary> public dvec4 xzyy => new dvec4(x, z, y, y); /// <summary> /// Returns dvec3.rbgg swizzling (equivalent to dvec3.xzyy). /// </summary> public dvec4 rbgg => new dvec4(x, z, y, y); /// <summary> /// Returns dvec3.xzyz swizzling. /// </summary> public dvec4 xzyz => new dvec4(x, z, y, z); /// <summary> /// Returns dvec3.rbgb swizzling (equivalent to dvec3.xzyz). /// </summary> public dvec4 rbgb => new dvec4(x, z, y, z); /// <summary> /// Returns dvec3.xzz swizzling. /// </summary> public dvec3 xzz => new dvec3(x, z, z); /// <summary> /// Returns dvec3.rbb swizzling (equivalent to dvec3.xzz). /// </summary> public dvec3 rbb => new dvec3(x, z, z); /// <summary> /// Returns dvec3.xzzx swizzling. /// </summary> public dvec4 xzzx => new dvec4(x, z, z, x); /// <summary> /// Returns dvec3.rbbr swizzling (equivalent to dvec3.xzzx). /// </summary> public dvec4 rbbr => new dvec4(x, z, z, x); /// <summary> /// Returns dvec3.xzzy swizzling. /// </summary> public dvec4 xzzy => new dvec4(x, z, z, y); /// <summary> /// Returns dvec3.rbbg swizzling (equivalent to dvec3.xzzy). /// </summary> public dvec4 rbbg => new dvec4(x, z, z, y); /// <summary> /// Returns dvec3.xzzz swizzling. /// </summary> public dvec4 xzzz => new dvec4(x, z, z, z); /// <summary> /// Returns dvec3.rbbb swizzling (equivalent to dvec3.xzzz). /// </summary> public dvec4 rbbb => new dvec4(x, z, z, z); /// <summary> /// Returns dvec3.yx swizzling. /// </summary> public dvec2 yx => new dvec2(y, x); /// <summary> /// Returns dvec3.gr swizzling (equivalent to dvec3.yx). /// </summary> public dvec2 gr => new dvec2(y, x); /// <summary> /// Returns dvec3.yxx swizzling. /// </summary> public dvec3 yxx => new dvec3(y, x, x); /// <summary> /// Returns dvec3.grr swizzling (equivalent to dvec3.yxx). /// </summary> public dvec3 grr => new dvec3(y, x, x); /// <summary> /// Returns dvec3.yxxx swizzling. /// </summary> public dvec4 yxxx => new dvec4(y, x, x, x); /// <summary> /// Returns dvec3.grrr swizzling (equivalent to dvec3.yxxx). /// </summary> public dvec4 grrr => new dvec4(y, x, x, x); /// <summary> /// Returns dvec3.yxxy swizzling. /// </summary> public dvec4 yxxy => new dvec4(y, x, x, y); /// <summary> /// Returns dvec3.grrg swizzling (equivalent to dvec3.yxxy). /// </summary> public dvec4 grrg => new dvec4(y, x, x, y); /// <summary> /// Returns dvec3.yxxz swizzling. /// </summary> public dvec4 yxxz => new dvec4(y, x, x, z); /// <summary> /// Returns dvec3.grrb swizzling (equivalent to dvec3.yxxz). /// </summary> public dvec4 grrb => new dvec4(y, x, x, z); /// <summary> /// Returns dvec3.yxy swizzling. /// </summary> public dvec3 yxy => new dvec3(y, x, y); /// <summary> /// Returns dvec3.grg swizzling (equivalent to dvec3.yxy). /// </summary> public dvec3 grg => new dvec3(y, x, y); /// <summary> /// Returns dvec3.yxyx swizzling. /// </summary> public dvec4 yxyx => new dvec4(y, x, y, x); /// <summary> /// Returns dvec3.grgr swizzling (equivalent to dvec3.yxyx). /// </summary> public dvec4 grgr => new dvec4(y, x, y, x); /// <summary> /// Returns dvec3.yxyy swizzling. /// </summary> public dvec4 yxyy => new dvec4(y, x, y, y); /// <summary> /// Returns dvec3.grgg swizzling (equivalent to dvec3.yxyy). /// </summary> public dvec4 grgg => new dvec4(y, x, y, y); /// <summary> /// Returns dvec3.yxyz swizzling. /// </summary> public dvec4 yxyz => new dvec4(y, x, y, z); /// <summary> /// Returns dvec3.grgb swizzling (equivalent to dvec3.yxyz). /// </summary> public dvec4 grgb => new dvec4(y, x, y, z); /// <summary> /// Returns dvec3.yxz swizzling. /// </summary> public dvec3 yxz => new dvec3(y, x, z); /// <summary> /// Returns dvec3.grb swizzling (equivalent to dvec3.yxz). /// </summary> public dvec3 grb => new dvec3(y, x, z); /// <summary> /// Returns dvec3.yxzx swizzling. /// </summary> public dvec4 yxzx => new dvec4(y, x, z, x); /// <summary> /// Returns dvec3.grbr swizzling (equivalent to dvec3.yxzx). /// </summary> public dvec4 grbr => new dvec4(y, x, z, x); /// <summary> /// Returns dvec3.yxzy swizzling. /// </summary> public dvec4 yxzy => new dvec4(y, x, z, y); /// <summary> /// Returns dvec3.grbg swizzling (equivalent to dvec3.yxzy). /// </summary> public dvec4 grbg => new dvec4(y, x, z, y); /// <summary> /// Returns dvec3.yxzz swizzling. /// </summary> public dvec4 yxzz => new dvec4(y, x, z, z); /// <summary> /// Returns dvec3.grbb swizzling (equivalent to dvec3.yxzz). /// </summary> public dvec4 grbb => new dvec4(y, x, z, z); /// <summary> /// Returns dvec3.yy swizzling. /// </summary> public dvec2 yy => new dvec2(y, y); /// <summary> /// Returns dvec3.gg swizzling (equivalent to dvec3.yy). /// </summary> public dvec2 gg => new dvec2(y, y); /// <summary> /// Returns dvec3.yyx swizzling. /// </summary> public dvec3 yyx => new dvec3(y, y, x); /// <summary> /// Returns dvec3.ggr swizzling (equivalent to dvec3.yyx). /// </summary> public dvec3 ggr => new dvec3(y, y, x); /// <summary> /// Returns dvec3.yyxx swizzling. /// </summary> public dvec4 yyxx => new dvec4(y, y, x, x); /// <summary> /// Returns dvec3.ggrr swizzling (equivalent to dvec3.yyxx). /// </summary> public dvec4 ggrr => new dvec4(y, y, x, x); /// <summary> /// Returns dvec3.yyxy swizzling. /// </summary> public dvec4 yyxy => new dvec4(y, y, x, y); /// <summary> /// Returns dvec3.ggrg swizzling (equivalent to dvec3.yyxy). /// </summary> public dvec4 ggrg => new dvec4(y, y, x, y); /// <summary> /// Returns dvec3.yyxz swizzling. /// </summary> public dvec4 yyxz => new dvec4(y, y, x, z); /// <summary> /// Returns dvec3.ggrb swizzling (equivalent to dvec3.yyxz). /// </summary> public dvec4 ggrb => new dvec4(y, y, x, z); /// <summary> /// Returns dvec3.yyy swizzling. /// </summary> public dvec3 yyy => new dvec3(y, y, y); /// <summary> /// Returns dvec3.ggg swizzling (equivalent to dvec3.yyy). /// </summary> public dvec3 ggg => new dvec3(y, y, y); /// <summary> /// Returns dvec3.yyyx swizzling. /// </summary> public dvec4 yyyx => new dvec4(y, y, y, x); /// <summary> /// Returns dvec3.gggr swizzling (equivalent to dvec3.yyyx). /// </summary> public dvec4 gggr => new dvec4(y, y, y, x); /// <summary> /// Returns dvec3.yyyy swizzling. /// </summary> public dvec4 yyyy => new dvec4(y, y, y, y); /// <summary> /// Returns dvec3.gggg swizzling (equivalent to dvec3.yyyy). /// </summary> public dvec4 gggg => new dvec4(y, y, y, y); /// <summary> /// Returns dvec3.yyyz swizzling. /// </summary> public dvec4 yyyz => new dvec4(y, y, y, z); /// <summary> /// Returns dvec3.gggb swizzling (equivalent to dvec3.yyyz). /// </summary> public dvec4 gggb => new dvec4(y, y, y, z); /// <summary> /// Returns dvec3.yyz swizzling. /// </summary> public dvec3 yyz => new dvec3(y, y, z); /// <summary> /// Returns dvec3.ggb swizzling (equivalent to dvec3.yyz). /// </summary> public dvec3 ggb => new dvec3(y, y, z); /// <summary> /// Returns dvec3.yyzx swizzling. /// </summary> public dvec4 yyzx => new dvec4(y, y, z, x); /// <summary> /// Returns dvec3.ggbr swizzling (equivalent to dvec3.yyzx). /// </summary> public dvec4 ggbr => new dvec4(y, y, z, x); /// <summary> /// Returns dvec3.yyzy swizzling. /// </summary> public dvec4 yyzy => new dvec4(y, y, z, y); /// <summary> /// Returns dvec3.ggbg swizzling (equivalent to dvec3.yyzy). /// </summary> public dvec4 ggbg => new dvec4(y, y, z, y); /// <summary> /// Returns dvec3.yyzz swizzling. /// </summary> public dvec4 yyzz => new dvec4(y, y, z, z); /// <summary> /// Returns dvec3.ggbb swizzling (equivalent to dvec3.yyzz). /// </summary> public dvec4 ggbb => new dvec4(y, y, z, z); /// <summary> /// Returns dvec3.yz swizzling. /// </summary> public dvec2 yz => new dvec2(y, z); /// <summary> /// Returns dvec3.gb swizzling (equivalent to dvec3.yz). /// </summary> public dvec2 gb => new dvec2(y, z); /// <summary> /// Returns dvec3.yzx swizzling. /// </summary> public dvec3 yzx => new dvec3(y, z, x); /// <summary> /// Returns dvec3.gbr swizzling (equivalent to dvec3.yzx). /// </summary> public dvec3 gbr => new dvec3(y, z, x); /// <summary> /// Returns dvec3.yzxx swizzling. /// </summary> public dvec4 yzxx => new dvec4(y, z, x, x); /// <summary> /// Returns dvec3.gbrr swizzling (equivalent to dvec3.yzxx). /// </summary> public dvec4 gbrr => new dvec4(y, z, x, x); /// <summary> /// Returns dvec3.yzxy swizzling. /// </summary> public dvec4 yzxy => new dvec4(y, z, x, y); /// <summary> /// Returns dvec3.gbrg swizzling (equivalent to dvec3.yzxy). /// </summary> public dvec4 gbrg => new dvec4(y, z, x, y); /// <summary> /// Returns dvec3.yzxz swizzling. /// </summary> public dvec4 yzxz => new dvec4(y, z, x, z); /// <summary> /// Returns dvec3.gbrb swizzling (equivalent to dvec3.yzxz). /// </summary> public dvec4 gbrb => new dvec4(y, z, x, z); /// <summary> /// Returns dvec3.yzy swizzling. /// </summary> public dvec3 yzy => new dvec3(y, z, y); /// <summary> /// Returns dvec3.gbg swizzling (equivalent to dvec3.yzy). /// </summary> public dvec3 gbg => new dvec3(y, z, y); /// <summary> /// Returns dvec3.yzyx swizzling. /// </summary> public dvec4 yzyx => new dvec4(y, z, y, x); /// <summary> /// Returns dvec3.gbgr swizzling (equivalent to dvec3.yzyx). /// </summary> public dvec4 gbgr => new dvec4(y, z, y, x); /// <summary> /// Returns dvec3.yzyy swizzling. /// </summary> public dvec4 yzyy => new dvec4(y, z, y, y); /// <summary> /// Returns dvec3.gbgg swizzling (equivalent to dvec3.yzyy). /// </summary> public dvec4 gbgg => new dvec4(y, z, y, y); /// <summary> /// Returns dvec3.yzyz swizzling. /// </summary> public dvec4 yzyz => new dvec4(y, z, y, z); /// <summary> /// Returns dvec3.gbgb swizzling (equivalent to dvec3.yzyz). /// </summary> public dvec4 gbgb => new dvec4(y, z, y, z); /// <summary> /// Returns dvec3.yzz swizzling. /// </summary> public dvec3 yzz => new dvec3(y, z, z); /// <summary> /// Returns dvec3.gbb swizzling (equivalent to dvec3.yzz). /// </summary> public dvec3 gbb => new dvec3(y, z, z); /// <summary> /// Returns dvec3.yzzx swizzling. /// </summary> public dvec4 yzzx => new dvec4(y, z, z, x); /// <summary> /// Returns dvec3.gbbr swizzling (equivalent to dvec3.yzzx). /// </summary> public dvec4 gbbr => new dvec4(y, z, z, x); /// <summary> /// Returns dvec3.yzzy swizzling. /// </summary> public dvec4 yzzy => new dvec4(y, z, z, y); /// <summary> /// Returns dvec3.gbbg swizzling (equivalent to dvec3.yzzy). /// </summary> public dvec4 gbbg => new dvec4(y, z, z, y); /// <summary> /// Returns dvec3.yzzz swizzling. /// </summary> public dvec4 yzzz => new dvec4(y, z, z, z); /// <summary> /// Returns dvec3.gbbb swizzling (equivalent to dvec3.yzzz). /// </summary> public dvec4 gbbb => new dvec4(y, z, z, z); /// <summary> /// Returns dvec3.zx swizzling. /// </summary> public dvec2 zx => new dvec2(z, x); /// <summary> /// Returns dvec3.br swizzling (equivalent to dvec3.zx). /// </summary> public dvec2 br => new dvec2(z, x); /// <summary> /// Returns dvec3.zxx swizzling. /// </summary> public dvec3 zxx => new dvec3(z, x, x); /// <summary> /// Returns dvec3.brr swizzling (equivalent to dvec3.zxx). /// </summary> public dvec3 brr => new dvec3(z, x, x); /// <summary> /// Returns dvec3.zxxx swizzling. /// </summary> public dvec4 zxxx => new dvec4(z, x, x, x); /// <summary> /// Returns dvec3.brrr swizzling (equivalent to dvec3.zxxx). /// </summary> public dvec4 brrr => new dvec4(z, x, x, x); /// <summary> /// Returns dvec3.zxxy swizzling. /// </summary> public dvec4 zxxy => new dvec4(z, x, x, y); /// <summary> /// Returns dvec3.brrg swizzling (equivalent to dvec3.zxxy). /// </summary> public dvec4 brrg => new dvec4(z, x, x, y); /// <summary> /// Returns dvec3.zxxz swizzling. /// </summary> public dvec4 zxxz => new dvec4(z, x, x, z); /// <summary> /// Returns dvec3.brrb swizzling (equivalent to dvec3.zxxz). /// </summary> public dvec4 brrb => new dvec4(z, x, x, z); /// <summary> /// Returns dvec3.zxy swizzling. /// </summary> public dvec3 zxy => new dvec3(z, x, y); /// <summary> /// Returns dvec3.brg swizzling (equivalent to dvec3.zxy). /// </summary> public dvec3 brg => new dvec3(z, x, y); /// <summary> /// Returns dvec3.zxyx swizzling. /// </summary> public dvec4 zxyx => new dvec4(z, x, y, x); /// <summary> /// Returns dvec3.brgr swizzling (equivalent to dvec3.zxyx). /// </summary> public dvec4 brgr => new dvec4(z, x, y, x); /// <summary> /// Returns dvec3.zxyy swizzling. /// </summary> public dvec4 zxyy => new dvec4(z, x, y, y); /// <summary> /// Returns dvec3.brgg swizzling (equivalent to dvec3.zxyy). /// </summary> public dvec4 brgg => new dvec4(z, x, y, y); /// <summary> /// Returns dvec3.zxyz swizzling. /// </summary> public dvec4 zxyz => new dvec4(z, x, y, z); /// <summary> /// Returns dvec3.brgb swizzling (equivalent to dvec3.zxyz). /// </summary> public dvec4 brgb => new dvec4(z, x, y, z); /// <summary> /// Returns dvec3.zxz swizzling. /// </summary> public dvec3 zxz => new dvec3(z, x, z); /// <summary> /// Returns dvec3.brb swizzling (equivalent to dvec3.zxz). /// </summary> public dvec3 brb => new dvec3(z, x, z); /// <summary> /// Returns dvec3.zxzx swizzling. /// </summary> public dvec4 zxzx => new dvec4(z, x, z, x); /// <summary> /// Returns dvec3.brbr swizzling (equivalent to dvec3.zxzx). /// </summary> public dvec4 brbr => new dvec4(z, x, z, x); /// <summary> /// Returns dvec3.zxzy swizzling. /// </summary> public dvec4 zxzy => new dvec4(z, x, z, y); /// <summary> /// Returns dvec3.brbg swizzling (equivalent to dvec3.zxzy). /// </summary> public dvec4 brbg => new dvec4(z, x, z, y); /// <summary> /// Returns dvec3.zxzz swizzling. /// </summary> public dvec4 zxzz => new dvec4(z, x, z, z); /// <summary> /// Returns dvec3.brbb swizzling (equivalent to dvec3.zxzz). /// </summary> public dvec4 brbb => new dvec4(z, x, z, z); /// <summary> /// Returns dvec3.zy swizzling. /// </summary> public dvec2 zy => new dvec2(z, y); /// <summary> /// Returns dvec3.bg swizzling (equivalent to dvec3.zy). /// </summary> public dvec2 bg => new dvec2(z, y); /// <summary> /// Returns dvec3.zyx swizzling. /// </summary> public dvec3 zyx => new dvec3(z, y, x); /// <summary> /// Returns dvec3.bgr swizzling (equivalent to dvec3.zyx). /// </summary> public dvec3 bgr => new dvec3(z, y, x); /// <summary> /// Returns dvec3.zyxx swizzling. /// </summary> public dvec4 zyxx => new dvec4(z, y, x, x); /// <summary> /// Returns dvec3.bgrr swizzling (equivalent to dvec3.zyxx). /// </summary> public dvec4 bgrr => new dvec4(z, y, x, x); /// <summary> /// Returns dvec3.zyxy swizzling. /// </summary> public dvec4 zyxy => new dvec4(z, y, x, y); /// <summary> /// Returns dvec3.bgrg swizzling (equivalent to dvec3.zyxy). /// </summary> public dvec4 bgrg => new dvec4(z, y, x, y); /// <summary> /// Returns dvec3.zyxz swizzling. /// </summary> public dvec4 zyxz => new dvec4(z, y, x, z); /// <summary> /// Returns dvec3.bgrb swizzling (equivalent to dvec3.zyxz). /// </summary> public dvec4 bgrb => new dvec4(z, y, x, z); /// <summary> /// Returns dvec3.zyy swizzling. /// </summary> public dvec3 zyy => new dvec3(z, y, y); /// <summary> /// Returns dvec3.bgg swizzling (equivalent to dvec3.zyy). /// </summary> public dvec3 bgg => new dvec3(z, y, y); /// <summary> /// Returns dvec3.zyyx swizzling. /// </summary> public dvec4 zyyx => new dvec4(z, y, y, x); /// <summary> /// Returns dvec3.bggr swizzling (equivalent to dvec3.zyyx). /// </summary> public dvec4 bggr => new dvec4(z, y, y, x); /// <summary> /// Returns dvec3.zyyy swizzling. /// </summary> public dvec4 zyyy => new dvec4(z, y, y, y); /// <summary> /// Returns dvec3.bggg swizzling (equivalent to dvec3.zyyy). /// </summary> public dvec4 bggg => new dvec4(z, y, y, y); /// <summary> /// Returns dvec3.zyyz swizzling. /// </summary> public dvec4 zyyz => new dvec4(z, y, y, z); /// <summary> /// Returns dvec3.bggb swizzling (equivalent to dvec3.zyyz). /// </summary> public dvec4 bggb => new dvec4(z, y, y, z); /// <summary> /// Returns dvec3.zyz swizzling. /// </summary> public dvec3 zyz => new dvec3(z, y, z); /// <summary> /// Returns dvec3.bgb swizzling (equivalent to dvec3.zyz). /// </summary> public dvec3 bgb => new dvec3(z, y, z); /// <summary> /// Returns dvec3.zyzx swizzling. /// </summary> public dvec4 zyzx => new dvec4(z, y, z, x); /// <summary> /// Returns dvec3.bgbr swizzling (equivalent to dvec3.zyzx). /// </summary> public dvec4 bgbr => new dvec4(z, y, z, x); /// <summary> /// Returns dvec3.zyzy swizzling. /// </summary> public dvec4 zyzy => new dvec4(z, y, z, y); /// <summary> /// Returns dvec3.bgbg swizzling (equivalent to dvec3.zyzy). /// </summary> public dvec4 bgbg => new dvec4(z, y, z, y); /// <summary> /// Returns dvec3.zyzz swizzling. /// </summary> public dvec4 zyzz => new dvec4(z, y, z, z); /// <summary> /// Returns dvec3.bgbb swizzling (equivalent to dvec3.zyzz). /// </summary> public dvec4 bgbb => new dvec4(z, y, z, z); /// <summary> /// Returns dvec3.zz swizzling. /// </summary> public dvec2 zz => new dvec2(z, z); /// <summary> /// Returns dvec3.bb swizzling (equivalent to dvec3.zz). /// </summary> public dvec2 bb => new dvec2(z, z); /// <summary> /// Returns dvec3.zzx swizzling. /// </summary> public dvec3 zzx => new dvec3(z, z, x); /// <summary> /// Returns dvec3.bbr swizzling (equivalent to dvec3.zzx). /// </summary> public dvec3 bbr => new dvec3(z, z, x); /// <summary> /// Returns dvec3.zzxx swizzling. /// </summary> public dvec4 zzxx => new dvec4(z, z, x, x); /// <summary> /// Returns dvec3.bbrr swizzling (equivalent to dvec3.zzxx). /// </summary> public dvec4 bbrr => new dvec4(z, z, x, x); /// <summary> /// Returns dvec3.zzxy swizzling. /// </summary> public dvec4 zzxy => new dvec4(z, z, x, y); /// <summary> /// Returns dvec3.bbrg swizzling (equivalent to dvec3.zzxy). /// </summary> public dvec4 bbrg => new dvec4(z, z, x, y); /// <summary> /// Returns dvec3.zzxz swizzling. /// </summary> public dvec4 zzxz => new dvec4(z, z, x, z); /// <summary> /// Returns dvec3.bbrb swizzling (equivalent to dvec3.zzxz). /// </summary> public dvec4 bbrb => new dvec4(z, z, x, z); /// <summary> /// Returns dvec3.zzy swizzling. /// </summary> public dvec3 zzy => new dvec3(z, z, y); /// <summary> /// Returns dvec3.bbg swizzling (equivalent to dvec3.zzy). /// </summary> public dvec3 bbg => new dvec3(z, z, y); /// <summary> /// Returns dvec3.zzyx swizzling. /// </summary> public dvec4 zzyx => new dvec4(z, z, y, x); /// <summary> /// Returns dvec3.bbgr swizzling (equivalent to dvec3.zzyx). /// </summary> public dvec4 bbgr => new dvec4(z, z, y, x); /// <summary> /// Returns dvec3.zzyy swizzling. /// </summary> public dvec4 zzyy => new dvec4(z, z, y, y); /// <summary> /// Returns dvec3.bbgg swizzling (equivalent to dvec3.zzyy). /// </summary> public dvec4 bbgg => new dvec4(z, z, y, y); /// <summary> /// Returns dvec3.zzyz swizzling. /// </summary> public dvec4 zzyz => new dvec4(z, z, y, z); /// <summary> /// Returns dvec3.bbgb swizzling (equivalent to dvec3.zzyz). /// </summary> public dvec4 bbgb => new dvec4(z, z, y, z); /// <summary> /// Returns dvec3.zzz swizzling. /// </summary> public dvec3 zzz => new dvec3(z, z, z); /// <summary> /// Returns dvec3.bbb swizzling (equivalent to dvec3.zzz). /// </summary> public dvec3 bbb => new dvec3(z, z, z); /// <summary> /// Returns dvec3.zzzx swizzling. /// </summary> public dvec4 zzzx => new dvec4(z, z, z, x); /// <summary> /// Returns dvec3.bbbr swizzling (equivalent to dvec3.zzzx). /// </summary> public dvec4 bbbr => new dvec4(z, z, z, x); /// <summary> /// Returns dvec3.zzzy swizzling. /// </summary> public dvec4 zzzy => new dvec4(z, z, z, y); /// <summary> /// Returns dvec3.bbbg swizzling (equivalent to dvec3.zzzy). /// </summary> public dvec4 bbbg => new dvec4(z, z, z, y); /// <summary> /// Returns dvec3.zzzz swizzling. /// </summary> public dvec4 zzzz => new dvec4(z, z, z, z); /// <summary> /// Returns dvec3.bbbb swizzling (equivalent to dvec3.zzzz). /// </summary> public dvec4 bbbb => new dvec4(z, z, z, z); #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 System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using NuGet.ProjectModel; using Microsoft.Extensions.DependencyModel; namespace Microsoft.Tools.ServiceModel.Svcutil { internal class MSBuildProj : IDisposable { private bool _isSaved; private bool _ownsDirectory; private readonly ProjectPropertyResolver _propertyResolver; private XNamespace _msbuildNS; private MSBuildProj() { _propertyResolver = new ProjectPropertyResolver(); } #region Properties // Values in this collection have the effect of properties that are passed to MSBuild in the command line which become global properties. public Dictionary<string, string> GlobalProperties { get; } = new Dictionary<string, string>(); // Netcore projects can specify TargetFramework and/or TargetFrameworks, TargetFramework is always used. // When only TargetFrameworks is specified, the build system builds the project specifying TargetFramework for each entry. private string _targetFramework; public string TargetFramework { get { return _targetFramework; } set { UpdateTargetFramework(value); } } private List<string> _targetFrameworks = new List<string>(); public IEnumerable<string> TargetFrameworks { get { return _targetFrameworks; } } private string _runtimeIdentifier; public string RuntimeIdentifier { get { return _runtimeIdentifier; } set { SetRuntimeIdentifier(value); } } private SortedSet<ProjectDependency> _dependencies = new SortedSet<ProjectDependency>(); public IEnumerable<ProjectDependency> Dependencies { get { return _dependencies; } } public SortedDictionary<string, string> _resolvedProperties = new SortedDictionary<string, string>(); public IEnumerable<KeyValuePair<string, string>> ResolvedProperties { get { return this._resolvedProperties; } } public string FileName { get; private set; } public string DirectoryPath { get; private set; } public string FullPath { get { return Path.Combine(DirectoryPath, FileName); } } public string SdkVersion { get; private set; } private XElement ProjectNode { get; set; } private XElement _projectReferenceGroup; private XElement ProjectReferceGroup { get { if (_projectReferenceGroup == null) { IEnumerable<XElement> refItems = this.ProjectNode.Elements("ProjectReference"); if (refItems == null || refItems.Count() == 0) { // add ref subgroup _projectReferenceGroup = new XElement("ItemGroup"); this.ProjectNode.Add(_projectReferenceGroup); } else { _projectReferenceGroup = refItems.FirstOrDefault().Parent; } } return _projectReferenceGroup; } } private XElement _referenceGroup; private XElement ReferenceGroup { get { if (_referenceGroup == null) { IEnumerable<XElement> refItems = this.ProjectNode.Elements("Reference"); if (refItems == null || refItems.Count() == 0) { // add ref subgroup _referenceGroup = new XElement("ItemGroup"); this.ProjectNode.Add(_referenceGroup); } else { _referenceGroup = refItems.FirstOrDefault().Parent; } } return _referenceGroup; } } #endregion #region Parsing/Settings Methods public static async Task<MSBuildProj> FromPathAsync(string filePath, ILogger logger, CancellationToken cancellationToken) { var project = await ParseAsync(File.ReadAllText(filePath), filePath, logger, cancellationToken).ConfigureAwait(false); project._isSaved = true; return project; } public static async Task<MSBuildProj> ParseAsync(string projectText, string projectFullPath, ILogger logger, CancellationToken cancellationToken) { using (var safeLogger = await SafeLogger.WriteStartOperationAsync(logger, $"Parsing project {Path.GetFileName(projectFullPath)}").ConfigureAwait(false)) { projectFullPath = Path.GetFullPath(projectFullPath); MSBuildProj msbuildProj = new MSBuildProj { FileName = Path.GetFileName(projectFullPath), DirectoryPath = Path.GetDirectoryName(projectFullPath) }; XDocument projDefinition = XDocument.Parse(projectText); var msbuildNS = XNamespace.None; if (projDefinition.Root != null && projDefinition.Root.Name != null) { msbuildNS = projDefinition.Root.Name.Namespace; } msbuildProj._msbuildNS = msbuildNS; msbuildProj.ProjectNode = projDefinition.Element(msbuildNS + "Project"); if (msbuildProj.ProjectNode == null) { throw new Exception(Shared.Resources.ErrorInvalidProjectFormat); } // The user project can declare TargetFramework and/or TargetFrameworks property. If both are provided, TargetFramework wins. // When TargetFrameworks is provided, the project is built for every entry specified in the TargetFramework property. IEnumerable<XElement> targetFrameworkElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "PropertyGroup", "TargetFramework"); if (targetFrameworkElements.Count() > 0) { // If property is specified more than once, MSBuild will resolve it by overwriting it with the last value. var targetFramework = targetFrameworkElements.Last().Value.Trim().ToLowerInvariant(); if (!string.IsNullOrWhiteSpace(targetFramework)) { var tfx = targetFramework.Split('-'); if (tfx.Length > 1 && (tfx[0] == "net5.0" || tfx[0] == "net6.0")) { targetFramework = tfx[0]; } msbuildProj._targetFrameworks.Add(targetFramework); } } if (msbuildProj._targetFrameworks.Count == 0) { // TargetFramework was not provided, check TargetFrameworks property. IEnumerable<XElement> targetFrameworksElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "PropertyGroup", "TargetFrameworks"); if (targetFrameworksElements.Count() > 0) { var targetFrameworks = targetFrameworksElements.Last().Value; foreach (var targetFx in targetFrameworks.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim())) { if (!string.IsNullOrWhiteSpace(targetFx)) { msbuildProj._targetFrameworks.Add(targetFx); } } } } msbuildProj._targetFramework = TargetFrameworkHelper.GetBestFitTargetFramework(msbuildProj._targetFrameworks); // Ensure target framework is valid. FrameworkInfo frameworkInfo = TargetFrameworkHelper.GetValidFrameworkInfo(msbuildProj.TargetFramework); IEnumerable<XElement> runtimeIdentifierElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "PropertyGroup", "RuntimeIdentifier"); if (runtimeIdentifierElements.Count() > 0) { msbuildProj.RuntimeIdentifier = runtimeIdentifierElements.Last().Value.Trim(); } IEnumerable<XElement> packageReferenceElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "ItemGroup", "PackageReference"); foreach (XElement reference in packageReferenceElements) { if(!TryGetItemIdentity(reference, out var packageName)) continue; string version = GetItemValue(reference, "Version"); if (!ProjectDependency.IsValidVersion(version)) { version = ""; } ProjectDependency packageDep = ProjectDependency.FromPackage(packageName, version); msbuildProj._dependencies.Add(packageDep); } IEnumerable<XElement> toolReferenceElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "ItemGroup", "DotNetCliToolReference"); foreach (XElement reference in toolReferenceElements) { if (!TryGetItemIdentity(reference, out var packageName)) continue; string version = GetItemValue(reference, "Version"); ProjectDependency packageDep = ProjectDependency.FromCliTool(packageName, version); msbuildProj._dependencies.Add(packageDep); } IEnumerable<XElement> projectReferenceElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "ItemGroup", "ProjectReference"); foreach (XElement reference in projectReferenceElements) { string projectPath = GetItemValue(reference, "Include", throwIfMissing: true); ProjectDependency projectDep = ProjectDependency.FromProject(projectPath); msbuildProj._dependencies.Add(projectDep); } IEnumerable<XElement> binReferenceElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "ItemGroup", "Reference"); foreach (XElement reference in binReferenceElements) { //Find hint path or path string binReference = GetItemIdentity(reference); if (!Path.IsPathRooted(binReference)) { string fullPath = null; bool fullPathFound = true; XElement hintPath = reference.Element("HintPath"); XElement path = reference.Element("Path"); if (path != null) { fullPath = path.Value; } else if (hintPath != null) { fullPath = hintPath.Value; } else { try { fullPath = new FileInfo(Path.Combine(msbuildProj.DirectoryPath, binReference)).FullName; } catch { } if (fullPath == null || !File.Exists(fullPath)) { fullPathFound = false; // If we're only targeting .NET Core or .NET Standard projects we throw if we can't find the full path to the assembly. if (!TargetFrameworkHelper.ContainsFullFrameworkTarget(msbuildProj._targetFrameworks)) { throw new Exception(string.Format(CultureInfo.CurrentCulture, Shared.Resources.ErrorProjectReferenceMissingFilePathFormat, binReference)); } } } if (fullPathFound) { if (System.IO.Directory.Exists(fullPath)) // IsDir? { fullPath = Path.Combine(fullPath, binReference); } else if (Directory.Exists(Path.Combine(msbuildProj.DirectoryPath, fullPath))) { fullPath = Path.Combine(msbuildProj.DirectoryPath, fullPath, binReference); } binReference = fullPath; } } ProjectDependency projectDep = ProjectDependency.FromAssembly(binReference); msbuildProj._dependencies.Add(projectDep); } // ensure we have a working directory for the ProcessRunner (ProjectPropertyResolver).. if (!Directory.Exists(msbuildProj.DirectoryPath)) { Directory.CreateDirectory(msbuildProj.DirectoryPath); msbuildProj._ownsDirectory = true; } var sdkVersion = await ProjectPropertyResolver.GetSdkVersionAsync(msbuildProj.DirectoryPath, logger, cancellationToken).ConfigureAwait(false); msbuildProj.SdkVersion = sdkVersion ?? string.Empty; return msbuildProj; } } public static async Task<MSBuildProj> DotNetNewAsync(string fullPath, ILogger logger, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); MSBuildProj project = null; bool ownsDir = false; if (fullPath == null) { throw new ArgumentNullException(nameof(fullPath)); } fullPath = Path.GetFullPath(fullPath); string projectName = Path.GetFileNameWithoutExtension(fullPath); string projectExtension = Path.GetExtension(fullPath); string projectDir = Path.GetDirectoryName(fullPath); if (string.IsNullOrEmpty(projectName) || string.CompareOrdinal(projectExtension.ToLowerInvariant(), ".csproj") != 0) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Shared.Resources.ErrorFullPathNotAProjectFilePathFormat, fullPath)); } if (File.Exists(fullPath)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Shared.Resources.ErrorProjectFileAlreadyExistsFormat, fullPath)); } // ensure we have a working directory for the ProcessRunner (ProjectPropertyResolver). if (!Directory.Exists(projectDir)) { Directory.CreateDirectory(projectDir); ownsDir = true; } var sdkVersion = await ProjectPropertyResolver.GetSdkVersionAsync(projectDir, logger, cancellationToken).ConfigureAwait(false); var dotnetNewParams = $"new console {GetNoRestoreParam(sdkVersion)} --force --type project --language C# --output . --name {projectName}"; await ProcessRunner.RunAsync("dotnet", dotnetNewParams, projectDir, logger, cancellationToken).ConfigureAwait(false); project = await ParseAsync(File.ReadAllText(fullPath), fullPath, logger, cancellationToken).ConfigureAwait(false); project._ownsDirectory = ownsDir; project.SdkVersion = sdkVersion ?? string.Empty; project._isSaved = true; return project; } private static IEnumerable<XElement> GetGroupValues(XElement projectElement, string group, bool createOnMissing = false) { // XElement.Elements() always returns a collection, no need to check for null. IEnumerable<XElement> groups = projectElement.Elements(group); if (createOnMissing && groups.Count() == 0) { // add a property group XElement propertyGroup = new XElement(group); projectElement.Add(propertyGroup); return new XElement[] { propertyGroup }; } return groups; } //Used for both references and properties private static IEnumerable<XElement> GetSubGroupValues(XElement projectElement, XNamespace msbuildNS, string group, string subGroupName) { IEnumerable<XElement> groups = GetGroupValues(projectElement, group); IEnumerable<XElement> subGroupValues = groups.Elements(msbuildNS + subGroupName); return subGroupValues; } private static string GetItemValue(XElement reference, string itemName, bool throwIfMissing = false) { // XElement.Attributes() alwasy returns a collection, no need to check for null. var itemAttribue = reference.Attributes().FirstOrDefault(item => item.Name == itemName); if (itemAttribue != null) { return itemAttribue.Value; } XElement itemNameElement = null; itemNameElement = reference.Elements().FirstOrDefault(item => item.Name == itemName); if (itemNameElement != null) { return itemNameElement.Value; } if (throwIfMissing) { throw new Exception(Shared.Resources.ErrorInvalidProjectFormat); } return null; } public static bool TryGetItemIdentity(XElement itemName, out string itemIdentity) { var itemAttribute = itemName.Attributes().FirstOrDefault(item => item.Name == "Include"); if (itemAttribute != null) { itemIdentity = itemAttribute.Value; return true; } itemIdentity = default; return false; } private static string GetItemIdentity(XElement itemName) { var itemAttribute = itemName.Attributes().FirstOrDefault(item => item.Name == "Include"); if (itemAttribute != null) { return itemAttribute.Value; } throw new Exception(Shared.Resources.ErrorInvalidProjectFormat); } public bool AddDependency(ProjectDependency dependency) { // a nuget package can contain multiple assemblies, we need to filter package references so we don't add dups. bool addDependency = !_dependencies.Any(d => { switch (d.DependencyType) { case ProjectDependencyType.Package: case ProjectDependencyType.Tool: return d.Name == dependency.Name; default: if (d.FullPath == null && dependency.FullPath == null) { goto case ProjectDependencyType.Package; } return d.FullPath == dependency.FullPath; } }); if (addDependency) { switch (dependency.DependencyType) { case ProjectDependencyType.Project: this.ProjectReferceGroup.Add(new XElement("ProjectReference", new XAttribute("Include", dependency.FullPath))); break; case ProjectDependencyType.Binary: this.ReferenceGroup.Add(new XElement("Reference", new XAttribute("Include", dependency.AssemblyName), new XElement("HintPath", dependency.FullPath))); break; case ProjectDependencyType.Package: this.ReferenceGroup.Add(new XElement("PackageReference", new XAttribute("Include", dependency.Name), new XAttribute("Version", dependency.Version))); break; case ProjectDependencyType.Tool: this.ReferenceGroup.Add(new XElement("DotNetCliToolReference", new XAttribute("Include", dependency.Name), new XAttribute("Version", dependency.Version))); break; } _dependencies.Add(dependency); _isSaved = false; } return addDependency; } // Sets the property value in a PropertyGroup. Returns true if the value was changed, and false if it was already set to that value. private bool SetPropertyValue(string propertyName, string value) { XElement element = new XElement(propertyName, null); IEnumerable<XElement> existingElements = GetSubGroupValues(this.ProjectNode, _msbuildNS, "PropertyGroup", propertyName); if (existingElements.Count() > 0) { element = existingElements.Last(); } else { IEnumerable<XElement> propertyGroupItems = GetGroupValues(this.ProjectNode, "PropertyGroup", createOnMissing: true); XElement propertyGroup = propertyGroupItems.First(); propertyGroup.Add(element); } if (element.Value != value) { element.SetValue(value); return true; } return false; } private void SetRuntimeIdentifier(string runtimeIdentifier) { if (this.RuntimeIdentifier != runtimeIdentifier && !string.IsNullOrWhiteSpace(runtimeIdentifier)) { if (SetPropertyValue("RuntimeIdentifier", runtimeIdentifier)) { _runtimeIdentifier = runtimeIdentifier; _isSaved = false; } } } public void ClearWarningsAsErrors() { // Add an empty WarningsAsErrors element to clear the list, and treat them as warnings. SetPropertyValue("WarningsAsErrors", string.Empty); } private void UpdateTargetFramework(string targetFramework) { if (_targetFramework != targetFramework && !string.IsNullOrWhiteSpace(targetFramework)) { // validate framework TargetFrameworkHelper.GetValidFrameworkInfo(targetFramework); if (!_targetFrameworks.Contains(targetFramework)) { // replace values (if existing). if (_targetFramework != null && _targetFrameworks.Contains(_targetFramework)) { _targetFrameworks.Remove(_targetFramework); } _targetFrameworks.Add(targetFramework); } IEnumerable<XElement> targetFrameworkElements = GetSubGroupValues(this.ProjectNode, _msbuildNS, "PropertyGroup", "TargetFramework"); if (targetFrameworkElements.Count() > 0) { var targetFrameworkNode = targetFrameworkElements.Last(); targetFrameworkNode.SetValue(targetFramework); } // TargetFramework was not provided, check TargetFrameworks property. IEnumerable<XElement> targetFrameworksElements = GetSubGroupValues(this.ProjectNode, _msbuildNS, "PropertyGroup", "TargetFrameworks"); if (targetFrameworksElements.Count() > 0) { var targetFrameworksNode = targetFrameworksElements.Last(); targetFrameworksNode.SetValue(_targetFrameworks.Aggregate((tfs, tf) => $"{tfs};{tf}")); } _targetFramework = targetFramework; _isSaved = false; } } #endregion #region Operation Methods public async Task SaveAsync(bool force, ILogger logger, CancellationToken cancellationToken) { _isSaved &= !force; await SaveAsync(logger, cancellationToken).ConfigureAwait(false); } public async Task SaveAsync(ILogger logger, CancellationToken cancellationToken) { ThrowOnDisposed(); cancellationToken.ThrowIfCancellationRequested(); if (!_isSaved) { using (await SafeLogger.WriteStartOperationAsync(logger, $"Saving project file: \"{this.FullPath}\"").ConfigureAwait(false)) { if (!Directory.Exists(this.DirectoryPath)) { Directory.CreateDirectory(this.DirectoryPath); _ownsDirectory = true; } using (StreamWriter writer = File.CreateText(this.FullPath)) { await AsyncHelper.RunAsync(() => ProjectNode.Save(writer), cancellationToken).ConfigureAwait(false); } _isSaved = true; } } } public async Task<ProcessRunner.ProcessResult> RestoreAsync(ILogger logger, CancellationToken cancellationToken) { ThrowOnDisposed(); if (!_isSaved) { await this.SaveAsync(logger, cancellationToken).ConfigureAwait(false); } var restoreParams = "restore --ignore-failed-sources" + (string.IsNullOrWhiteSpace(this.RuntimeIdentifier) ? "" : (" -r " + this.RuntimeIdentifier)); // Restore no-dependencies first to workaround NuGet issue https://github.com/NuGet/Home/issues/4979 await ProcessRunner.TryRunAsync("dotnet", restoreParams + " --no-dependencies", this.DirectoryPath, logger, cancellationToken).ConfigureAwait(false); var result = await ProcessRunner.TryRunAsync("dotnet", restoreParams, this.DirectoryPath, logger, cancellationToken).ConfigureAwait(false); return result; } /// <summary> /// Builds the project and optionally restores it before building. If restore is false the project is not saved automatically. /// </summary> /// <returns></returns> public async Task<ProcessRunner.ProcessResult> BuildAsync(bool restore, ILogger logger, CancellationToken cancellationToken) { if (restore) { await this.RestoreAsync(logger, cancellationToken).ConfigureAwait(false); } return await BuildAsync(logger, cancellationToken).ConfigureAwait(false); } public async Task<ProcessRunner.ProcessResult> BuildAsync(ILogger logger, CancellationToken cancellationToken) { ThrowOnDisposed(); string buildParams = $"build {GetNoRestoreParam(this.SdkVersion)}"; return await ProcessRunner.RunAsync("dotnet", buildParams, this.DirectoryPath, logger, cancellationToken).ConfigureAwait(false); } #endregion #region Helper Methods public async Task<IEnumerable<ProjectDependency>> ResolveProjectReferencesAsync(IEnumerable<ProjectDependency> excludeDependencies, ILogger logger, CancellationToken cancellationToken) { ThrowOnDisposed(); IEnumerable<ProjectDependency> dependencies = null; if (excludeDependencies == null) { excludeDependencies = new List<ProjectDependency>(); } using (var safeLogger = await SafeLogger.WriteStartOperationAsync(logger, "Resolving project references ...").ConfigureAwait(false)) { if (_targetFrameworks.Count == 1 && TargetFrameworkHelper.IsSupportedFramework(this.TargetFramework, out var frameworkInfo) && frameworkInfo.IsDnx) { await this.RestoreAsync(logger, cancellationToken).ConfigureAwait(false); var packageReferences = await ResolvePackageReferencesAsync(logger, cancellationToken).ConfigureAwait(false); var assemblyReferences = await ResolveAssemblyReferencesAsync(logger, cancellationToken).ConfigureAwait(false); dependencies = packageReferences.Union(assemblyReferences).Except(excludeDependencies); } else { await safeLogger.WriteWarningAsync(Shared.Resources.WarningMultiFxOrNoSupportedDnxVersion, logToUI: true).ConfigureAwait(false); dependencies = new List<ProjectDependency>(); } await safeLogger.WriteMessageAsync($"Resolved project reference count: {dependencies.Count()}", logToUI: false).ConfigureAwait(false); } return dependencies; } private async Task<List<ProjectDependency>> ResolvePackageReferencesAsync(ILogger logger, CancellationToken cancellationToken) { ThrowOnDisposed(); cancellationToken.ThrowIfCancellationRequested(); var packageDependencies = new List<ProjectDependency>(); using (var safeLogger = await SafeLogger.WriteStartOperationAsync(logger, "Resolving package references ...").ConfigureAwait(false)) { await AsyncHelper.RunAsync(async () => { try { var assetsFile = new FileInfo(Path.Combine(this.DirectoryPath, "obj", "project.assets.json")).FullName; if (File.Exists(assetsFile)) { LockFile lockFile = LockFileUtilities.GetLockFile(assetsFile, logger as NuGet.Common.ILogger); if (lockFile != null) { if (lockFile.Targets.Count == 1) { foreach (var lib in lockFile.Targets[0].Libraries) { bool isPackage = StringComparer.OrdinalIgnoreCase.Compare(lib.Type, "package") == 0; if (isPackage) { foreach (var compiletimeAssembly in lib.CompileTimeAssemblies) { if (Path.GetExtension(compiletimeAssembly.Path) == ".dll") { var dependency = ProjectDependency.FromPackage(Path.GetFileNameWithoutExtension(compiletimeAssembly.Path), lib.Name, lib.Version.ToNormalizedString()); var itemIdx = packageDependencies.IndexOf(dependency); if (itemIdx == -1) { packageDependencies.Add(dependency); } else if (dependency.IsFramework) { // packages can be described individually and/or as part of a platform metapackage in the lock file; for instance: Microsoft.CSharp is a package that is part of Microsoft.NetCore. packageDependencies[itemIdx] = dependency; } } } } } packageDependencies.Sort(); } else { await safeLogger.WriteWarningAsync(Shared.Resources.WarningMultiFxOrNoSupportedDnxVersion, logToUI: true).ConfigureAwait(false); } } else { await safeLogger.WriteWarningAsync(Shared.Resources.WarningCannotResolveProjectReferences, logToUI: true).ConfigureAwait(false); } } } catch (Exception ex) { if (Utils.IsFatalOrUnexpected(ex)) throw; await safeLogger.WriteWarningAsync(ex.Message, logToUI: false).ConfigureAwait(false); } }, cancellationToken).ConfigureAwait(false); await safeLogger.WriteMessageAsync($"Package reference count: {packageDependencies.Count}", logToUI: false).ConfigureAwait(false); } return packageDependencies; } private async Task<List<ProjectDependency>> ResolveAssemblyReferencesAsync(ILogger logger, CancellationToken cancellationToken) { ThrowOnDisposed(); cancellationToken.ThrowIfCancellationRequested(); var assemblyDependencies = new List<ProjectDependency>(); using (var safeLogger = await SafeLogger.WriteStartOperationAsync(logger, $"Resolving assembly references for {this.TargetFramework} target framework ...").ConfigureAwait(false)) { await ResolveProperyValuesAsync(new string[] { "OutputPath", "TargetPath" }, logger, cancellationToken).ConfigureAwait(false); var outputPath = this._resolvedProperties["OutputPath"]; if (!Path.IsPathRooted(outputPath)) { outputPath = Path.Combine(this.DirectoryPath, outputPath.Trim(new char[] { '\"' })); } var depsFile = this.GlobalProperties.TryGetValue("Configuration", out var activeConfiguration) && !string.IsNullOrWhiteSpace(activeConfiguration) ? Path.Combine(outputPath, $"{Path.GetFileNameWithoutExtension(this.FileName)}.deps.json") : await ResolveDepsFilePathFromBuildConfigAsync(outputPath, logger, cancellationToken).ConfigureAwait(false); if (File.Exists(depsFile)) { await AsyncHelper.RunAsync(async () => { try { DependencyContext depContext = null; using (var stream = File.OpenRead(depsFile)) { depContext = new DependencyContextJsonReader().Read(stream); } var targetLib = Path.GetFileName(this._resolvedProperties["TargetPath"].Trim('\"')); if (string.IsNullOrEmpty(targetLib)) { targetLib = $"{Path.ChangeExtension(this.FileName, ".dll")}"; } foreach (var rtLib in depContext.RuntimeLibraries.Where(l => l.NativeLibraryGroups.Count == 0)) { ProjectDependency dependency = null; switch (rtLib.Type) { case "project": case "reference": foreach (var assemblyGroup in rtLib.RuntimeAssemblyGroups) { foreach (var assetPath in assemblyGroup.AssetPaths) { if (!Path.GetFileName(assetPath).Equals(targetLib, RuntimeEnvironmentHelper.FileStringComparison)) { dependency = ProjectDependency.FromAssembly(Path.Combine(outputPath, assetPath)); if (File.Exists(dependency.FullPath) && !assemblyDependencies.Contains(dependency)) { assemblyDependencies.Add(dependency); } } } } break; //case "package": default: break; } } } catch (Exception ex) { if (Utils.IsFatalOrUnexpected(ex)) throw; await safeLogger.WriteWarningAsync(ex.Message, logToUI: false).ConfigureAwait(false); } }, cancellationToken).ConfigureAwait(false); assemblyDependencies.Sort(); } else { await safeLogger.WriteWarningAsync("Deps file not found (project not built), unable to resolve assembly/project dependencies!", logToUI: false).ConfigureAwait(false); } await safeLogger.WriteMessageAsync($"Assembly reference count: {assemblyDependencies.Count}", logToUI: false).ConfigureAwait(false); } return assemblyDependencies; } public async Task<IEnumerable<KeyValuePair<string, string>>> ResolveProperyValuesAsync(IEnumerable<string> propertyNames, ILogger logger, CancellationToken cancellationToken) { ThrowOnDisposed(); cancellationToken.ThrowIfCancellationRequested(); if (propertyNames == null) { throw new ArgumentNullException(nameof(propertyNames)); } if (!this.GlobalProperties.Any(p => p.Key == "TargetFramework")) { this.GlobalProperties["TargetFramework"] = this.TargetFramework; } if (!this.GlobalProperties.Any(p => p.Key == "SdkVersion")) { this.GlobalProperties["SdkVersion"] = this.SdkVersion; } if (!propertyNames.All(p => this._resolvedProperties.Keys.Contains(p))) { var propertyTable = this._resolvedProperties.Where(p => propertyNames.Contains(p.Key)); if (propertyTable.Count() != propertyNames.Count()) { propertyTable = await _propertyResolver.EvaluateProjectPropertiesAsync(this.FullPath, this.TargetFramework, propertyNames, this.GlobalProperties, logger, cancellationToken).ConfigureAwait(false); foreach (var entry in propertyTable) { this._resolvedProperties[entry.Key] = entry.Value; } } } return this._resolvedProperties.Where(p => propertyNames.Contains(p.Key)); } private async Task<string> ResolveDepsFilePathFromBuildConfigAsync(string outputPath, ILogger logger, CancellationToken cancellationToken) { // Since we are resolving the deps file path it means the passed in outputPath is built using the default build // configuration (debug/release). We need to resolve the configuration by looking at the most recent build in the // output path. The output should look something like 'bin\Debug\netcoreapp1.0\HelloSvcutil.deps.json' using (var safeLogger = await SafeLogger.WriteStartOperationAsync(logger, $"Resolving deps.json file ...").ConfigureAwait(false)) { var fileName = $"{Path.GetFileNameWithoutExtension(this.FileName)}.deps.json"; var depsFile = string.Empty; // find the most recent deps.json files under the project's bin folder built for the project's target framework. var binFolder = await PathHelper.TryFindFolderAsync("bin", outputPath, logger, cancellationToken).ConfigureAwait(false); if (Directory.Exists(binFolder)) { var depsFiles = Directory.GetFiles(binFolder, "*", SearchOption.AllDirectories) .Where(d => Path.GetFileName(d).Equals(fileName, RuntimeEnvironmentHelper.FileStringComparison)) .Where(f => PathHelper.GetFolderName(Path.GetDirectoryName(f)) == this.TargetFramework) .Select(f => new FileInfo(f)) .OrderByDescending(f => f.CreationTimeUtc); depsFile = depsFiles.FirstOrDefault()?.FullName; } await safeLogger.WriteMessageAsync($"deps file: {depsFile}", logToUI: false).ConfigureAwait(false); return depsFile; } } public override string ToString() { return this.FullPath; } private void ThrowOnDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(MSBuildProj)); } } private static string GetNoRestoreParam(string sdkVersion) { if (string.IsNullOrEmpty(sdkVersion) || sdkVersion.StartsWith("1", StringComparison.OrdinalIgnoreCase)) { return string.Empty; } return "--no-restore"; } #endregion #region IDisposable Support private bool _disposed = false; protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { try { if (_ownsDirectory && Directory.Exists(this.DirectoryPath) && !DebugUtils.KeepTemporaryDirs) { try { Directory.Delete(this.DirectoryPath, recursive: true); } catch { } } } catch { } } _disposed = true; } } public void Dispose() { Dispose(true); } #endregion } }
//--------------------------------------------------------------------------- // // <copyright file="NotifyCollectionChangedEventArgs.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: NotifyCollectionChanged event arguments // // Specs: http://avalon/connecteddata/Specs/INotifyCollectionChanged.mht // //--------------------------------------------------------------------------- // Adapted for Unity #if !NETFX_CORE namespace System.Collections.Specialized { /// <summary> /// This enum describes the action that caused a CollectionChanged event. /// </summary> public enum NotifyCollectionChangedAction { /// <summary> One or more items were added to the collection. </summary> Add, /// <summary> One or more items were removed from the collection. </summary> Remove, /// <summary> One or more items were replaced in the collection. </summary> Replace, /// <summary> One or more items were moved within the collection. </summary> Move, /// <summary> The contents of the collection changed dramatically. </summary> Reset, } /// <summary> /// Arguments for the CollectionChanged event. /// A collection that supports INotifyCollectionChangedThis raises this event /// whenever an item is added or removed, or when the contents of the collection /// changes dramatically. /// </summary> public class NotifyCollectionChangedEventArgs : EventArgs { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a reset change. /// </summary> /// <param name="action">The action that caused the event (must be Reset).</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action) { if (action != NotifyCollectionChangedAction.Reset) throw new ArgumentException("This constructor can only be used with the Reset action.", "action"); InitializeAdd(action, null, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item change. /// </summary> /// <param name="action">The action that caused the event; can only be Reset, Add or Remove action.</param> /// <param name="changedItem">The item affected by the change.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException("This constructor can only be used with the Reset, Add, or Remove actions.", "action"); if (action == NotifyCollectionChangedAction.Reset) { if (changedItem != null) throw new ArgumentException("This constructor can only be used with the Reset action if changedItem is null", "action"); InitializeAdd(action, null, -1); } else { InitializeAddOrRemove(action, new object[] { changedItem }, -1); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item change. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItem">The item affected by the change.</param> /// <param name="index">The index where the change occurred.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem, int index) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException("This constructor can only be used with the Reset, Add, or Remove actions.", "action"); if (action == NotifyCollectionChangedAction.Reset) { if (changedItem != null) throw new ArgumentException("This constructor can only be used with the Reset action if changedItem is null", "action"); if (index != -1) throw new ArgumentException("This constructor can only be used with the Reset action if index is -1", "action"); InitializeAdd(action, null, -1); } else { InitializeAddOrRemove(action, new object[] { changedItem }, index); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item change. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException("This constructor can only be used with the Reset, Add, or Remove actions.", "action"); if (action == NotifyCollectionChangedAction.Reset) { if (changedItems != null) throw new ArgumentException("This constructor can only be used with the Reset action if changedItem is null", "action"); InitializeAdd(action, null, -1); } else { if (changedItems == null) throw new ArgumentNullException("changedItems"); InitializeAddOrRemove(action, changedItems, -1); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item change (or a reset). /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> /// <param name="startingIndex">The index where the change occurred.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems, int startingIndex) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException("This constructor can only be used with the Reset, Add, or Remove actions.", "action"); if (action == NotifyCollectionChangedAction.Reset) { if (changedItems != null) throw new ArgumentException("This constructor can only be used with the Reset action if changedItem is null", "action"); if (startingIndex != -1) throw new ArgumentException("This constructor can only be used with the Reset action if index is -1", "action"); InitializeAdd(action, null, -1); } else { if (changedItems == null) throw new ArgumentNullException("changedItems"); if (startingIndex < -1) throw new ArgumentException("The value of index must be -1 or greater.", "startingIndex"); InitializeAddOrRemove(action, changedItems, startingIndex); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItem">The new item replacing the original item.</param> /// <param name="oldItem">The original item that is replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object newItem, object oldItem) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException("This constructor can only be used with the Replace action.", "action"); InitializeMoveOrReplace(action, new object[] { newItem }, new object[] { oldItem }, -1, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItem">The new item replacing the original item.</param> /// <param name="oldItem">The original item that is replaced.</param> /// <param name="index">The index of the item being replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object newItem, object oldItem, int index) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException("This constructor can only be used with the Replace action.", "action"); int oldStartingIndex = index; InitializeMoveOrReplace(action, new object[] { newItem }, new object[] { oldItem }, index, oldStartingIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItems">The new items replacing the original items.</param> /// <param name="oldItems">The original items that are replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException("This constructor can only be used with the Replace action.", "action"); if (newItems == null) throw new ArgumentNullException("newItems"); if (oldItems == null) throw new ArgumentNullException("oldItems"); InitializeMoveOrReplace(action, newItems, oldItems, -1, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItems">The new items replacing the original items.</param> /// <param name="oldItems">The original items that are replaced.</param> /// <param name="startingIndex">The starting index of the items being replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException("This constructor can only be used with the Replace action.", "action"); if (newItems == null) throw new ArgumentNullException("newItems"); if (oldItems == null) throw new ArgumentNullException("oldItems"); InitializeMoveOrReplace(action, newItems, oldItems, startingIndex, startingIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Move event. /// </summary> /// <param name="action">Can only be a Move action.</param> /// <param name="changedItem">The item affected by the change.</param> /// <param name="index">The new index for the changed item.</param> /// <param name="oldIndex">The old index for the changed item.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem, int index, int oldIndex) { if (action != NotifyCollectionChangedAction.Move) throw new ArgumentException("This constructor can only be used with the Move action.", "action"); if (index < 0) throw new ArgumentException("The value of index must be -1 or greater.", "index"); object[] changedItems = new object[] { changedItem }; InitializeMoveOrReplace(action, changedItems, changedItems, index, oldIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Move event. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> /// <param name="index">The new index for the changed items.</param> /// <param name="oldIndex">The old index for the changed items.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems, int index, int oldIndex) { if (action != NotifyCollectionChangedAction.Move) throw new ArgumentException("This constructor can only be used with the Move action.", "action"); if (index < 0) throw new ArgumentException("The value of index must be -1 or greater.", "index"); InitializeMoveOrReplace(action, changedItems, changedItems, index, oldIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs with given fields (no validation). Used by WinRT marshaling. /// </summary> internal NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int newIndex, int oldIndex) { _action = action; _newItems = (newItems == null) ? null : ArrayList.ReadOnly(newItems); _oldItems = (oldItems == null) ? null : ArrayList.ReadOnly(oldItems); _newStartingIndex = newIndex; _oldStartingIndex = oldIndex; } private void InitializeAddOrRemove(NotifyCollectionChangedAction action, IList changedItems, int startingIndex) { if (action == NotifyCollectionChangedAction.Add) InitializeAdd(action, changedItems, startingIndex); else if (action == NotifyCollectionChangedAction.Remove) InitializeRemove(action, changedItems, startingIndex); else throw new ArgumentException("This method must be used with the Add or Remove action.", "action"); } private void InitializeAdd(NotifyCollectionChangedAction action, IList newItems, int newStartingIndex) { _action = action; _newItems = (newItems == null) ? null : ArrayList.ReadOnly(newItems); _newStartingIndex = newStartingIndex; } private void InitializeRemove(NotifyCollectionChangedAction action, IList oldItems, int oldStartingIndex) { _action = action; _oldItems = (oldItems == null) ? null : ArrayList.ReadOnly(oldItems); _oldStartingIndex = oldStartingIndex; } private void InitializeMoveOrReplace(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex, int oldStartingIndex) { InitializeAdd(action, newItems, startingIndex); InitializeRemove(action, oldItems, oldStartingIndex); } //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ /// <summary> /// The action that caused the event. /// </summary> public NotifyCollectionChangedAction Action { get { return _action; } } /// <summary> /// The items affected by the change. /// </summary> public IList NewItems { get { return _newItems; } } /// <summary> /// The old items affected by the change (for Replace events). /// </summary> public IList OldItems { get { return _oldItems; } } /// <summary> /// The index where the change occurred. /// </summary> public int NewStartingIndex { get { return _newStartingIndex; } } /// <summary> /// The old index where the change occurred (for Move events). /// </summary> public int OldStartingIndex { get { return _oldStartingIndex; } } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ private NotifyCollectionChangedAction _action; private IList _newItems, _oldItems; private int _newStartingIndex = -1; private int _oldStartingIndex = -1; } /// <summary> /// The delegate to use for handlers that receive the CollectionChanged event. /// </summary> public delegate void NotifyCollectionChangedEventHandler(object sender, NotifyCollectionChangedEventArgs e); } #endif
using System; using NUnit.Framework; using ObjParser; namespace ObjParser_Tests { [TestFixture] public class LoadObjTests { private Obj obj; private Mtl mtl; [SetUp] public void SetUp() { obj = new Obj(); mtl = new Mtl(); } #region Vertex [Test] public void LoadObj_OneVert_OneVertCount() { // Arrange var objFile = new[] { "v 0.0 0.0 0.0" }; // Act obj.LoadObj(objFile); // Assert Assert.IsTrue(obj.VertexList.Count == 1); } [Test] public void LoadOBj_TwoVerts_TwoVertCount() { // Arrange var objFile = new[] { "v 0.0 0.0 0.0", "v 1.0 1.0 1.0" }; // Act obj.LoadObj(objFile); // Assert Assert.IsTrue(obj.VertexList.Count == 2); } [Test] public void LoadObj_EmptyObj_EmptyObjNoVertsNoFaces() { // Arrange var objFile = new string[] {}; // Act obj.LoadObj(objFile); // Assert Assert.IsTrue(obj.VertexList.Count == 0); Assert.IsTrue(obj.FaceList.Count == 0); } [Test] public void LoadObj_NoVertPositions_ThrowsArgumentException() { // Arrange var objFile = new[] { "v 0.0 0.0 0.0", "v" }; // Act // Assert Assert.That(() => obj.LoadObj(objFile), Throws.TypeOf<ArgumentException>()); } [Test] public void LoadObj_CommaSeperatedVertPositions_ThrowsArgumentException() { // Arrange var objFile = new[] { // Valid "v 0, 0, 0,", // Invalid "v 0.1, 0.1, 0.2,", "v 0.1, 0.1, 0.3,", "v 0.1, 0.1, 0.4," }; // Act // Assert Assert.That(() => obj.LoadObj(objFile), Throws.TypeOf<ArgumentException>()); } [Test] public void LoadObj_LettersInsteadOfPositions_ThrowsArgumentException() { // Arrange var objFile = new[] { "v a b c" }; // Act // Assert Assert.That(() => obj.LoadObj(objFile), Throws.TypeOf<ArgumentException>()); } #endregion #region TextureVertex [Test] public void LoadObj_OneTextureVert_OneTextureVertCount() { // Arrange var objFile = new[] { "vt 0.0 0.0" }; // Act obj.LoadObj(objFile); // Assert Assert.IsTrue(obj.TextureList.Count == 1); } [Test] public void LoadOBj_TwoTextureVerts_TwoTextureVertCount() { // Arrange var objFile = new[] { "vt 0.0 0.0", "vt 1.0 1.0" }; // Act obj.LoadObj(objFile); // Assert Assert.IsTrue(obj.TextureList.Count == 2); } [Test] public void LoadOBj_TwoTextureVerts_TwoTextureVertValues() { // Arrange var objFile = new[] { "vt 5.0711 0.0003", "vt 5.4612 1.0000" }; // Act obj.LoadObj(objFile); // Assert Assert.IsTrue(obj.TextureList.Count == 2); Assert.AreEqual(5.0711d, obj.TextureList[0].X); Assert.AreEqual(0.0003d, obj.TextureList[0].Y); Assert.AreEqual(5.4612d, obj.TextureList[1].X); Assert.AreEqual(1.0000d, obj.TextureList[1].Y); } #endregion #region Mtl [Test] public void Mtl_LoadMtl_TwoMaterials() { // Arrange var mtlFile = new[] { "newmtl Material", "Ns 96.078431", "Ka 1.000000 1.000000 1.000000", "Kd 0.630388 0.620861 0.640000", "Ks 0.500000 0.500000 0.500000", "Ke 0.000000 0.000000 0.000000", "Tf 0.000000 0.000000 0.000000", "Ni 1.000000", "d 1.000000", "illum 2", "", "newmtl Material.001", "Ns 96.078431", "Ka 1.000000 1.000000 1.000000", "Kd 0.640000 0.026578 0.014364", "Ks 0.500000 0.500000 0.500000", "Ke 0.000000 0.000000 0.000000", "Ni 1.000000", "d 1.000000", "illum 2" }; // Act mtl.LoadMtl(mtlFile); // Assert Assert.AreEqual(2, mtl.MaterialList.Count); ObjParser.Types.Material first = mtl.MaterialList[0]; Assert.AreEqual("Material", first.Name); Assert.AreEqual(96.078431f, first.SpecularExponent); Assert.AreEqual(1.0f, first.AmbientReflectivity.r); Assert.AreEqual(1.0f, first.AmbientReflectivity.g); Assert.AreEqual(1.0f, first.AmbientReflectivity.b); Assert.AreEqual(0.630388f, first.DiffuseReflectivity.r); Assert.AreEqual(0.620861f, first.DiffuseReflectivity.g); Assert.AreEqual(0.640000f, first.DiffuseReflectivity.b); Assert.AreEqual(0.5f, first.SpecularReflectivity.r); Assert.AreEqual(0.5f, first.SpecularReflectivity.g); Assert.AreEqual(0.5f, first.SpecularReflectivity.b); Assert.AreEqual(0.0f, first.EmissiveCoefficient.r); Assert.AreEqual(0.0f, first.EmissiveCoefficient.g); Assert.AreEqual(0.0f, first.EmissiveCoefficient.b); Assert.AreEqual(0.0f, first.TransmissionFilter.r); Assert.AreEqual(0.0f, first.TransmissionFilter.g); Assert.AreEqual(0.0f, first.TransmissionFilter.b); Assert.AreEqual(1.0f, first.OpticalDensity); Assert.AreEqual(1.0f, first.Dissolve); Assert.AreEqual(2, first.IlluminationModel); ObjParser.Types.Material second = mtl.MaterialList[1]; Assert.AreEqual("Material.001", second.Name); Assert.AreEqual(96.078431f, second.SpecularExponent); } #endregion #region Face [Test] public void LoadObj_FourVertsSingleFace_FourVertsOneFaceCount() { // Arrange var objFile = new[] { "v -0.500000 -0.500000 0.500000", "v 0.500000 -0.500000 0.500000", "v -0.500000 0.500000 0.500000", "v 0.500000 0.500000 0.500000", "f 1/1/1 2/2/1 3/3/1" }; // Act obj.LoadObj(objFile); // Assert Assert.IsTrue(obj.VertexList.Count == 4); Assert.IsTrue(obj.FaceList.Count == 1); Assert.IsNull(obj.FaceList[0].UseMtl); } [Test] public void LoadObj_FourVertsThreeFace_TwoMaterialsCount() { // Arrange var objFile = new[] { "v -0.500000 -0.500000 0.500000", "v 0.500000 -0.500000 0.500000", "v -0.500000 0.500000 0.500000", "v 0.500000 0.500000 0.500000", "usemtl Material", "f 1/1/1 2/2/1 3/3/1", "usemtl Material.001", "f 1/1/1 2/2/1 3/3/1", "f 1/1/1 2/2/1 3/3/1" }; // Act obj.LoadObj(objFile); // Assert Assert.IsTrue(obj.VertexList.Count == 4); Assert.IsTrue(obj.FaceList.Count == 3); Assert.AreEqual(obj.FaceList[0].UseMtl, "Material"); Assert.AreEqual(obj.FaceList[1].UseMtl, "Material.001"); Assert.AreEqual(obj.FaceList[2].UseMtl, "Material.001"); } [Test] public void LoadObj_FourVertsTwoFace_OneMaterialCount() { // Arrange var objFile = new[] { "v -0.500000 -0.500000 0.500000", "v 0.500000 -0.500000 0.500000", "v -0.500000 0.500000 0.500000", "v 0.500000 0.500000 0.500000", "f 1/1/1 2/2/1 3/3/1", "usemtl Material", "f 1/1/1 2/2/1 3/3/1" }; // Act obj.LoadObj(objFile); // Assert Assert.IsTrue(obj.VertexList.Count == 4); Assert.IsTrue(obj.FaceList.Count == 2); Assert.IsNull(obj.FaceList[0].UseMtl); Assert.AreEqual(obj.FaceList[1].UseMtl, "Material"); } [Test] public void LoadObj_FourVertsSingleFaceNoTextureVerts_FourVertsOneFaceCount() { // Arrange var objFile = new[] { "v -0.500000 -0.500000 0.500000", "v 0.500000 -0.500000 0.500000", "v -0.500000 0.500000 0.500000", "v 0.500000 0.500000 0.500000", "f 1//1 2//1 3//1" }; // Act obj.LoadObj(objFile); // Assert Assert.IsTrue(obj.VertexList.Count == 4); Assert.IsTrue(obj.FaceList.Count == 1); } #endregion } }
namespace Azure.Messaging.EventHubs { public partial class EventData { public EventData(System.BinaryData eventBody) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] protected EventData(System.BinaryData eventBody, System.Collections.Generic.IDictionary<string, object> properties = null, System.Collections.Generic.IReadOnlyDictionary<string, object> systemProperties = null, long sequenceNumber = (long)-9223372036854775808, long offset = (long)-9223372036854775808, System.DateTimeOffset enqueuedTime = default(System.DateTimeOffset), string partitionKey = null) { } public EventData(System.ReadOnlyMemory<byte> eventBody) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] protected EventData(System.ReadOnlyMemory<byte> eventBody, System.Collections.Generic.IDictionary<string, object> properties = null, System.Collections.Generic.IReadOnlyDictionary<string, object> systemProperties = null, long sequenceNumber = (long)-9223372036854775808, long offset = (long)-9223372036854775808, System.DateTimeOffset enqueuedTime = default(System.DateTimeOffset), string partitionKey = null) { } public EventData(string eventBody) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public System.ReadOnlyMemory<byte> Body { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public System.IO.Stream BodyAsStream { get { throw null; } } public string ContentType { get { throw null; } set { } } public string CorrelationId { get { throw null; } set { } } public System.DateTimeOffset EnqueuedTime { get { throw null; } } public System.BinaryData EventBody { get { throw null; } } public string MessageId { get { throw null; } set { } } public long Offset { get { throw null; } } public string PartitionKey { get { throw null; } } public System.Collections.Generic.IDictionary<string, object> Properties { get { throw null; } } public long SequenceNumber { get { throw null; } } public System.Collections.Generic.IReadOnlyDictionary<string, object> SystemProperties { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public Azure.Core.Amqp.AmqpAnnotatedMessage GetRawAmqpMessage() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubConnection : System.IAsyncDisposable { protected EventHubConnection() { } public EventHubConnection(string connectionString) { } public EventHubConnection(string connectionString, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions) { } public EventHubConnection(string connectionString, string eventHubName) { } public EventHubConnection(string fullyQualifiedNamespace, string eventHubName, Azure.AzureNamedKeyCredential credential, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions = null) { } public EventHubConnection(string fullyQualifiedNamespace, string eventHubName, Azure.AzureSasCredential credential, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions = null) { } public EventHubConnection(string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions = null) { } public EventHubConnection(string connectionString, string eventHubName, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions) { } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public bool IsClosed { get { throw null; } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubConnectionOptions { public EventHubConnectionOptions() { } public System.Net.Security.RemoteCertificateValidationCallback CertificateValidationCallback { get { throw null; } set { } } public System.TimeSpan ConnectionIdleTimeout { get { throw null; } set { } } public System.Uri CustomEndpointAddress { get { throw null; } set { } } public System.Net.IWebProxy Proxy { get { throw null; } set { } } public int ReceiveBufferSizeInBytes { get { throw null; } set { } } public int SendBufferSizeInBytes { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsTransportType TransportType { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubProperties { protected internal EventHubProperties(string name, System.DateTimeOffset createdOn, string[] partitionIds) { } public System.DateTimeOffset CreatedOn { get { throw null; } } public string Name { get { throw null; } } public string[] PartitionIds { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubsConnectionStringProperties { public EventHubsConnectionStringProperties() { } public System.Uri Endpoint { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public string SharedAccessKey { get { throw null; } } public string SharedAccessKeyName { get { throw null; } } public string SharedAccessSignature { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static Azure.Messaging.EventHubs.EventHubsConnectionStringProperties Parse(string connectionString) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubsException : System.Exception { public EventHubsException(bool isTransient, string eventHubName) { } public EventHubsException(bool isTransient, string eventHubName, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { } public EventHubsException(bool isTransient, string eventHubName, string message) { } public EventHubsException(bool isTransient, string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { } public EventHubsException(bool isTransient, string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason, System.Exception innerException) { } public EventHubsException(bool isTransient, string eventHubName, string message, System.Exception innerException) { } public EventHubsException(string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { } public string EventHubName { get { throw null; } } public bool IsTransient { get { throw null; } } public override string Message { get { throw null; } } public Azure.Messaging.EventHubs.EventHubsException.FailureReason Reason { get { throw null; } } public override string ToString() { throw null; } public enum FailureReason { GeneralError = 0, ClientClosed = 1, ConsumerDisconnected = 2, ResourceNotFound = 3, MessageSizeExceeded = 4, QuotaExceeded = 5, ServiceBusy = 6, ServiceTimeout = 7, ServiceCommunicationProblem = 8, ProducerDisconnected = 9, InvalidClientState = 10, } } public static partial class EventHubsModelFactory { public static Azure.Messaging.EventHubs.EventData EventData(System.BinaryData eventBody, System.Collections.Generic.IDictionary<string, object> properties = null, System.Collections.Generic.IReadOnlyDictionary<string, object> systemProperties = null, string partitionKey = null, long sequenceNumber = (long)-9223372036854775808, long offset = (long)-9223372036854775808, System.DateTimeOffset enqueuedTime = default(System.DateTimeOffset)) { throw null; } public static Azure.Messaging.EventHubs.Producer.EventDataBatch EventDataBatch(long batchSizeBytes, System.Collections.Generic.IList<Azure.Messaging.EventHubs.EventData> batchEventStore, Azure.Messaging.EventHubs.Producer.CreateBatchOptions batchOptions = null, System.Func<Azure.Messaging.EventHubs.EventData, bool> tryAddCallback = null) { throw null; } public static Azure.Messaging.EventHubs.EventHubProperties EventHubProperties(string name, System.DateTimeOffset createdOn, string[] partitionIds) { throw null; } public static Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties LastEnqueuedEventProperties(long? lastSequenceNumber, long? lastOffset, System.DateTimeOffset? lastEnqueuedTime, System.DateTimeOffset? lastReceivedTime) { throw null; } public static Azure.Messaging.EventHubs.Consumer.PartitionContext PartitionContext(string partitionId, Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties lastEnqueuedEventProperties = default(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties)) { throw null; } public static Azure.Messaging.EventHubs.PartitionProperties PartitionProperties(string eventHubName, string partitionId, bool isEmpty, long beginningSequenceNumber, long lastSequenceNumber, long lastOffset, System.DateTimeOffset lastEnqueuedTime) { throw null; } } public enum EventHubsRetryMode { Fixed = 0, Exponential = 1, } public partial class EventHubsRetryOptions { public EventHubsRetryOptions() { } public Azure.Messaging.EventHubs.EventHubsRetryPolicy CustomRetryPolicy { get { throw null; } set { } } public System.TimeSpan Delay { get { throw null; } set { } } public System.TimeSpan MaximumDelay { get { throw null; } set { } } public int MaximumRetries { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryMode Mode { get { throw null; } set { } } public System.TimeSpan TryTimeout { get { throw null; } set { } } } public abstract partial class EventHubsRetryPolicy { protected EventHubsRetryPolicy() { } public abstract System.TimeSpan? CalculateRetryDelay(System.Exception lastException, int attemptCount); public abstract System.TimeSpan CalculateTryTimeout(int attemptCount); [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public enum EventHubsTransportType { AmqpTcp = 0, AmqpWebSockets = 1, } public partial class PartitionProperties { protected internal PartitionProperties(string eventHubName, string partitionId, bool isEmpty, long beginningSequenceNumber, long lastSequenceNumber, long lastOffset, System.DateTimeOffset lastEnqueuedTime) { } public long BeginningSequenceNumber { get { throw null; } } public string EventHubName { get { throw null; } } public string Id { get { throw null; } } public bool IsEmpty { get { throw null; } } public long LastEnqueuedOffset { get { throw null; } } public long LastEnqueuedSequenceNumber { get { throw null; } } public System.DateTimeOffset LastEnqueuedTime { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Azure.Messaging.EventHubs.Consumer { public partial class EventHubConsumerClient : System.IAsyncDisposable { public const string DefaultConsumerGroupName = "$Default"; protected EventHubConsumerClient() { } public EventHubConsumerClient(string consumerGroup, Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { } public EventHubConsumerClient(string consumerGroup, string connectionString) { } public EventHubConsumerClient(string consumerGroup, string connectionString, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions) { } public EventHubConsumerClient(string consumerGroup, string connectionString, string eventHubName) { } public EventHubConsumerClient(string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.AzureNamedKeyCredential credential, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { } public EventHubConsumerClient(string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.AzureSasCredential credential, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { } public EventHubConsumerClient(string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { } public EventHubConsumerClient(string consumerGroup, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions) { } public string ConsumerGroup { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public string Identifier { get { throw null; } } public bool IsClosed { get { throw null; } protected set { } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.EventHubProperties> GetEventHubPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual System.Threading.Tasks.Task<string[]> GetPartitionIdsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(string partitionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(bool startReadingAtEarliestEvent, Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions = null, [System.Runtime.CompilerServices.EnumeratorCancellationAttribute] System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsFromPartitionAsync(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition startingPosition, Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions, [System.Runtime.CompilerServices.EnumeratorCancellationAttribute] System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsFromPartitionAsync(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition startingPosition, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubConsumerClientOptions { public EventHubConsumerClientOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public string Identifier { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EventPosition : System.IEquatable<Azure.Messaging.EventHubs.Consumer.EventPosition> { private object _dummy; private int _dummyPrimitive; public static Azure.Messaging.EventHubs.Consumer.EventPosition Earliest { get { throw null; } } public static Azure.Messaging.EventHubs.Consumer.EventPosition Latest { get { throw null; } } public bool Equals(Azure.Messaging.EventHubs.Consumer.EventPosition other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public static Azure.Messaging.EventHubs.Consumer.EventPosition FromEnqueuedTime(System.DateTimeOffset enqueuedTime) { throw null; } public static Azure.Messaging.EventHubs.Consumer.EventPosition FromOffset(long offset, bool isInclusive = true) { throw null; } public static Azure.Messaging.EventHubs.Consumer.EventPosition FromSequenceNumber(long sequenceNumber, bool isInclusive = true) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Messaging.EventHubs.Consumer.EventPosition left, Azure.Messaging.EventHubs.Consumer.EventPosition right) { throw null; } public static bool operator !=(Azure.Messaging.EventHubs.Consumer.EventPosition left, Azure.Messaging.EventHubs.Consumer.EventPosition right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct LastEnqueuedEventProperties : System.IEquatable<Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties> { public LastEnqueuedEventProperties(long? lastSequenceNumber, long? lastOffset, System.DateTimeOffset? lastEnqueuedTime, System.DateTimeOffset? lastReceivedTime) { throw null; } public System.DateTimeOffset? EnqueuedTime { get { throw null; } } public System.DateTimeOffset? LastReceivedTime { get { throw null; } } public long? Offset { get { throw null; } } public long? SequenceNumber { get { throw null; } } public bool Equals(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties left, Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties right) { throw null; } public static bool operator !=(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties left, Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties right) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class PartitionContext { protected internal PartitionContext(string partitionId) { } public string PartitionId { get { throw null; } } public virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct PartitionEvent { private object _dummy; private int _dummyPrimitive; public PartitionEvent(Azure.Messaging.EventHubs.Consumer.PartitionContext partition, Azure.Messaging.EventHubs.EventData data) { throw null; } public Azure.Messaging.EventHubs.EventData Data { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.PartitionContext Partition { get { throw null; } } } public partial class ReadEventOptions { public ReadEventOptions() { } public int CacheEventCount { get { throw null; } set { } } public System.TimeSpan? MaximumWaitTime { get { throw null; } set { } } public long? OwnerLevel { get { throw null; } set { } } public int PrefetchCount { get { throw null; } set { } } public long? PrefetchSizeInBytes { get { throw null; } set { } } public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Azure.Messaging.EventHubs.Primitives { public partial class EventProcessorCheckpoint { public EventProcessorCheckpoint() { } public string ConsumerGroup { get { throw null; } set { } } public string EventHubName { get { throw null; } set { } } public string FullyQualifiedNamespace { get { throw null; } set { } } public string PartitionId { get { throw null; } set { } } public Azure.Messaging.EventHubs.Consumer.EventPosition StartingPosition { get { throw null; } set { } } } public partial class EventProcessorOptions { public EventProcessorOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public Azure.Messaging.EventHubs.Consumer.EventPosition DefaultStartingPosition { get { throw null; } set { } } public string Identifier { get { throw null; } set { } } public Azure.Messaging.EventHubs.Processor.LoadBalancingStrategy LoadBalancingStrategy { get { throw null; } set { } } public System.TimeSpan LoadBalancingUpdateInterval { get { throw null; } set { } } public System.TimeSpan? MaximumWaitTime { get { throw null; } set { } } public System.TimeSpan PartitionOwnershipExpirationInterval { get { throw null; } set { } } public int PrefetchCount { get { throw null; } set { } } public long? PrefetchSizeInBytes { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventProcessorPartition { public EventProcessorPartition() { } public string PartitionId { get { throw null; } protected internal set { } } } public partial class EventProcessorPartitionOwnership { public EventProcessorPartitionOwnership() { } public string ConsumerGroup { get { throw null; } set { } } public string EventHubName { get { throw null; } set { } } public string FullyQualifiedNamespace { get { throw null; } set { } } public System.DateTimeOffset LastModifiedTime { get { throw null; } set { } } public string OwnerIdentifier { get { throw null; } set { } } public string PartitionId { get { throw null; } set { } } public string Version { get { throw null; } set { } } } public abstract partial class EventProcessor<TPartition> where TPartition : Azure.Messaging.EventHubs.Primitives.EventProcessorPartition, new() { protected EventProcessor() { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string connectionString, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.AzureNamedKeyCredential credential, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.AzureSasCredential credential, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } public string ConsumerGroup { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public string Identifier { get { throw null; } } public bool IsRunning { get { throw null; } protected set { } } protected Azure.Messaging.EventHubs.EventHubsRetryPolicy RetryPolicy { get { throw null; } } protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership>> ClaimOwnershipAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership> desiredOwnership, System.Threading.CancellationToken cancellationToken); protected internal virtual Azure.Messaging.EventHubs.EventHubConnection CreateConnection() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } protected virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.Primitives.EventProcessorCheckpoint> GetCheckpointAsync(string partitionId, System.Threading.CancellationToken cancellationToken) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorCheckpoint>> ListCheckpointsAsync(System.Threading.CancellationToken cancellationToken); protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership>> ListOwnershipAsync(System.Threading.CancellationToken cancellationToken); protected virtual System.Threading.Tasks.Task<string[]> ListPartitionIdsAsync(Azure.Messaging.EventHubs.EventHubConnection connection, System.Threading.CancellationToken cancellationToken) { throw null; } protected virtual System.Threading.Tasks.Task OnInitializingPartitionAsync(TPartition partition, System.Threading.CancellationToken cancellationToken) { throw null; } protected virtual System.Threading.Tasks.Task OnPartitionProcessingStoppedAsync(TPartition partition, Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason reason, System.Threading.CancellationToken cancellationToken) { throw null; } protected abstract System.Threading.Tasks.Task OnProcessingErrorAsync(System.Exception exception, TPartition partition, string operationDescription, System.Threading.CancellationToken cancellationToken); protected abstract System.Threading.Tasks.Task OnProcessingEventBatchAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> events, TPartition partition, System.Threading.CancellationToken cancellationToken); protected virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties(string partitionId) { throw null; } public virtual void StartProcessing(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public virtual System.Threading.Tasks.Task StartProcessingAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual void StopProcessing(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public virtual System.Threading.Tasks.Task StopProcessingAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class PartitionReceiver : System.IAsyncDisposable { protected PartitionReceiver() { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string connectionString, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string fullyQualifiedNamespace, string eventHubName, Azure.AzureNamedKeyCredential credential, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string fullyQualifiedNamespace, string eventHubName, Azure.AzureSasCredential credential, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public string ConsumerGroup { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public string Identifier { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.EventPosition InitialPosition { get { throw null; } } public bool IsClosed { get { throw null; } protected set { } } public string PartitionId { get { throw null; } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties() { throw null; } public virtual System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData>> ReceiveBatchAsync(int maximumEventCount, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData>> ReceiveBatchAsync(int maximumEventCount, System.TimeSpan maximumWaitTime, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class PartitionReceiverOptions { public PartitionReceiverOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public System.TimeSpan? DefaultMaximumReceiveWaitTime { get { throw null; } set { } } public string Identifier { get { throw null; } set { } } public long? OwnerLevel { get { throw null; } set { } } public int PrefetchCount { get { throw null; } set { } } public long? PrefetchSizeInBytes { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Azure.Messaging.EventHubs.Processor { public enum LoadBalancingStrategy { Balanced = 0, Greedy = 1, } public partial class PartitionClosingEventArgs { public PartitionClosingEventArgs(string partitionId, Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason reason, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public string PartitionId { get { throw null; } } public Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason Reason { get { throw null; } } } public partial class PartitionInitializingEventArgs { public PartitionInitializingEventArgs(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition defaultStartingPosition, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.EventPosition DefaultStartingPosition { get { throw null; } set { } } public string PartitionId { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ProcessErrorEventArgs { private object _dummy; private int _dummyPrimitive; public ProcessErrorEventArgs(string partitionId, string operation, System.Exception exception, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public System.Exception Exception { get { throw null; } } public string Operation { get { throw null; } } public string PartitionId { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ProcessEventArgs { private object _dummy; private int _dummyPrimitive; public ProcessEventArgs(Azure.Messaging.EventHubs.Consumer.PartitionContext partition, Azure.Messaging.EventHubs.EventData data, System.Func<System.Threading.CancellationToken, System.Threading.Tasks.Task> updateCheckpointImplementation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public Azure.Messaging.EventHubs.EventData Data { get { throw null; } } public bool HasEvent { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.PartitionContext Partition { get { throw null; } } public System.Threading.Tasks.Task UpdateCheckpointAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public enum ProcessingStoppedReason { Shutdown = 0, OwnershipLost = 1, } } namespace Azure.Messaging.EventHubs.Producer { public partial class CreateBatchOptions : Azure.Messaging.EventHubs.Producer.SendEventOptions { public CreateBatchOptions() { } public long? MaximumSizeInBytes { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public sealed partial class EventDataBatch : System.IDisposable { internal EventDataBatch() { } public int Count { get { throw null; } } public long MaximumSizeInBytes { get { throw null; } } public long SizeInBytes { get { throw null; } } public void Dispose() { } public bool TryAdd(Azure.Messaging.EventHubs.EventData eventData) { throw null; } } public partial class EventHubProducerClient : System.IAsyncDisposable { protected EventHubProducerClient() { } public EventHubProducerClient(Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { } public EventHubProducerClient(string connectionString) { } public EventHubProducerClient(string connectionString, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions) { } public EventHubProducerClient(string connectionString, string eventHubName) { } public EventHubProducerClient(string fullyQualifiedNamespace, string eventHubName, Azure.AzureNamedKeyCredential credential, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { } public EventHubProducerClient(string fullyQualifiedNamespace, string eventHubName, Azure.AzureSasCredential credential, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { } public EventHubProducerClient(string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { } public EventHubProducerClient(string connectionString, string eventHubName, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions) { } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public string Identifier { get { throw null; } } public bool IsClosed { get { throw null; } protected set { } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask<Azure.Messaging.EventHubs.Producer.EventDataBatch> CreateBatchAsync(Azure.Messaging.EventHubs.Producer.CreateBatchOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask<Azure.Messaging.EventHubs.Producer.EventDataBatch> CreateBatchAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.EventHubProperties> GetEventHubPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual System.Threading.Tasks.Task<string[]> GetPartitionIdsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(string partitionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task SendAsync(Azure.Messaging.EventHubs.Producer.EventDataBatch eventBatch, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task SendAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> eventBatch, Azure.Messaging.EventHubs.Producer.SendEventOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task SendAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> eventBatch, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubProducerClientOptions { public EventHubProducerClientOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public string Identifier { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class SendEventOptions { public SendEventOptions() { } public string PartitionId { get { throw null; } set { } } public string PartitionKey { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Microsoft.Extensions.Azure { public static partial class EventHubClientBuilderExtensions { public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClientWithNamespace<TBuilder>(this TBuilder builder, string consumerGroup, string fullyQualifiedNamespace, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder>(this TBuilder builder, string consumerGroup, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder>(this TBuilder builder, string consumerGroup, string connectionString, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClientWithNamespace<TBuilder>(this TBuilder builder, string fullyQualifiedNamespace, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder>(this TBuilder builder, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder>(this TBuilder builder, string connectionString, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; } } }
/* * AsyncResult.cs - Implementation of the * "System.Runtime.Remoting.Messaging.AsyncResult" class. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Runtime.Remoting.Messaging { #if CONFIG_REFLECTION using System; using System.Threading; using System.Runtime.CompilerServices; // This class is not ECMA-compatible, strictly speaking. But it // is required to implement asynchronous delegates. public class AsyncResult : IAsyncResult #if CONFIG_REMOTING , IMessageSink #endif { // Internal state. private Delegate del; private Object[] args; private AsyncCallback callback; private Object state; private Object result; private Exception resultException; private bool synchronous; private bool completed; private bool endInvokeCalled; private ManualResetEvent waitHandle; #if CONFIG_REMOTING private IMessage replyMessage; private IMessageCtrl messageControl; #endif // Construct a new asynchronous result object and begin invocation. internal AsyncResult(Delegate del, Object[] args, AsyncCallback callback, Object state) { // Initialize the fields within this class. this.del = del; this.args = args; this.callback = callback; this.state = state; this.result = null; this.resultException = null; this.synchronous = false; this.completed = false; this.endInvokeCalled = false; // If we have threads, then queue the delegate to run // on the thread pool's completion worker thread. if(Thread.CanStartThreads()) { ThreadPool.QueueCompletionItem (new WaitCallback(Run), null); return; } // We don't have threads, so call the delegate synchronously. this.synchronous = true; try { this.result = del.DynamicInvoke(args); } catch(Exception e) { this.resultException = e; } this.completed = true; if(callback != null) { callback(this); } } // Get the delegate that was invoked. public virtual Object AsyncDelegate { get { return del; } } // Get the state information for a BeginInvoke callback. public virtual Object AsyncState { get { return state; } } // Get a wait handle that can be used to wait for the // asynchronous delegate call to complete. public virtual WaitHandle AsyncWaitHandle { get { lock(this) { if(waitHandle == null) { waitHandle = new ManualResetEvent(false); } return waitHandle; } } } // Determine if the call completed synchronously. public virtual bool CompletedSynchronously { get { lock(this) { return synchronous; } } } // Get or set the state which represents if "EndInvoke" // has been called for the delegate. public bool EndInvokeCalled { get { lock(this) { return endInvokeCalled; } } set { lock(this) { endInvokeCalled = value; } } } // Determine if the call has completed yet. public virtual bool IsCompleted { get { lock(this) { return completed; } } } // Run the delegate on the completion worker thread. private void Run(Object state) { try { result = del.DynamicInvoke(args); } catch(Exception e) { resultException = e; } completed = true; ((ISignal)AsyncWaitHandle).Signal(); if(callback != null) { callback(this); } } // Set the output parameters for an "EndInvoke" request. [MethodImpl(MethodImplOptions.InternalCall)] extern private static void SetOutParams (Delegate del, Object[] args, Object[] outParams); // End invocation on the delegate in this object. internal Object EndInvoke(Object[] outParams) { // Check for synchronous returns first. lock(this) { if(synchronous) { endInvokeCalled = true; if(resultException != null) { throw resultException; } else { SetOutParams(del, args, outParams); return result; } } } // Wait for the worker thread to signal us. AsyncWaitHandle.WaitOne(); // Process the return values. lock(this) { endInvokeCalled = true; if(resultException != null) { throw resultException; } else { SetOutParams(del, args, outParams); return result; } } } #if CONFIG_REMOTING // Implement the IMessageSink interface. public IMessageSink NextSink { get { return null; } } public virtual IMessageCtrl AsyncProcessMessage (IMessage msg, IMessageSink replySink) { throw new NotSupportedException (_("NotSupp_DelAsyncProcMsg")); } public virtual IMessage SyncProcessMessage(IMessage msg) { if(msg != null) { if(msg is IMethodReturnMessage) { replyMessage = msg; } else { replyMessage = new ReturnMessage (new RemotingException(), new NullMessage()); } } else { replyMessage = new ReturnMessage (new RemotingException(), new NullMessage()); } completed = true; ((ISignal)AsyncWaitHandle).Signal(); if(callback != null) { callback(this); } return null; } // Get the reply message. public virtual IMessage GetReplyMessage() { return replyMessage; } // Set the message control information for this result. public virtual void SetMessageCtrl(IMessageCtrl mc) { messageControl = mc; } #endif // CONFIG_REMOTING }; // class AsyncResult #endif // CONFIG_REFLECTION }; // namespace System.Runtime.Remoting.Messaging
namespace Alchemi.Console.PropertiesDialogs { partial class ApplicationProperties { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ApplicationProperties)); this.btnStop = new System.Windows.Forms.Button(); this.chkPrimary = new System.Windows.Forms.CheckBox(); this.txNumThreads = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.txState = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.txCompleted = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.txCreated = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.txUsername = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.txId = new System.Windows.Forms.TextBox(); this.lbId = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.tabGeneral.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.iconBox)).BeginInit(); this.tabs.SuspendLayout(); this.SuspendLayout(); // // btnOK // this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnCancel // this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnApply // this.btnApply.Click += new System.EventHandler(this.btnApply_Click); // // imgListSmall // this.imgListSmall.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgListSmall.ImageStream"))); this.imgListSmall.Images.SetKeyName(0, ""); this.imgListSmall.Images.SetKeyName(1, ""); this.imgListSmall.Images.SetKeyName(2, ""); this.imgListSmall.Images.SetKeyName(3, ""); this.imgListSmall.Images.SetKeyName(4, ""); this.imgListSmall.Images.SetKeyName(5, ""); this.imgListSmall.Images.SetKeyName(6, ""); this.imgListSmall.Images.SetKeyName(7, ""); this.imgListSmall.Images.SetKeyName(8, ""); this.imgListSmall.Images.SetKeyName(9, ""); this.imgListSmall.Images.SetKeyName(10, ""); this.imgListSmall.Images.SetKeyName(11, ""); this.imgListSmall.Images.SetKeyName(12, ""); // // tabGeneral // this.tabGeneral.Controls.Add(this.btnStop); this.tabGeneral.Controls.Add(this.chkPrimary); this.tabGeneral.Controls.Add(this.txNumThreads); this.tabGeneral.Controls.Add(this.label6); this.tabGeneral.Controls.Add(this.txState); this.tabGeneral.Controls.Add(this.label5); this.tabGeneral.Controls.Add(this.txCompleted); this.tabGeneral.Controls.Add(this.label4); this.tabGeneral.Controls.Add(this.txCreated); this.tabGeneral.Controls.Add(this.label3); this.tabGeneral.Controls.Add(this.txUsername); this.tabGeneral.Controls.Add(this.label2); this.tabGeneral.Controls.Add(this.txId); this.tabGeneral.Controls.Add(this.lbId); this.tabGeneral.Controls.SetChildIndex(this.iconBox, 0); this.tabGeneral.Controls.SetChildIndex(this.lbName, 0); this.tabGeneral.Controls.SetChildIndex(this.lineLabel, 0); this.tabGeneral.Controls.SetChildIndex(this.lbId, 0); this.tabGeneral.Controls.SetChildIndex(this.txId, 0); this.tabGeneral.Controls.SetChildIndex(this.label2, 0); this.tabGeneral.Controls.SetChildIndex(this.txUsername, 0); this.tabGeneral.Controls.SetChildIndex(this.label3, 0); this.tabGeneral.Controls.SetChildIndex(this.txCreated, 0); this.tabGeneral.Controls.SetChildIndex(this.label4, 0); this.tabGeneral.Controls.SetChildIndex(this.txCompleted, 0); this.tabGeneral.Controls.SetChildIndex(this.label5, 0); this.tabGeneral.Controls.SetChildIndex(this.txState, 0); this.tabGeneral.Controls.SetChildIndex(this.label6, 0); this.tabGeneral.Controls.SetChildIndex(this.txNumThreads, 0); this.tabGeneral.Controls.SetChildIndex(this.chkPrimary, 0); this.tabGeneral.Controls.SetChildIndex(this.btnStop, 0); // // iconBox // this.iconBox.Image = ((System.Drawing.Image)(resources.GetObject("iconBox.Image"))); // // btnStop // this.btnStop.Location = new System.Drawing.Point(248, 288); this.btnStop.Name = "btnStop"; this.btnStop.Size = new System.Drawing.Size(75, 23); this.btnStop.TabIndex = 33; this.btnStop.Text = "Stop"; this.btnStop.Click += new System.EventHandler(this.btnStop_Click); // // chkPrimary // this.chkPrimary.AutoCheck = false; this.chkPrimary.Location = new System.Drawing.Point(16, 256); this.chkPrimary.Name = "chkPrimary"; this.chkPrimary.Size = new System.Drawing.Size(104, 24); this.chkPrimary.TabIndex = 32; this.chkPrimary.Text = "Primary"; // // txNumThreads // this.txNumThreads.BackColor = System.Drawing.Color.White; this.txNumThreads.Location = new System.Drawing.Point(88, 232); this.txNumThreads.Name = "txNumThreads"; this.txNumThreads.ReadOnly = true; this.txNumThreads.Size = new System.Drawing.Size(120, 20); this.txNumThreads.TabIndex = 31; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(16, 232); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(67, 13); this.label6.TabIndex = 30; this.label6.Text = "# of threads:"; // // txState // this.txState.BackColor = System.Drawing.Color.White; this.txState.Location = new System.Drawing.Point(88, 200); this.txState.Name = "txState"; this.txState.ReadOnly = true; this.txState.Size = new System.Drawing.Size(120, 20); this.txState.TabIndex = 29; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(16, 200); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(35, 13); this.label5.TabIndex = 28; this.label5.Text = "State:"; // // txCompleted // this.txCompleted.BackColor = System.Drawing.Color.White; this.txCompleted.Location = new System.Drawing.Point(88, 168); this.txCompleted.Name = "txCompleted"; this.txCompleted.ReadOnly = true; this.txCompleted.Size = new System.Drawing.Size(224, 20); this.txCompleted.TabIndex = 27; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(16, 168); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(60, 13); this.label4.TabIndex = 26; this.label4.Text = "Completed:"; // // txCreated // this.txCreated.BackColor = System.Drawing.Color.White; this.txCreated.Location = new System.Drawing.Point(88, 136); this.txCreated.Name = "txCreated"; this.txCreated.ReadOnly = true; this.txCreated.Size = new System.Drawing.Size(224, 20); this.txCreated.TabIndex = 25; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(16, 136); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(47, 13); this.label3.TabIndex = 24; this.label3.Text = "Created:"; // // txUsername // this.txUsername.BackColor = System.Drawing.Color.White; this.txUsername.Location = new System.Drawing.Point(88, 104); this.txUsername.Name = "txUsername"; this.txUsername.ReadOnly = true; this.txUsername.Size = new System.Drawing.Size(224, 20); this.txUsername.TabIndex = 23; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(16, 104); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(61, 13); this.label2.TabIndex = 22; this.label2.Text = "User name:"; // // txId // this.txId.BackColor = System.Drawing.Color.White; this.txId.Location = new System.Drawing.Point(88, 72); this.txId.Name = "txId"; this.txId.ReadOnly = true; this.txId.Size = new System.Drawing.Size(224, 20); this.txId.TabIndex = 21; // // lbId // this.lbId.AutoSize = true; this.lbId.Location = new System.Drawing.Point(16, 72); this.lbId.Name = "lbId"; this.lbId.Size = new System.Drawing.Size(19, 13); this.lbId.TabIndex = 20; this.lbId.Text = "Id:"; // // ApplicationProperties2 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(352, 389); this.Name = "ApplicationProperties2"; this.Text = "Application Properties"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.tabGeneral.ResumeLayout(false); this.tabGeneral.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.iconBox)).EndInit(); this.tabs.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnStop; private System.Windows.Forms.CheckBox chkPrimary; private System.Windows.Forms.TextBox txNumThreads; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox txState; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox txCompleted; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txCreated; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txUsername; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txId; private System.Windows.Forms.Label lbId; } }
/* * 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.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Client; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Servers; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Data.SimpleDB; namespace OpenSim.Region.CoreModules.Avatar.MuteList { public class MuteListModule : IRegionModule, IMuteListModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private bool enabled = true; private List<Scene> m_SceneList = new List<Scene>(); private ConnectionFactory _connectionFactory = null; // Legacy mutes are BY_NAME and have null UUID. enum MuteType { BY_NAME = 0, AGENT = 1, OBJECT = 2, GROUP = 3, COUNT = 4 }; class MuteListEntry { public int m_Type; // MuteType public string m_Name; public uint m_Flags; public MuteListEntry() { m_Type = (int)MuteType.AGENT; m_Name = String.Empty; m_Flags = 0; } public MuteListEntry(int type, string name, uint flags) { m_Type = type; m_Name = name; m_Flags = flags; } }; Dictionary<UUID, Dictionary<UUID, MuteListEntry>> MuteListCache = new Dictionary<UUID, Dictionary<UUID, MuteListEntry>>(); public void Initialize(Scene scene, IConfigSource config) { if (!enabled) return; IConfig cnf = config.Configs["Messaging"]; if (cnf == null) { enabled = false; return; } if (cnf != null && cnf.GetString( "MuteListModule", "None") != "MuteListModule") { enabled = false; return; } string dbType = cnf.GetString("MuteListDBType"); if (dbType == null) dbType = "MySQL"; // default string connStr = cnf.GetString("MuteListConnString"); if (connStr == null) { // If the MuteListConnString INI option isn't found, fall back to the one used for profiles. cnf = config.Configs["Profile"]; connStr = cnf.GetString("ProfileConnString"); } _connectionFactory = new ConnectionFactory(dbType, connStr); lock (m_SceneList) { if (!m_SceneList.Contains(scene)) m_SceneList.Add(scene); scene.RegisterModuleInterface<IMuteListModule>(this); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnRemovePresence += OnRemovePresence; } } public void PostInitialize() { if (!enabled) return; if (m_SceneList.Count == 0) return; // Test the db connection using (ISimpleDB db = _connectionFactory.GetConnection()) { } m_log.Debug("[MUTE LIST] Mute list enabled."); } public string Name { get { return "MuteListModule"; } } public bool IsSharedModule { get { return true; } } public void Close() { } private void OnNewClient(IClientAPI client) { client.OnMuteListRequest += OnMuteListRequest; client.OnUpdateMuteListEntry += OnUpdateMuteListEntry; client.OnRemoveMuteListEntry += OnRemoveMuteListEntry; } private void OnRemovePresence(UUID AgentId) { if (MuteListCache.ContainsKey(AgentId)) MuteListCache.Remove(AgentId); } private Dictionary<UUID, MuteListEntry> MapMuteListFromDBResults(List<Dictionary<string, string>> results) { Dictionary<UUID, MuteListEntry> MuteList = new Dictionary<UUID, MuteListEntry>(); foreach (Dictionary<string, string> result in results) { MuteListEntry entry = new MuteListEntry(); UUID MuteID = new UUID(result["MuteID"]); entry.m_Type = Convert.ToInt32(result["MuteType"]); entry.m_Name = result["MuteName"]; entry.m_Flags = Convert.ToUInt32(result["MuteFlags"]); MuteList.Add(MuteID, entry); } return MuteList; } private Dictionary<UUID,MuteListEntry> DBLoadMuteList(UUID AgentID) { using (ISimpleDB db = _connectionFactory.GetConnection()) { string query = " SELECT AgentID, MuteType, MuteID, MuteName, MuteFlags" + " FROM mutelist" + " WHERE " + " AgentID = ?agentID"; Dictionary<string, object> parms = new Dictionary<string,object>(); parms.Add("?agentID", AgentID); List<Dictionary<string, string>> results = db.QueryWithResults(query, parms); if (results.Count < 1 || results[0]["AgentID"] == null) return null; return MapMuteListFromDBResults(results); } } Dictionary<UUID,MuteListEntry> GetMuteList(UUID AgentID) { if (MuteListCache.ContainsKey(AgentID)) return MuteListCache[AgentID]; Dictionary<UUID,MuteListEntry> MuteList = DBLoadMuteList(AgentID); if (MuteList == null) // Mute list is empty for user, return a new empty one MuteList = new Dictionary<UUID,MuteListEntry>(); MuteListCache.Add(AgentID, MuteList); return MuteList; } /// <summary> /// This doesn't return the mutelist (mutees) for a user, it returns all users who have this user/object muted (muters). /// Implemented as a single DB call. /// </summary> /// <param name="id">The user or object that may be muted.</param> /// <returns>UUIDs of those who have it muted.</returns> public List<UUID> GetInverseMuteList(UUID muteID) { List<UUID> muters = new List<UUID>(); using (ISimpleDB db = _connectionFactory.GetConnection()) { string query = " SELECT * FROM mutelist WHERE MuteID = ?muteID"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?muteID", muteID); List<Dictionary<string, string>> results = db.QueryWithResults(query, parms); if (results.Count < 1 || results[0]["AgentID"] == null) return muters; // empty list foreach (Dictionary<string, string> result in results) { UUID MuteID = new UUID(result["AgentID"]); muters.Add(MuteID); } } return muters; } /// <summary> /// Don't use this for messages broadcast to more than one user /// </summary> /// <param name="sender"></param> /// <param name="target"></param> /// <returns>Returns true if target has sender muted.</returns> public bool IsMuted(UUID sender, UUID target) { using (ISimpleDB db = _connectionFactory.GetConnection()) { string query = "SELECT COUNT(*) as MuteCount FROM mutelist WHERE AgentID = ?agentID AND MuteID = ?muteID"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?agentID", target); parms.Add("?muteID", sender); List<Dictionary<string, string>> results = db.QueryWithResults(query, parms); return (Convert.ToInt32(results[0]["MuteCount"]) != 0); } } private void DBStoreMuteListEntry(UUID AgentID, UUID MuteID, MuteListEntry entry, bool isUpdate) { using (ISimpleDB db = _connectionFactory.GetConnection()) { string query; if (isUpdate) query = "UPDATE mutelist " + "SET " + " MuteType = ?muteType" + " , MuteName = ?muteName" + " , MuteFlags= ?muteFlags" + " WHERE " + " AgentID = ?agentID AND MuteID = ?muteID"; else query = "INSERT INTO mutelist " + "(AgentID, MuteType, MuteID, MuteName, MuteFlags) " + "VALUES(?AgentID, ?MuteType, ?MuteID, ?MuteName, ?MuteFlags)"; Dictionary<string, object> parms = new Dictionary<string,object>(); parms.Add("?agentID", AgentID); parms.Add("?muteID", MuteID); parms.Add("?muteType", entry.m_Type); parms.Add("?muteName", entry.m_Name); parms.Add("?muteFlags", entry.m_Flags); db.QueryNoResults(query, parms); } } private void DBRemoveMuteListEntry(UUID AgentID, UUID MuteID) { using (ISimpleDB db = _connectionFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string,object>(); string query = "DELETE FROM mutelist WHERE AgentID = ?agentID AND MuteID = ?muteID"; parms.Add("?agentID", AgentID); parms.Add("?muteID", MuteID); db.QueryNoResults(query, parms); } } private byte[] GetMuteListFileData(UUID AgentID) { Dictionary<UUID, MuteListEntry> MuteList; string data = String.Empty; int lines = 0; MuteList = GetMuteList(AgentID); foreach (KeyValuePair<UUID, MuteListEntry> pair in MuteList) { UUID MuteID = new UUID(pair.Key); MuteListEntry entry = pair.Value; if (lines++ != 0) data += "\n"; data += " "+entry.m_Type.ToString()+ " "+MuteID.ToString()+ " "+entry.m_Name.ToString()+ "|"+entry.m_Flags.ToString(); } return Utils.StringToBytes(data); } private void OnMuteListRequest(IClientAPI client, uint crc) { m_log.DebugFormat("[MUTE LIST] List request for crc {0}", crc); string filename = "mutes"+client.AgentId.ToString(); IXfer xfer = client.Scene.RequestModuleInterface<IXfer>(); if (xfer != null) { xfer.AddNewFile(filename, GetMuteListFileData(client.AgentId)); client.SendMuteListUpdate(filename); } } private void OnUpdateMuteListEntry(IClientAPI client, UUID AgentID, int muteType, UUID muteID, string Name, uint muteFlags) { Dictionary<UUID, MuteListEntry> MuteList; bool isUpdate = false; MuteList = GetMuteList(AgentID); isUpdate = MuteList.ContainsKey(muteID); if (isUpdate) MuteList.Remove(muteID); switch ((MuteType)muteType) { case MuteType.BY_NAME: m_log.DebugFormat("[MUTE LIST] Update from {0} for name: {1} (ID {2}) flags={3}", AgentID, Name, muteID, muteFlags); break; case MuteType.AGENT: m_log.DebugFormat("[MUTE LIST] Update from {0} for agent: {1} ({2}) flags={3}", AgentID, muteID, Name, muteFlags); break; case MuteType.OBJECT: m_log.DebugFormat("[MUTE LIST] Update from {0} for object: {1} ({2}) flags={3}", AgentID, muteID, Name, muteFlags); break; case MuteType.GROUP: m_log.DebugFormat("[MUTE LIST] Update from {0} for group: {1} ({2}) flags={3}", AgentID, muteID, Name, muteFlags); break; case MuteType.COUNT: m_log.DebugFormat("[MUTE LIST] Update from {0} for count: {1} ({2}) flags={3}", AgentID, muteID, Name, muteFlags); break; default: m_log.ErrorFormat("[MUTE LIST] Update from {0} unknown type {1} with ID {2} Name {3} flags={4}", AgentID, muteType, muteID, Name, muteFlags); break; } MuteListEntry entry = new MuteListEntry(muteType, Name, muteFlags); MuteList.Add(muteID, entry); DBStoreMuteListEntry(AgentID, muteID, entry, isUpdate); } private void OnRemoveMuteListEntry(IClientAPI client, UUID AgentID, UUID muteID, string name) { m_log.DebugFormat("[MUTE LIST] Remove from {0} for ID {1} Name {2}", AgentID, muteID, name); Dictionary<UUID, MuteListEntry> MuteList; MuteList = GetMuteList(AgentID); if (MuteList.ContainsKey(muteID)) { MuteList.Remove(muteID); DBRemoveMuteListEntry(AgentID, muteID); } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Umbraco.Core { /// <summary> /// A utility class for type checking, this provides internal caching so that calls to these methods will be faster /// than doing a manual type check in c# /// </summary> internal static class TypeHelper { private static readonly ConcurrentDictionary<Type, FieldInfo[]> GetFieldsCache = new ConcurrentDictionary<Type, FieldInfo[]>(); private static readonly ConcurrentDictionary<Tuple<Type, bool, bool, bool>, PropertyInfo[]> GetPropertiesCache = new ConcurrentDictionary<Tuple<Type, bool, bool, bool>, PropertyInfo[]>(); /// <summary> /// Checks if the method is actually overriding a base method /// </summary> /// <param name="m"></param> /// <returns></returns> public static bool IsOverride(MethodInfo m) { return m.GetBaseDefinition().DeclaringType != m.DeclaringType; } /// <summary> /// Find all assembly references that are referencing the assignTypeFrom Type's assembly found in the assemblyList /// </summary> /// <param name="assignTypeFrom"></param> /// <param name="assemblies"></param> /// <returns></returns> /// <remarks> /// If the assembly of the assignTypeFrom Type is in the App_Code assembly, then we return nothing since things cannot /// reference that assembly, same with the global.asax assembly. /// </remarks> public static Assembly[] GetReferencedAssemblies(Type assignTypeFrom, IEnumerable<Assembly> assemblies) { //check if it is the app_code assembly. //check if it is App_global.asax assembly if (assignTypeFrom.Assembly.IsAppCodeAssembly() || assignTypeFrom.Assembly.IsGlobalAsaxAssembly()) { return Enumerable.Empty<Assembly>().ToArray(); } //find all assembly references that are referencing the current type's assembly since we //should only be scanning those assemblies because any other assembly will definitely not //contain sub type's of the one we're currently looking for return assemblies .Where(assembly => assembly == assignTypeFrom.Assembly || HasReferenceToAssemblyWithName(assembly, assignTypeFrom.Assembly.GetName().Name)) .ToArray(); } /// <summary> /// checks if the assembly has a reference with the same name as the expected assembly name. /// </summary> /// <param name="assembly"></param> /// <param name="expectedAssemblyName"></param> /// <returns></returns> private static bool HasReferenceToAssemblyWithName(Assembly assembly, string expectedAssemblyName) { return assembly .GetReferencedAssemblies() .Select(a => a.Name) .Contains(expectedAssemblyName, StringComparer.Ordinal); } /// <summary> /// Returns true if the type is a class and is not static /// </summary> /// <param name="t"></param> /// <returns></returns> public static bool IsNonStaticClass(Type t) { return t.IsClass && IsStaticClass(t) == false; } /// <summary> /// Returns true if the type is a static class /// </summary> /// <param name="type"></param> /// <returns></returns> /// <remarks> /// In IL a static class is abstract and sealed /// see: http://stackoverflow.com/questions/1175888/determine-if-a-type-is-static /// </remarks> public static bool IsStaticClass(Type type) { return type.IsAbstract && type.IsSealed; } /// <summary> /// Finds a lowest base class amongst a collection of types /// </summary> /// <param name="types"></param> /// <returns></returns> /// <remarks> /// The term 'lowest' refers to the most base class of the type collection. /// If a base type is not found amongst the type collection then an invalid attempt is returned. /// </remarks> public static Attempt<Type> GetLowestBaseType(params Type[] types) { if (types.Length == 0) { return Attempt<Type>.Fail(); } if (types.Length == 1) { return Attempt.Succeed(types[0]); } foreach (var curr in types) { var others = types.Except(new[] {curr}); //is the curr type a common denominator for all others ? var isBase = others.All(curr.IsAssignableFrom); //if this type is the base for all others if (isBase) { return Attempt.Succeed(curr); } } return Attempt<Type>.Fail(); } /// <summary> /// Determines whether the type <paramref name="implementation"/> is assignable from the specified implementation <typeparamref name="TContract"/>, /// and caches the result across the application using a <see cref="ConcurrentDictionary{TKey,TValue}"/>. /// </summary> /// <param name="contract">The type of the contract.</param> /// <param name="implementation">The implementation.</param> /// <returns> /// <c>true</c> if [is type assignable from] [the specified contract]; otherwise, <c>false</c>. /// </returns> public static bool IsTypeAssignableFrom(Type contract, Type implementation) { return contract.IsAssignableFrom(implementation); } /// <summary> /// Determines whether the type <paramref name="implementation"/> is assignable from the specified implementation <typeparamref name="TContract"/>, /// and caches the result across the application using a <see cref="ConcurrentDictionary{TKey,TValue}"/>. /// </summary> /// <typeparam name="TContract">The type of the contract.</typeparam> /// <param name="implementation">The implementation.</param> public static bool IsTypeAssignableFrom<TContract>(Type implementation) { return IsTypeAssignableFrom(typeof(TContract), implementation); } /// <summary> /// A cached method to determine whether <paramref name="implementation"/> represents a value type. /// </summary> /// <param name="implementation">The implementation.</param> public static bool IsValueType(Type implementation) { return implementation.IsValueType || implementation.IsPrimitive; } /// <summary> /// A cached method to determine whether <paramref name="implementation"/> is an implied value type (<see cref="Type.IsValueType"/>, <see cref="Type.IsEnum"/> or a string). /// </summary> /// <param name="implementation">The implementation.</param> public static bool IsImplicitValueType(Type implementation) { return IsValueType(implementation) || implementation.IsEnum || implementation == typeof (string); } public static bool IsTypeAssignableFrom<TContract>(object implementation) { if (implementation == null) throw new ArgumentNullException("implementation"); return IsTypeAssignableFrom<TContract>(implementation.GetType()); } /// <summary> /// Returns a PropertyInfo from a type /// </summary> /// <param name="type"></param> /// <param name="name"></param> /// <param name="mustRead"></param> /// <param name="mustWrite"></param> /// <param name="includeIndexed"></param> /// <param name="caseSensitive"> </param> /// <returns></returns> public static PropertyInfo GetProperty(Type type, string name, bool mustRead = true, bool mustWrite = true, bool includeIndexed = false, bool caseSensitive = true) { return CachedDiscoverableProperties(type, mustRead, mustWrite, includeIndexed) .FirstOrDefault(x => { if (caseSensitive) return x.Name == name; return x.Name.InvariantEquals(name); }); } /// <summary> /// Returns all public properties including inherited properties even for interfaces /// </summary> /// <param name="type"></param> /// <returns></returns> /// <remarks> /// taken from http://stackoverflow.com/questions/358835/getproperties-to-return-all-properties-for-an-interface-inheritance-hierarchy /// </remarks> public static PropertyInfo[] GetPublicProperties(Type type) { if (type.IsInterface) { var propertyInfos = new List<PropertyInfo>(); var considered = new List<Type>(); var queue = new Queue<Type>(); considered.Add(type); queue.Enqueue(type); while (queue.Count > 0) { var subType = queue.Dequeue(); foreach (var subInterface in subType.GetInterfaces()) { if (considered.Contains(subInterface)) continue; considered.Add(subInterface); queue.Enqueue(subInterface); } var typeProperties = subType.GetProperties( BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); var newPropertyInfos = typeProperties .Where(x => !propertyInfos.Contains(x)); propertyInfos.InsertRange(0, newPropertyInfos); } return propertyInfos.ToArray(); } return type.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); } /// <summary> /// Gets (and caches) <see cref="FieldInfo"/> discoverable in the current <see cref="AppDomain"/> for a given <paramref name="type"/>. /// </summary> /// <param name="type">The source.</param> /// <returns></returns> public static FieldInfo[] CachedDiscoverableFields(Type type) { return GetFieldsCache.GetOrAdd( type, x => type .GetFields(BindingFlags.Public | BindingFlags.Instance) .Where(y => !y.IsInitOnly) .ToArray()); } /// <summary> /// Gets (and caches) <see cref="PropertyInfo"/> discoverable in the current <see cref="AppDomain"/> for a given <paramref name="type"/>. /// </summary> /// <param name="type">The source.</param> /// <param name="mustRead">true if the properties discovered are readable</param> /// <param name="mustWrite">true if the properties discovered are writable</param> /// <param name="includeIndexed">true if the properties discovered are indexable</param> /// <returns></returns> public static PropertyInfo[] CachedDiscoverableProperties(Type type, bool mustRead = true, bool mustWrite = true, bool includeIndexed = false) { return GetPropertiesCache.GetOrAdd( new Tuple<Type, bool, bool, bool>(type, mustRead, mustWrite, includeIndexed), x => type .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(y => (!mustRead || y.CanRead) && (!mustWrite || y.CanWrite) && (includeIndexed || !y.GetIndexParameters().Any())) .ToArray()); } } }
/****************************************************************************/ /* DirectoryUtilities.cs */ /****************************************************************************/ /* AUTHOR: Vance Morrison * Date : 11/3/2005 */ /****************************************************************************/ using System; using System.Collections.Generic; using System.Diagnostics; // for StackTrace; Process using System.IO; /******************************************************************************/ /// <summary> /// General purpose utilities dealing with archiveFile system directories. /// </summary> public static class DirectoryUtilities { public static string GetRelativePath(string fileName, string directory) { Debug.Assert(fileName.StartsWith(directory), "directory not a prefix"); int directoryEnd = directory.Length; if (directoryEnd == 0) { return fileName; } while (directoryEnd < fileName.Length && fileName[directoryEnd] == '\\') { directoryEnd++; } string relativePath = fileName.Substring(directoryEnd); return relativePath; } /// <summary> /// SafeCopy sourceDirectory to directoryToVersion recursively. The target directory does /// no need to exist /// </summary> public static void Copy(string sourceDirectory, string targetDirectory) { Copy(sourceDirectory, targetDirectory, SearchOption.AllDirectories); } /// <summary> /// SafeCopy all files from sourceDirectory to directoryToVersion. If searchOptions == AllDirectories /// then the copy is recursive, otherwise it is just one level. The target directory does not /// need to exist. /// </summary> public static void Copy(string sourceDirectory, string targetDirectory, SearchOption searchOptions) { if (!Directory.Exists(targetDirectory)) { Directory.CreateDirectory(targetDirectory); } foreach (string sourceFile in Directory.GetFiles(sourceDirectory)) { string targetFile = Path.Combine(targetDirectory, Path.GetFileName(sourceFile)); FileUtilities.ForceCopy(sourceFile, targetFile); } if (searchOptions == SearchOption.AllDirectories) { foreach (string sourceDir in Directory.GetDirectories(sourceDirectory)) { string targetDir = Path.Combine(targetDirectory, Path.GetFileName(sourceDir)); Copy(sourceDir, targetDir, searchOptions); } } } /// <summary> /// Clean is sort of a 'safe' recursive delete of a directory. It either deletes the /// files or moves them to '*.deleting' names. It deletes directories that are completely /// empty. Thus it will do a recursive delete when that is possible. There will only /// be *.deleting files after this returns. It returns the number of files and directories /// that could not be deleted. /// </summary> public static int Clean(string directory) { if (!Directory.Exists(directory)) { return 0; } int ret = 0; foreach (string file in Directory.GetFiles(directory)) { if (!FileUtilities.ForceDelete(file)) { ret++; } } foreach (string subDir in Directory.GetDirectories(directory)) { ret += Clean(subDir); } if (ret == 0) { try { Directory.Delete(directory, true); } catch { ret++; } } else { ret++; } return ret; } /// <summary> /// Removes the oldest directories directly under 'directoryPath' so that /// only 'numberToKeep' are left. /// </summary> /// <param variable="directoryPath">Directory to removed old files from.</param> /// <param variable="numberToKeep">The number of files to keep.</param> /// <returns> true if there were no errors deleting files</returns> public static bool DeleteOldest(string directoryPath, int numberToKeep) { if (!Directory.Exists(directoryPath)) { return true; } string[] dirs = Directory.GetDirectories(directoryPath); int numToDelete = dirs.Length - numberToKeep; if (numToDelete <= 0) { return true; } Array.Sort<string>(dirs, delegate (string x, string y) { return File.GetLastWriteTimeUtc(x).CompareTo(File.GetLastWriteTimeUtc(y)); }); bool ret = true; for (int i = 0; i < numToDelete; i++) { try { Directory.Delete(dirs[i]); } catch (Exception) { // TODO trace message; ret = false; } } return ret; } /// <summary> /// DirectoryUtilities.GetFiles is basicaly the same as Directory.GetFiles /// however it returns IEnumerator, which means that it lazy. This is very important /// for large directory trees. A searchPattern can be specified (Windows wildcard conventions) /// that can be used to filter the set of archiveFile names returned. /// /// Suggested Usage /// /// foreach(string fileName in DirectoryUtilities.GetFiles("c:\", "*.txt")){ /// Console.WriteLine(fileName); /// } /// /// </summary> /// <param variable="directoryPath">The base directory to enumerate</param> /// <param variable="searchPattern">A pattern to filter the names (windows filename wildcards * ?)</param> /// <param variable="searchOptions">Indicate if the search is recursive or not. </param> /// <returns>The enumerator for all archiveFile names in the directory (recursively). </returns> public static IEnumerable<string> GetFiles(string directoryPath, string searchPattern, SearchOption searchOptions) { string[] fileNames = Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly); Array.Sort<string>(fileNames, StringComparer.OrdinalIgnoreCase); foreach (string fileName in fileNames) { yield return fileName; } if (searchOptions == SearchOption.AllDirectories) { string[] subDirNames = Directory.GetDirectories(directoryPath); Array.Sort<string>(subDirNames); foreach (string subDir in subDirNames) { foreach (string fileName in DirectoryUtilities.GetFiles(subDir, searchPattern, searchOptions)) { yield return fileName; } } } } public static IEnumerable<string> GetFiles(string directoryName, string searchPattern) { return GetFiles(directoryName, searchPattern, SearchOption.TopDirectoryOnly); } public static IEnumerable<string> GetFiles(string directoryName) { return GetFiles(directoryName, "*"); } }
/* * 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 Lucene.Net.Search; using Microsoft.VisualStudio.TestTools.UnitTesting; using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using Term = Lucene.Net.Index.Term; namespace LuceneNetSqlDirectory.Tests { [TestClass] public class TestTermScorer : LuceneTestCase { private class AnonymousClassCollector : Collector { public AnonymousClassCollector(System.Collections.IList docs, TestTermScorer enclosingInstance) { InitBlock(docs, enclosingInstance); } private void InitBlock(System.Collections.IList docs, TestTermScorer enclosingInstance) { this._docs = docs; this._enclosingInstance = enclosingInstance; } private System.Collections.IList _docs; private TestTermScorer _enclosingInstance; public TestTermScorer EnclosingInstance { get { return _enclosingInstance; } } private int _baseRenamed = 0; private Scorer _scorer; public override void SetScorer(Scorer scorer) { this._scorer = scorer; } public override void Collect(int doc) { float score = _scorer.Score(); doc = doc + _baseRenamed; _docs.Add(new TestHit(_enclosingInstance, doc, score)); Assert.IsTrue(score > 0, "score " + score + " is not greater than 0"); Assert.IsTrue(doc == 0 || doc == 5, "Doc: " + doc + " does not equal 0 or doc does not equal 5"); } public override void SetNextReader(IndexReader reader, int docBase) { _baseRenamed = docBase; } public override bool AcceptsDocsOutOfOrder { get { return true; } } } protected internal SqlServerDirectory Directory; private const System.String FIELD = "field"; protected internal System.String[] Values = new System.String[] { "all", "dogs dogs", "like", "playing", "fetch", "all" }; protected internal IndexSearcher IndexSearcher; protected internal IndexReader indexReader; [TestInitialize] public override void TestInitialize() { base.TestInitialize(); Directory = new SqlServerDirectory(Connection, new Options()); IndexWriter writer = new IndexWriter(Directory, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); for (int i = 0; i < Values.Length; i++) { Document doc = new Document(); doc.Add(new Field(FIELD, Values[i], Field.Store.YES, Field.Index.ANALYZED)); writer.AddDocument(doc); } writer.Close(); IndexSearcher = new IndexSearcher(Directory, false); indexReader = IndexSearcher.IndexReader; } [TestMethod] public virtual void Test() { Term allTerm = new Term(FIELD, "all"); TermQuery termQuery = new TermQuery(allTerm); Weight weight = termQuery.Weight(IndexSearcher); TermScorer ts = new TermScorer(weight, indexReader.TermDocs(allTerm), IndexSearcher.Similarity, indexReader.Norms(FIELD)); //we have 2 documents with the term all in them, one document for all the other values System.Collections.IList docs = new System.Collections.ArrayList(); //must call next first ts.Score(new AnonymousClassCollector(docs, this)); Assert.IsTrue(docs.Count == 2, "docs Size: " + docs.Count + " is not: " + 2); TestHit doc0 = (TestHit)docs[0]; TestHit doc5 = (TestHit)docs[1]; //The scores should be the same Assert.IsTrue(doc0.Score == doc5.Score, doc0.Score + " does not equal: " + doc5.Score); /* Score should be (based on Default Sim.: All floats are approximate tf = 1 numDocs = 6 docFreq(all) = 2 idf = ln(6/3) + 1 = 1.693147 idf ^ 2 = 2.8667 boost = 1 lengthNorm = 1 //there is 1 term in every document coord = 1 sumOfSquaredWeights = (idf * boost) ^ 2 = 1.693147 ^ 2 = 2.8667 queryNorm = 1 / (sumOfSquaredWeights)^0.5 = 1 /(1.693147) = 0.590 score = 1 * 2.8667 * 1 * 1 * 0.590 = 1.69 */ Assert.IsTrue(doc0.Score == 1.6931472f, doc0.Score + " does not equal: " + 1.6931472f); } [TestMethod] public virtual void TestNext() { Term allTerm = new Term(FIELD, "all"); TermQuery termQuery = new TermQuery(allTerm); Weight weight = termQuery.Weight(IndexSearcher); TermScorer ts = new TermScorer(weight, indexReader.TermDocs(allTerm), IndexSearcher.Similarity, indexReader.Norms(FIELD)); Assert.IsTrue(ts.NextDoc() != DocIdSetIterator.NO_MORE_DOCS, "next did not return a doc"); Assert.IsTrue(ts.Score() == 1.6931472f, "score is not correct"); Assert.IsTrue(ts.NextDoc() != DocIdSetIterator.NO_MORE_DOCS, "next did not return a doc"); Assert.IsTrue(ts.Score() == 1.6931472f, "score is not correct"); Assert.IsTrue(ts.NextDoc() == DocIdSetIterator.NO_MORE_DOCS, "next returned a doc and it should not have"); } [TestMethod] public virtual void TestSkipTo() { Term allTerm = new Term(FIELD, "all"); TermQuery termQuery = new TermQuery(allTerm); Weight weight = termQuery.Weight(IndexSearcher); TermScorer ts = new TermScorer(weight, indexReader.TermDocs(allTerm), IndexSearcher.Similarity, indexReader.Norms(FIELD)); Assert.IsTrue(ts.Advance(3) != DocIdSetIterator.NO_MORE_DOCS, "Didn't skip"); //The next doc should be doc 5 Assert.IsTrue(ts.DocID() == 5, "doc should be number 5"); } private class TestHit { private void InitBlock(TestTermScorer enclosingInstance) { this._enclosingInstance = enclosingInstance; } private TestTermScorer _enclosingInstance; public TestTermScorer EnclosingInstance { get { return _enclosingInstance; } } public int Doc; public float Score; public TestHit(TestTermScorer enclosingInstance, int doc, float score) { InitBlock(enclosingInstance); this.Doc = doc; this.Score = score; } public override System.String ToString() { return "TestHit{" + "doc=" + Doc + ", score=" + Score + "}"; } } } }
namespace InControl { using UnityEngine; public class UnityInputDevice : InputDevice { static string[,] analogQueries; static string[,] buttonQueries; public const int MaxDevices = 10; public const int MaxButtons = 20; public const int MaxAnalogs = 20; internal int JoystickId { get; private set; } UnityInputDeviceProfileBase profile; public UnityInputDevice( UnityInputDeviceProfileBase deviceProfile ) : this( deviceProfile, 0, "" ) { } public UnityInputDevice( int joystickId, string joystickName ) : this( null, joystickId, joystickName ) { } public UnityInputDevice( UnityInputDeviceProfileBase deviceProfile, int joystickId, string joystickName ) { profile = deviceProfile; JoystickId = joystickId; if (joystickId != 0) { SortOrder = 100 + joystickId; } SetupAnalogQueries(); SetupButtonQueries(); AnalogSnapshot = null; if (IsKnown) { Name = profile.Name; Meta = profile.Meta; DeviceClass = profile.DeviceClass; DeviceStyle = profile.DeviceStyle; var analogMappingCount = profile.AnalogCount; for (var i = 0; i < analogMappingCount; i++) { var analogMapping = profile.AnalogMappings[i]; if (Utility.TargetIsAlias( analogMapping.Target )) { Debug.LogError( "Cannot map control \"" + analogMapping.Handle + "\" as InputControlType." + analogMapping.Target + " in profile \"" + deviceProfile.Name + "\" because this target is reserved as an alias. The mapping will be ignored." ); } else { var analogControl = AddControl( analogMapping.Target, analogMapping.Handle ); analogControl.Sensitivity = Mathf.Min( profile.Sensitivity, analogMapping.Sensitivity ); analogControl.LowerDeadZone = Mathf.Max( profile.LowerDeadZone, analogMapping.LowerDeadZone ); analogControl.UpperDeadZone = Mathf.Min( profile.UpperDeadZone, analogMapping.UpperDeadZone ); analogControl.Raw = analogMapping.Raw; analogControl.Passive = analogMapping.Passive; } } var buttonMappingCount = profile.ButtonCount; for (var i = 0; i < buttonMappingCount; i++) { var buttonMapping = profile.ButtonMappings[i]; if (Utility.TargetIsAlias( buttonMapping.Target )) { Debug.LogError( "Cannot map control \"" + buttonMapping.Handle + "\" as InputControlType." + buttonMapping.Target + " in profile \"" + deviceProfile.Name + "\" because this target is reserved as an alias. The mapping will be ignored." ); } else { var buttonControl = AddControl( buttonMapping.Target, buttonMapping.Handle ); buttonControl.Passive = buttonMapping.Passive; } } } else { Name = "Unknown Device"; Meta = "\"" + joystickName + "\""; for (var i = 0; i < NumUnknownButtons; i++) { AddControl( InputControlType.Button0 + i, "Button " + i ); } for (var i = 0; i < NumUnknownAnalogs; i++) { AddControl( InputControlType.Analog0 + i, "Analog " + i, 0.2f, 0.9f ); } } } public override void Update( ulong updateTick, float deltaTime ) { if (IsKnown) { var analogMappingCount = profile.AnalogCount; for (var i = 0; i < analogMappingCount; i++) { var analogMapping = profile.AnalogMappings[i]; var analogValue = analogMapping.Source.GetValue( this ); var targetControl = GetControl( analogMapping.Target ); if (!(analogMapping.IgnoreInitialZeroValue && targetControl.IsOnZeroTick && Utility.IsZero( analogValue ))) { var mappedValue = analogMapping.MapValue( analogValue ); targetControl.UpdateWithValue( mappedValue, updateTick, deltaTime ); } } var buttonMappingCount = profile.ButtonCount; for (var i = 0; i < buttonMappingCount; i++) { var buttonMapping = profile.ButtonMappings[i]; var buttonState = buttonMapping.Source.GetState( this ); UpdateWithState( buttonMapping.Target, buttonState, updateTick, deltaTime ); } } else { for (var i = 0; i < NumUnknownButtons; i++) { UpdateWithState( InputControlType.Button0 + i, ReadRawButtonState( i ), updateTick, deltaTime ); } for (var i = 0; i < NumUnknownAnalogs; i++) { UpdateWithValue( InputControlType.Analog0 + i, ReadRawAnalogValue( i ), updateTick, deltaTime ); } } } static void SetupAnalogQueries() { if (analogQueries == null) { analogQueries = new string[MaxDevices, MaxAnalogs]; for (var joystickId = 1; joystickId <= MaxDevices; joystickId++) { for (var analogId = 0; analogId < MaxAnalogs; analogId++) { analogQueries[joystickId - 1, analogId] = "joystick " + joystickId + " analog " + analogId; } } } } static void SetupButtonQueries() { if (buttonQueries == null) { buttonQueries = new string[MaxDevices, MaxButtons]; for (var joystickId = 1; joystickId <= MaxDevices; joystickId++) { for (var buttonId = 0; buttonId < MaxButtons; buttonId++) { buttonQueries[joystickId - 1, buttonId] = "joystick " + joystickId + " button " + buttonId; } } } } static string GetAnalogKey( int joystickId, int analogId ) { return analogQueries[joystickId - 1, analogId]; } static string GetButtonKey( int joystickId, int buttonId ) { return buttonQueries[joystickId - 1, buttonId]; } internal override bool ReadRawButtonState( int index ) { if (index < MaxButtons) { var buttonQuery = buttonQueries[JoystickId - 1, index]; return Input.GetKey( buttonQuery ); } return false; } internal override float ReadRawAnalogValue( int index ) { if (index < MaxAnalogs) { var analogQuery = analogQueries[JoystickId - 1, index]; return Input.GetAxisRaw( analogQuery ); } return 0.0f; } public override bool IsSupportedOnThisPlatform { get { return profile == null || profile.IsSupportedOnThisPlatform; } } public override bool IsKnown { get { return profile != null; } } internal override int NumUnknownButtons { get { return MaxButtons; } } internal override int NumUnknownAnalogs { get { return MaxAnalogs; } } } }
/* Copyright(c) 2009, Stefan Simek Copyright(c) 2016, Vladyslav Taranov MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Text; using NUnit.Framework; using TriAxis.RunSharp; namespace TriAxis.RunSharp.Tests { [TestFixture] public class _12_Delegates : TestBase { [Test] public void TestGenBookstore() { TestingFacade.GetTestsForGenerator(GenBookstore, @">>> GEN TriAxis.RunSharp.Tests.12_Delegates.GenBookstore === RUN TriAxis.RunSharp.Tests.12_Delegates.GenBookstore Paperback Book Titles: The C Programming Language The Unicode Standard 2.0 Dogbert's Clues for the Clueless Average Paperback Book Price: $23.97 <<< END TriAxis.RunSharp.Tests.12_Delegates.GenBookstore ").RunAll(); } // example based on the MSDN Delegates Sample (bookstore.cs) public static void GenBookstore(AssemblyGen ag) { var st = ag.StaticFactory; var exp = ag.ExpressionFactory; ITypeMapper m = ag.TypeMapper; TypeGen book, processBookDelegate, BookDBLocal; // A set of classes for handling a bookstore: using (ag.Namespace("Bookstore")) { // Describes a book in the book list: book = ag.Public.Struct("Book"); { FieldGen title = book.Public.Field(typeof(string), "Title"); // Title of the book. FieldGen author = book.Public.Field(typeof(string), "Author"); // Author of the book. FieldGen price = book.Public.Field(typeof(decimal), "Price"); // Price of the book. FieldGen paperback = book.Public.Field(typeof(bool), "Paperback"); // Is it paperback? CodeGen g = book.Public.Constructor() .Parameter(typeof(string), "title") .Parameter(typeof(string), "author") .Parameter(typeof(decimal), "price") .Parameter(typeof(bool), "paperBack"); { g.Assign(title, g.Arg("title")); g.Assign(author, g.Arg("author")); g.Assign(price, g.Arg("price")); g.Assign(paperback, g.Arg("paperBack")); } } // Declare a delegate type for processing a book: processBookDelegate = ag.Public.Delegate(typeof(void), "ProcessBookDelegate").Parameter(book, "book"); // Maintains a book database. BookDBLocal = ag.Public.Class("BookDB"); { // List of all books in the database: FieldGen list = BookDBLocal.Field(typeof(ArrayList), "list", exp.New(typeof(ArrayList))); // Add a book to the database: CodeGen g = BookDBLocal.Public.Method(typeof(void), "AddBook") .Parameter(typeof(string), "title") .Parameter(typeof(string), "author") .Parameter(typeof(decimal), "price") .Parameter(typeof(bool), "paperBack") ; { g.Invoke(list, "Add", exp.New(book, g.Arg("title"), g.Arg("author"), g.Arg("price"), g.Arg("paperBack"))); } // Call a passed-in delegate on each paperback book to process it: g = BookDBLocal.Public.Method(typeof(void), "ProcessPaperbackBooks").Parameter(processBookDelegate, "processBook"); { var b = g.ForEach(book, list); { g.If(b.Field("Paperback")); { g.InvokeDelegate(g.Arg("processBook"), b); } g.End(); } g.End(); } } } // Using the Bookstore classes: using (ag.Namespace("BookTestClient")) { // Class to total and average prices of books: TypeGen priceTotaller = ag.Class("PriceTotaller"); { FieldGen countBooks = priceTotaller.Field(typeof(int), "countBooks", 0); FieldGen priceBooks = priceTotaller.Field(typeof(decimal), "priceBooks", 0.0m); CodeGen g = priceTotaller.Internal.Method(typeof(void), "AddBookToTotal").Parameter(book, "book"); { g.AssignAdd(countBooks, 1); g.AssignAdd(priceBooks, g.Arg("book").Field("Price")); } g = priceTotaller.Internal.Method(typeof(decimal), "AveragePrice"); { g.Return(priceBooks / countBooks); } } // Class to test the book database: TypeGen test = ag.Class("Test"); { // Print the title of the book. CodeGen g = test.Static.Method(typeof(void), "PrintTitle").Parameter(book, "book"); { g.WriteLine(" {0}", g.Arg("book").Field("Title")); } // Initialize the book database with some test books: g = test.Static.Method(typeof(void), "AddBooks").Parameter(BookDBLocal, "bookDB"); { var bookDb = g.Arg("bookDB"); g.Invoke(bookDb, "AddBook", "The C Programming Language", "Brian W. Kernighan and Dennis M. Ritchie", 19.95m, true); g.Invoke(bookDb, "AddBook", "The Unicode Standard 2.0", "The Unicode Consortium", 39.95m, true); g.Invoke(bookDb, "AddBook", "The MS-DOS Encyclopedia", "Ray Duncan", 129.95m, false); g.Invoke(bookDb, "AddBook", "Dogbert's Clues for the Clueless", "Scott Adams", 12.00m, true); } // Execution starts here. g = test.Public.Static.Method(typeof(void), "Main"); { var bookDb = g.Local(exp.New(BookDBLocal)); // Initialize the database with some books: g.Invoke(test, "AddBooks", bookDb); // Print all the titles of paperbacks: g.WriteLine("Paperback Book Titles:"); // Create a new delegate object associated with the static // method Test.PrintTitle: g.Invoke(bookDb, "ProcessPaperbackBooks", (Operand)exp.NewDelegate(processBookDelegate, test, "PrintTitle")); // Get the average price of a paperback by using // a PriceTotaller object: var totaller = g.Local(exp.New(priceTotaller)); // Create a new delegate object associated with the nonstatic // method AddBookToTotal on the object totaller: g.Invoke(bookDb, "ProcessPaperbackBooks", (Operand)exp.NewDelegate(processBookDelegate, totaller, "AddBookToTotal")); g.WriteLine("Average Paperback Book Price: ${0:#.##}", totaller.Invoke("AveragePrice")); } } } } [Test] public void TestGenCompose() { TestingFacade.GetTestsForGenerator(GenCompose, @">>> GEN TriAxis.RunSharp.Tests.12_Delegates.GenCompose === RUN TriAxis.RunSharp.Tests.12_Delegates.GenCompose Invoking delegate a: Hello, A! Invoking delegate b: Goodbye, B! Invoking delegate c: Hello, C! Goodbye, C! Invoking delegate d: Goodbye, D! <<< END TriAxis.RunSharp.Tests.12_Delegates.GenCompose ").RunAll(); } // example based on the MSDN Delegates Sample (compose.cs) public static void GenCompose(AssemblyGen ag) { var st = ag.StaticFactory; var exp = ag.ExpressionFactory; TypeGen myDelegate = ag.Delegate(typeof(void), "MyDelegate").Parameter(typeof(string), "string"); TypeGen myClass = ag.Class("MyClass"); { CodeGen g = myClass.Public.Static.Method(typeof(void), "Hello").Parameter(typeof(string), "s"); { g.WriteLine(" Hello, {0}!", g.Arg("s")); } g = myClass.Public.Static.Method(typeof(void), "Goodbye").Parameter(typeof(string), "s"); { g.WriteLine(" Goodbye, {0}!", g.Arg("s")); } g = myClass.Public.Static.Method(typeof(void), "Main"); { ContextualOperand a = g.Local(), b = g.Local(), c = g.Local(), d = g.Local(); // Create the delegate object a that references // the method Hello: ITypeMapper typeMapper = ag.TypeMapper; g.Assign(a, exp.NewDelegate(myDelegate, myClass, "Hello")); // Create the delegate object b that references // the method Goodbye: ITypeMapper typeMapper1 = ag.TypeMapper; g.Assign(b, exp.NewDelegate(myDelegate, myClass, "Goodbye")); // The two delegates, a and b, are composed to form c, // which calls both methods in order: g.Assign(c, a + b); // Remove a from the composed delegate, leaving d, // which calls only the method Goodbye: g.Assign(d, c - a); g.WriteLine("Invoking delegate a:"); g.InvokeDelegate(a, "A"); g.WriteLine("Invoking delegate b:"); g.InvokeDelegate(b, "B"); g.WriteLine("Invoking delegate c:"); g.InvokeDelegate(c, "C"); g.WriteLine("Invoking delegate d:"); g.InvokeDelegate(d, "D"); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Metadata.ManagedReference { using System.Collections.Generic; using System.Reflection.Metadata; using Microsoft.CodeAnalysis; using Microsoft.DocAsCode.DataContracts.ManagedReference; public abstract class ReferenceItemVisitor : SymbolVisitor { public static readonly SymbolDisplayFormat ShortFormat = SimpleYamlModelGenerator.ShortFormat; public static readonly SymbolDisplayFormat QualifiedFormat = SimpleYamlModelGenerator.QualifiedFormat; public static readonly SymbolDisplayFormat ShortFormatWithoutGenericeParameter = ShortFormat .WithGenericsOptions(SymbolDisplayGenericsOptions.None); public static readonly SymbolDisplayFormat QualifiedFormatWithoutGenericeParameter = QualifiedFormat .WithGenericsOptions(SymbolDisplayGenericsOptions.None); protected ReferenceItemVisitor(ReferenceItem referenceItem) { ReferenceItem = referenceItem; } protected ReferenceItem ReferenceItem { get; private set; } public override void VisitNamedType(INamedTypeSymbol symbol) { if (symbol.IsTupleType) { symbol = symbol.TupleUnderlyingType ?? symbol; } if (symbol.IsGenericType) { if (symbol.IsUnboundGenericType) { AddLinkItems(symbol, true); } else { AddLinkItems(symbol.OriginalDefinition, false); AddBeginGenericParameter(); for (int i = 0; i < symbol.TypeArguments.Length; i++) { if (i > 0) { AddGenericParameterSeparator(); } symbol.TypeArguments[i].Accept(this); } AddEndGenericParameter(); } } else { AddLinkItems(symbol, true); } } protected abstract void AddLinkItems(INamedTypeSymbol symbol, bool withGenericeParameter); protected abstract void AddBeginGenericParameter(); protected abstract void AddGenericParameterSeparator(); protected abstract void AddEndGenericParameter(); } public class CSReferenceItemVisitor : ReferenceItemVisitor { private readonly bool _asOverload; public CSReferenceItemVisitor(ReferenceItem referenceItem, bool asOverload) : base(referenceItem) { _asOverload = asOverload; if (!referenceItem.Parts.ContainsKey(SyntaxLanguage.CSharp)) { referenceItem.Parts.Add(SyntaxLanguage.CSharp, new List<LinkItem>()); } } public override void VisitNamespace(INamespaceSymbol symbol) { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = NameVisitorCreator.GetCSharp(NameOptions.None).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified).GetName(symbol), IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0, }); } public override void VisitTypeParameter(ITypeParameterSymbol symbol) { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = symbol.Name, DisplayNamesWithType = symbol.Name, DisplayQualifiedNames = symbol.Name, }); } public override void VisitArrayType(IArrayTypeSymbol symbol) { symbol.ElementType.Accept(this); if (symbol.Rank == 1) { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = "[]", DisplayNamesWithType = "[]", DisplayQualifiedNames = "[]", }); } else { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = "[" + new string(',', symbol.Rank - 1) + "]", DisplayNamesWithType = "[" + new string(',', symbol.Rank - 1) + "]", DisplayQualifiedNames = "[" + new string(',', symbol.Rank - 1) + "]", }); } } public override void VisitPointerType(IPointerTypeSymbol symbol) { symbol.PointedAtType.Accept(this); ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = "*", DisplayNamesWithType = "*", DisplayQualifiedNames = "*", }); } public override void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = "delegate*", DisplayNamesWithType = "delegate*", DisplayQualifiedNames = "delegate*", }); var signature = symbol.Signature; if (signature.CallingConvention != SignatureCallingConvention.Default) { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = "unmanaged", DisplayNamesWithType = "unmanaged", DisplayQualifiedNames = "unmanaged", }); if ((signature.CallingConvention != SignatureCallingConvention.Unmanaged) || (signature.UnmanagedCallingConventionTypes.Length != 0)) { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = " [", DisplayNamesWithType = " [", DisplayQualifiedNames = " [", }); if (signature.UnmanagedCallingConventionTypes.Length != 0) { for (int i = 0; i < signature.UnmanagedCallingConventionTypes.Length; i++) { if (i > 0) { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = ", ", DisplayNamesWithType = ", ", DisplayQualifiedNames = ", ", }); } signature.UnmanagedCallingConventionTypes[i].Accept(this); } } else { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = signature.CallingConvention.ToString(), DisplayNamesWithType = signature.CallingConvention.ToString(), DisplayQualifiedNames = signature.CallingConvention.ToString(), }); } ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = "]", DisplayNamesWithType = "]", DisplayQualifiedNames = "]", }); } } ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = "<", DisplayNamesWithType = "<", DisplayQualifiedNames = "<", }); foreach (var parameter in signature.Parameters) { parameter.Type.Accept(this); ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = ", ", DisplayNamesWithType = ", ", DisplayQualifiedNames = ", ", }); } signature.ReturnType.Accept(this); ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = ">", DisplayNamesWithType = ">", DisplayQualifiedNames = ">", }); } public override void VisitMethod(IMethodSymbol symbol) { var id = _asOverload ? VisitorHelper.GetOverloadId(symbol.OriginalDefinition) : VisitorHelper.GetId(symbol.OriginalDefinition); ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = NameVisitorCreator.GetCSharp(_asOverload ? NameOptions.WithTypeGenericParameter : NameOptions.WithGenericParameter).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType | (_asOverload ? NameOptions.WithTypeGenericParameter : NameOptions.WithGenericParameter)).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified | (_asOverload ? NameOptions.WithTypeGenericParameter : NameOptions.WithGenericParameter)).GetName(symbol), Name = id, IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0, }); if (_asOverload) { return; } ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = "(", DisplayNamesWithType = "(", DisplayQualifiedNames = "(", }); for (int i = 0; i < symbol.Parameters.Length; i++) { if (i > 0) { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = ", ", DisplayNamesWithType = ", ", DisplayQualifiedNames = ", ", }); } symbol.Parameters[i].Type.Accept(this); } ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = ")", DisplayNamesWithType = ")", DisplayQualifiedNames = ")", }); } public override void VisitProperty(IPropertySymbol symbol) { var id = _asOverload ? VisitorHelper.GetOverloadId(symbol.OriginalDefinition) : VisitorHelper.GetId(symbol.OriginalDefinition); ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = NameVisitorCreator.GetCSharp(NameOptions.WithTypeGenericParameter).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType | NameOptions.WithTypeGenericParameter).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified | NameOptions.WithTypeGenericParameter).GetName(symbol), Name = id, IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0, }); if (symbol.Parameters.Length > 0 && !_asOverload) { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = "[", DisplayNamesWithType = "[", DisplayQualifiedNames = "[", }); for (int i = 0; i < symbol.Parameters.Length; i++) { if (i > 0) { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = ", ", DisplayNamesWithType = ", ", DisplayQualifiedNames = ", ", }); } symbol.Parameters[i].Type.Accept(this); } ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = "]", DisplayNamesWithType = "]", DisplayQualifiedNames = "]", }); } } public override void VisitEvent(IEventSymbol symbol) { var id = VisitorHelper.GetId(symbol.OriginalDefinition); ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = NameVisitorCreator.GetCSharp(NameOptions.WithTypeGenericParameter).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType | NameOptions.WithTypeGenericParameter).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified | NameOptions.WithTypeGenericParameter).GetName(symbol), Name = id, IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0, }); } public override void VisitField(IFieldSymbol symbol) { var id = VisitorHelper.GetId(symbol.OriginalDefinition); ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = NameVisitorCreator.GetCSharp(NameOptions.WithTypeGenericParameter).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType | NameOptions.WithTypeGenericParameter).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified | NameOptions.WithTypeGenericParameter).GetName(symbol), Name = id, IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0, }); } public override void VisitDynamicType(IDynamicTypeSymbol symbol) { var id = VisitorHelper.GetId(symbol.OriginalDefinition); ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = NameVisitorCreator.GetCSharp(NameOptions.None).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified).GetName(symbol), Name = id, }); } protected override void AddBeginGenericParameter() { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = "<", DisplayNamesWithType = "<", DisplayQualifiedNames = "<", }); } protected override void AddEndGenericParameter() { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = ">", DisplayNamesWithType = ">", DisplayQualifiedNames = ">", }); } protected override void AddGenericParameterSeparator() { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = ", ", DisplayNamesWithType = ", ", DisplayQualifiedNames = ", ", }); } protected override void AddLinkItems(INamedTypeSymbol symbol, bool withGenericeParameter) { var id = VisitorHelper.GetId(symbol); if (withGenericeParameter) { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = NameVisitorCreator.GetCSharp(NameOptions.WithGenericParameter).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType | NameOptions.WithGenericParameter).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified | NameOptions.WithGenericParameter).GetName(symbol), Name = id, IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0, }); } else { ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem { DisplayName = NameVisitorCreator.GetCSharp(NameOptions.None).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified).GetName(symbol), Name = id, IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0, }); } } } public class VBReferenceItemVisitor : ReferenceItemVisitor { private readonly bool _asOverload; public VBReferenceItemVisitor(ReferenceItem referenceItem, bool asOverload) : base(referenceItem) { _asOverload = asOverload; if (!referenceItem.Parts.ContainsKey(SyntaxLanguage.VB)) { referenceItem.Parts.Add(SyntaxLanguage.VB, new List<LinkItem>()); } } public override void VisitNamespace(INamespaceSymbol symbol) { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = NameVisitorCreator.GetVB(NameOptions.None).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified).GetName(symbol), }); } public override void VisitTypeParameter(ITypeParameterSymbol symbol) { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = symbol.Name, DisplayNamesWithType = symbol.Name, DisplayQualifiedNames = symbol.Name, }); } public override void VisitArrayType(IArrayTypeSymbol symbol) { symbol.ElementType.Accept(this); if (symbol.Rank == 1) { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = "()", DisplayNamesWithType = "()", DisplayQualifiedNames = "()", }); } else { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = "(" + new string(',', symbol.Rank - 1) + ")", DisplayNamesWithType = "(" + new string(',', symbol.Rank - 1) + ")", DisplayQualifiedNames = "(" + new string(',', symbol.Rank - 1) + ")", }); } } public override void VisitPointerType(IPointerTypeSymbol symbol) { symbol.PointedAtType.Accept(this); ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = "*", DisplayNamesWithType = "*", DisplayQualifiedNames = "*", }); } public override void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = "delegate*", DisplayNamesWithType = "delegate*", DisplayQualifiedNames = "delegate*", }); var signature = symbol.Signature; if (signature.CallingConvention != SignatureCallingConvention.Default) { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = "unmanaged", DisplayNamesWithType = "unmanaged", DisplayQualifiedNames = "unmanaged", }); if ((signature.CallingConvention != SignatureCallingConvention.Unmanaged) || (signature.UnmanagedCallingConventionTypes.Length != 0)) { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = " [", DisplayNamesWithType = " [", DisplayQualifiedNames = " [", }); if (signature.UnmanagedCallingConventionTypes.Length != 0) { for (int i = 0; i < signature.UnmanagedCallingConventionTypes.Length; i++) { if (i > 0) { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = ", ", DisplayNamesWithType = ", ", DisplayQualifiedNames = ", ", }); } signature.UnmanagedCallingConventionTypes[i].Accept(this); } } else { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = signature.CallingConvention.ToString(), DisplayNamesWithType = signature.CallingConvention.ToString(), DisplayQualifiedNames = signature.CallingConvention.ToString(), }); } ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = "]", DisplayNamesWithType = "]", DisplayQualifiedNames = "]", }); } } ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = "<", DisplayNamesWithType = "<", DisplayQualifiedNames = "<", }); foreach (var parameter in signature.Parameters) { parameter.Type.Accept(this); ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = ", ", DisplayNamesWithType = ", ", DisplayQualifiedNames = ", ", }); } signature.ReturnType.Accept(this); ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = ">", DisplayNamesWithType = ">", DisplayQualifiedNames = ">", }); } public override void VisitMethod(IMethodSymbol symbol) { var id = _asOverload ? VisitorHelper.GetOverloadId(symbol.OriginalDefinition) : VisitorHelper.GetId(symbol.OriginalDefinition); ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = NameVisitorCreator.GetVB(_asOverload ? NameOptions.WithTypeGenericParameter : NameOptions.WithGenericParameter).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType | (_asOverload ? NameOptions.WithTypeGenericParameter : NameOptions.WithGenericParameter)).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified | (_asOverload ? NameOptions.WithTypeGenericParameter : NameOptions.WithGenericParameter)).GetName(symbol), Name = id, IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0, }); if (_asOverload) { return; } ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = "(", DisplayNamesWithType = "(", DisplayQualifiedNames = "(", }); for (int i = 0; i < symbol.Parameters.Length; i++) { if (i > 0) { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = ", ", DisplayNamesWithType = ", ", DisplayQualifiedNames = ", ", }); } symbol.Parameters[i].Type.Accept(this); } ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = ")", DisplayNamesWithType = ")", DisplayQualifiedNames = ")", }); } public override void VisitProperty(IPropertySymbol symbol) { var id = _asOverload ? VisitorHelper.GetOverloadId(symbol.OriginalDefinition) : VisitorHelper.GetId(symbol.OriginalDefinition); ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = NameVisitorCreator.GetVB(NameOptions.WithTypeGenericParameter).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType | NameOptions.WithTypeGenericParameter).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified | NameOptions.WithTypeGenericParameter).GetName(symbol), Name = id, IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0, }); if (symbol.Parameters.Length > 0 && !_asOverload) { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = "(", DisplayNamesWithType = "(", DisplayQualifiedNames = "(", }); for (int i = 0; i < symbol.Parameters.Length; i++) { if (i > 0) { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = ", ", DisplayNamesWithType = ", ", DisplayQualifiedNames = ", ", }); } symbol.Parameters[i].Type.Accept(this); } ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = ")", DisplayNamesWithType = ")", DisplayQualifiedNames = ")", }); } } public override void VisitEvent(IEventSymbol symbol) { var id = VisitorHelper.GetId(symbol.OriginalDefinition); ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = NameVisitorCreator.GetVB(NameOptions.WithTypeGenericParameter).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType | NameOptions.WithTypeGenericParameter).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified | NameOptions.WithTypeGenericParameter).GetName(symbol), Name = id, IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0, }); } public override void VisitField(IFieldSymbol symbol) { var id = VisitorHelper.GetId(symbol.OriginalDefinition); ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = NameVisitorCreator.GetVB(NameOptions.WithTypeGenericParameter).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType | NameOptions.WithTypeGenericParameter).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified | NameOptions.WithTypeGenericParameter).GetName(symbol), Name = id, IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0, }); } protected override void AddBeginGenericParameter() { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = "(Of ", DisplayNamesWithType = "(Of ", DisplayQualifiedNames = "(Of ", }); } protected override void AddEndGenericParameter() { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = ")", DisplayNamesWithType = ")", DisplayQualifiedNames = ")", }); } protected override void AddGenericParameterSeparator() { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = ", ", DisplayNamesWithType = ", ", DisplayQualifiedNames = ", ", }); } protected override void AddLinkItems(INamedTypeSymbol symbol, bool withGenericParameter) { var id = VisitorHelper.GetId(symbol); if (withGenericParameter) { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = NameVisitorCreator.GetVB(NameOptions.WithGenericParameter).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType | NameOptions.WithGenericParameter).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified | NameOptions.WithGenericParameter).GetName(symbol), Name = id, IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0, }); } else { ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem { DisplayName = NameVisitorCreator.GetVB(NameOptions.None).GetName(symbol), DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType).GetName(symbol), DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified).GetName(symbol), Name = id, IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0, }); } } } }
using OpenKh.Common; using OpenKh.Kh2; using OpenKh.Kh2.Extensions; using OpenKh.Tools.Common.Wpf; using OpenKh.Tools.Kh2BattleEditor.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Windows; using Xe.Tools; using Xe.Tools.Wpf.Commands; using Xe.Tools.Wpf.Dialogs; namespace OpenKh.Tools.Kh2BattleEditor.ViewModels { public class MainViewModel : BaseNotifyPropertyChanged { private static readonly string ApplicationName = Utilities.GetApplicationName(); private Window Window => Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive); private static readonly List<FileDialogFilter> BattleFilter = FileDialogFilterComposer.Compose() .AddExtensions("00battle", "bin", "bar").AddAllFiles(); private string _fileName; private IEnumerable<Bar.Entry> _battleItems; private EnmpViewModel _enmp; private FmlvViewModel _fmlv; private BonsViewModel _bons; private PrztViewModel _przt; private LvupViewModel _lvup; private SumnViewModel _sumn; private BtlvViewModel _btlv; private PlrpViewModel _plrp; public string Title => $"{FileName ?? "untitled"} | {ApplicationName}"; private string FileName { get => _fileName; set { _fileName = value; OnPropertyChanged(nameof(Title)); } } public RelayCommand OpenCommand { get; } public RelayCommand SaveCommand { get; } public RelayCommand SaveAsCommand { get; } public RelayCommand ExitCommand { get; } public RelayCommand AboutCommand { get; } public EnmpViewModel Enmp { get => _enmp; private set { _enmp = value; OnPropertyChanged();} } public FmlvViewModel Fmlv { get => _fmlv; private set { _fmlv = value; OnPropertyChanged(); } } public BonsViewModel Bons { get => _bons; private set { _bons = value; OnPropertyChanged(); } } public PrztViewModel Przt { get => _przt; private set { _przt = value; OnPropertyChanged(); } } public LvupViewModel Lvup { get => _lvup; private set { _lvup = value; OnPropertyChanged(); } } public SumnViewModel Sumn { get => _sumn; private set { _sumn = value; OnPropertyChanged(); } } public BtlvViewModel Btlv { get => _btlv; private set { _btlv = value; OnPropertyChanged(); } } public PlrpViewModel Plrp { get => _plrp; private set { _plrp = value; OnPropertyChanged(); } } public MainViewModel() { OpenCommand = new RelayCommand(x => { FileDialog.OnOpen(fileName => { OpenFile(fileName); }, BattleFilter); }, x => true); SaveCommand = new RelayCommand(x => { if (!string.IsNullOrEmpty(FileName)) { SaveFile(FileName, FileName); } else { SaveAsCommand.Execute(x); } }, x => true); SaveAsCommand = new RelayCommand(x => { FileDialog.OnSave(fileName => { SaveFile(FileName, fileName); FileName = fileName; }, BattleFilter); }, x => true); ExitCommand = new RelayCommand(x => { Window.Close(); }, x => true); AboutCommand = new RelayCommand(x => { new AboutDialog(Assembly.GetExecutingAssembly()).ShowDialog(); }, x => true); CreateBattleItems(); } public bool OpenFile(string fileName) => File.OpenRead(fileName).Using(stream => { if (!Bar.IsValid(stream)) { MessageBox.Show(Window, $"{Path.GetFileName(fileName)} is not a valid BAR file.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return false; } var items = Bar.Read(stream); if (!Is00battle(items)) { MessageBox.Show(Window, $"{Path.GetFileName(fileName)} does not appear to be a valid 00battle.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return false; } LoadBattleItems(items); FileName = fileName; return true; }); public void SaveFile(string previousFileName, string fileName) { File.Create(fileName).Using(stream => { SaveBattleItems(); Bar.Write(stream, _battleItems); }); } private bool Is00battle(List<Bar.Entry> items) => items.Any(x => new[] { "atkp", "enmp", "fmlv", "lvpm", "bons", "przt", "lvup", "sumn", "btlv", "plrp", }.Contains(x.Name)); private void CreateBattleItems() { _battleItems = new Bar.Entry[0]; Enmp = GetDefaultBattleViewModelInstance<EnmpViewModel>(); Fmlv = GetDefaultBattleViewModelInstance<FmlvViewModel>(); Bons = GetDefaultBattleViewModelInstance<BonsViewModel>(); Przt = GetDefaultBattleViewModelInstance<PrztViewModel>(); Lvup = GetDefaultBattleViewModelInstance<LvupViewModel>(); Sumn = GetDefaultBattleViewModelInstance<SumnViewModel>(); Btlv = GetDefaultBattleViewModelInstance<BtlvViewModel>(); Plrp = GetDefaultBattleViewModelInstance<PlrpViewModel>(); } private void LoadBattleItems(IEnumerable<Bar.Entry> entries) { _battleItems = entries; Enmp = GetBattleViewModelInstance<EnmpViewModel>(_battleItems); Fmlv = GetBattleViewModelInstance<FmlvViewModel>(_battleItems); Bons = GetBattleViewModelInstance<BonsViewModel>(_battleItems); Przt = GetBattleViewModelInstance<PrztViewModel>(_battleItems); Lvup = GetBattleViewModelInstance<LvupViewModel>(_battleItems); Sumn = GetBattleViewModelInstance<SumnViewModel>(_battleItems); Btlv = GetBattleViewModelInstance<BtlvViewModel>(_battleItems); Plrp = GetBattleViewModelInstance<PlrpViewModel>(_battleItems); } private void SaveBattleItems() { _battleItems = SaveBattleItem(_battleItems, Enmp); _battleItems = SaveBattleItem(_battleItems, Fmlv); _battleItems = SaveBattleItem(_battleItems, Bons); _battleItems = SaveBattleItem(_battleItems, Przt); _battleItems = SaveBattleItem(_battleItems, Lvup); _battleItems = SaveBattleItem(_battleItems, Sumn); _battleItems = SaveBattleItem(_battleItems, Btlv); _battleItems = SaveBattleItem(_battleItems, Plrp); } private IEnumerable<Bar.Entry> SaveBattleItem(IEnumerable<Bar.Entry> entries, IBattleGetChanges battleGetChanges) => entries.ForEntry(Bar.EntryType.List, battleGetChanges.EntryName, 0, entry => entry.Stream = battleGetChanges.CreateStream()); private T GetBattleViewModelInstance<T>(IEnumerable<Bar.Entry> entries) where T : IBattleGetChanges => (T)Activator.CreateInstance(typeof(T), entries); private T GetDefaultBattleViewModelInstance<T>() where T : IBattleGetChanges => Activator.CreateInstance<T>(); } }
/* * Copyright 2021 Google LLC All Rights Reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file or at * https://developers.google.com/open-source/licenses/bsd */ // <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/monitoring.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Api { /// <summary>Holder for reflection information generated from google/api/monitoring.proto</summary> public static partial class MonitoringReflection { #region Descriptor /// <summary>File descriptor for google/api/monitoring.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static MonitoringReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chtnb29nbGUvYXBpL21vbml0b3JpbmcucHJvdG8SCmdvb2dsZS5hcGki7AEK", "Ck1vbml0b3JpbmcSSwoVcHJvZHVjZXJfZGVzdGluYXRpb25zGAEgAygLMiwu", "Z29vZ2xlLmFwaS5Nb25pdG9yaW5nLk1vbml0b3JpbmdEZXN0aW5hdGlvbhJL", "ChVjb25zdW1lcl9kZXN0aW5hdGlvbnMYAiADKAsyLC5nb29nbGUuYXBpLk1v", "bml0b3JpbmcuTW9uaXRvcmluZ0Rlc3RpbmF0aW9uGkQKFU1vbml0b3JpbmdE", "ZXN0aW5hdGlvbhIaChJtb25pdG9yZWRfcmVzb3VyY2UYASABKAkSDwoHbWV0", "cmljcxgCIAMoCUJxCg5jb20uZ29vZ2xlLmFwaUIPTW9uaXRvcmluZ1Byb3Rv", "UAFaRWdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvYXBp", "L3NlcnZpY2Vjb25maWc7c2VydmljZWNvbmZpZ6ICBEdBUEliBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Monitoring), global::Google.Api.Monitoring.Parser, new[]{ "ProducerDestinations", "ConsumerDestinations" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Monitoring.Types.MonitoringDestination), global::Google.Api.Monitoring.Types.MonitoringDestination.Parser, new[]{ "MonitoredResource", "Metrics" }, null, null, null, null)}) })); } #endregion } #region Messages /// <summary> /// Monitoring configuration of the service. /// /// The example below shows how to configure monitored resources and metrics /// for monitoring. In the example, a monitored resource and two metrics are /// defined. The `library.googleapis.com/book/returned_count` metric is sent /// to both producer and consumer projects, whereas the /// `library.googleapis.com/book/num_overdue` metric is only sent to the /// consumer project. /// /// monitored_resources: /// - type: library.googleapis.com/Branch /// display_name: "Library Branch" /// description: "A branch of a library." /// launch_stage: GA /// labels: /// - key: resource_container /// description: "The Cloud container (ie. project id) for the Branch." /// - key: location /// description: "The location of the library branch." /// - key: branch_id /// description: "The id of the branch." /// metrics: /// - name: library.googleapis.com/book/returned_count /// display_name: "Books Returned" /// description: "The count of books that have been returned." /// launch_stage: GA /// metric_kind: DELTA /// value_type: INT64 /// unit: "1" /// labels: /// - key: customer_id /// description: "The id of the customer." /// - name: library.googleapis.com/book/num_overdue /// display_name: "Books Overdue" /// description: "The current number of overdue books." /// launch_stage: GA /// metric_kind: GAUGE /// value_type: INT64 /// unit: "1" /// labels: /// - key: customer_id /// description: "The id of the customer." /// monitoring: /// producer_destinations: /// - monitored_resource: library.googleapis.com/Branch /// metrics: /// - library.googleapis.com/book/returned_count /// consumer_destinations: /// - monitored_resource: library.googleapis.com/Branch /// metrics: /// - library.googleapis.com/book/returned_count /// - library.googleapis.com/book/num_overdue /// </summary> public sealed partial class Monitoring : pb::IMessage<Monitoring> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Monitoring> _parser = new pb::MessageParser<Monitoring>(() => new Monitoring()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Monitoring> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.MonitoringReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Monitoring() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Monitoring(Monitoring other) : this() { producerDestinations_ = other.producerDestinations_.Clone(); consumerDestinations_ = other.consumerDestinations_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Monitoring Clone() { return new Monitoring(this); } /// <summary>Field number for the "producer_destinations" field.</summary> public const int ProducerDestinationsFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Api.Monitoring.Types.MonitoringDestination> _repeated_producerDestinations_codec = pb::FieldCodec.ForMessage(10, global::Google.Api.Monitoring.Types.MonitoringDestination.Parser); private readonly pbc::RepeatedField<global::Google.Api.Monitoring.Types.MonitoringDestination> producerDestinations_ = new pbc::RepeatedField<global::Google.Api.Monitoring.Types.MonitoringDestination>(); /// <summary> /// Monitoring configurations for sending metrics to the producer project. /// There can be multiple producer destinations. A monitored resource type may /// appear in multiple monitoring destinations if different aggregations are /// needed for different sets of metrics associated with that monitored /// resource type. A monitored resource and metric pair may only be used once /// in the Monitoring configuration. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.Monitoring.Types.MonitoringDestination> ProducerDestinations { get { return producerDestinations_; } } /// <summary>Field number for the "consumer_destinations" field.</summary> public const int ConsumerDestinationsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Api.Monitoring.Types.MonitoringDestination> _repeated_consumerDestinations_codec = pb::FieldCodec.ForMessage(18, global::Google.Api.Monitoring.Types.MonitoringDestination.Parser); private readonly pbc::RepeatedField<global::Google.Api.Monitoring.Types.MonitoringDestination> consumerDestinations_ = new pbc::RepeatedField<global::Google.Api.Monitoring.Types.MonitoringDestination>(); /// <summary> /// Monitoring configurations for sending metrics to the consumer project. /// There can be multiple consumer destinations. A monitored resource type may /// appear in multiple monitoring destinations if different aggregations are /// needed for different sets of metrics associated with that monitored /// resource type. A monitored resource and metric pair may only be used once /// in the Monitoring configuration. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.Monitoring.Types.MonitoringDestination> ConsumerDestinations { get { return consumerDestinations_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Monitoring); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Monitoring other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!producerDestinations_.Equals(other.producerDestinations_)) return false; if(!consumerDestinations_.Equals(other.consumerDestinations_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= producerDestinations_.GetHashCode(); hash ^= consumerDestinations_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else producerDestinations_.WriteTo(output, _repeated_producerDestinations_codec); consumerDestinations_.WriteTo(output, _repeated_consumerDestinations_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { producerDestinations_.WriteTo(ref output, _repeated_producerDestinations_codec); consumerDestinations_.WriteTo(ref output, _repeated_consumerDestinations_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += producerDestinations_.CalculateSize(_repeated_producerDestinations_codec); size += consumerDestinations_.CalculateSize(_repeated_consumerDestinations_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Monitoring other) { if (other == null) { return; } producerDestinations_.Add(other.producerDestinations_); consumerDestinations_.Add(other.consumerDestinations_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { producerDestinations_.AddEntriesFrom(input, _repeated_producerDestinations_codec); break; } case 18: { consumerDestinations_.AddEntriesFrom(input, _repeated_consumerDestinations_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { producerDestinations_.AddEntriesFrom(ref input, _repeated_producerDestinations_codec); break; } case 18: { consumerDestinations_.AddEntriesFrom(ref input, _repeated_consumerDestinations_codec); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the Monitoring message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Configuration of a specific monitoring destination (the producer project /// or the consumer project). /// </summary> public sealed partial class MonitoringDestination : pb::IMessage<MonitoringDestination> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<MonitoringDestination> _parser = new pb::MessageParser<MonitoringDestination>(() => new MonitoringDestination()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MonitoringDestination> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.Monitoring.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MonitoringDestination() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MonitoringDestination(MonitoringDestination other) : this() { monitoredResource_ = other.monitoredResource_; metrics_ = other.metrics_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MonitoringDestination Clone() { return new MonitoringDestination(this); } /// <summary>Field number for the "monitored_resource" field.</summary> public const int MonitoredResourceFieldNumber = 1; private string monitoredResource_ = ""; /// <summary> /// The monitored resource type. The type must be defined in /// [Service.monitored_resources][google.api.Service.monitored_resources] section. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string MonitoredResource { get { return monitoredResource_; } set { monitoredResource_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "metrics" field.</summary> public const int MetricsFieldNumber = 2; private static readonly pb::FieldCodec<string> _repeated_metrics_codec = pb::FieldCodec.ForString(18); private readonly pbc::RepeatedField<string> metrics_ = new pbc::RepeatedField<string>(); /// <summary> /// Types of the metrics to report to this monitoring destination. /// Each type must be defined in [Service.metrics][google.api.Service.metrics] section. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> Metrics { get { return metrics_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MonitoringDestination); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MonitoringDestination other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (MonitoredResource != other.MonitoredResource) return false; if(!metrics_.Equals(other.metrics_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (MonitoredResource.Length != 0) hash ^= MonitoredResource.GetHashCode(); hash ^= metrics_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (MonitoredResource.Length != 0) { output.WriteRawTag(10); output.WriteString(MonitoredResource); } metrics_.WriteTo(output, _repeated_metrics_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (MonitoredResource.Length != 0) { output.WriteRawTag(10); output.WriteString(MonitoredResource); } metrics_.WriteTo(ref output, _repeated_metrics_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (MonitoredResource.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MonitoredResource); } size += metrics_.CalculateSize(_repeated_metrics_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MonitoringDestination other) { if (other == null) { return; } if (other.MonitoredResource.Length != 0) { MonitoredResource = other.MonitoredResource; } metrics_.Add(other.metrics_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { MonitoredResource = input.ReadString(); break; } case 18: { metrics_.AddEntriesFrom(input, _repeated_metrics_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { MonitoredResource = input.ReadString(); break; } case 18: { metrics_.AddEntriesFrom(ref input, _repeated_metrics_codec); break; } } } } #endif } } #endregion } #endregion } #endregion Designer generated code
// *********************************************************************** // Copyright (c) 2009 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; namespace NUnit.Framework.Constraints { /// <summary> /// ConstraintExpression represents a compound constraint in the /// process of being constructed from a series of syntactic elements. /// /// Individual elements are appended to the expression as they are /// reognized. Once an actual Constraint is appended, the expression /// returns a resolvable Constraint. /// </summary> public class ConstraintExpression : ConstraintExpressionBase { /// <summary> /// Initializes a new instance of the <see cref="T:ConstraintExpression"/> class. /// </summary> public ConstraintExpression() { } /// <summary> /// Initializes a new instance of the <see cref="T:ConstraintExpression"/> /// class passing in a ConstraintBuilder, which may be pre-populated. /// </summary> /// <param name="builder">The builder.</param> public ConstraintExpression(ConstraintBuilder builder) : base( builder ) { } #region Not /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public ConstraintExpression Not { get { return this.Append(new NotOperator()); } } /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public ConstraintExpression No { get { return this.Append(new NotOperator()); } } #endregion #region All /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them succeed. /// </summary> public ConstraintExpression All { get { return this.Append(new AllOperator()); } } #endregion #region Some /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if at least one of them succeeds. /// </summary> public ConstraintExpression Some { get { return this.Append(new SomeOperator()); } } #endregion #region None /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them fail. /// </summary> public ConstraintExpression None { get { return this.Append(new NoneOperator()); } } #endregion #region Exactly(n) /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding only if a specified number of them succeed. /// </summary> public ConstraintExpression Exactly(int expectedCount) { return this.Append(new ExactCountOperator(expectedCount)); } #endregion #region Property /// <summary> /// Returns a new PropertyConstraintExpression, which will either /// test for the existence of the named property on the object /// being tested or apply any following constraint to that property. /// </summary> public ResolvableConstraintExpression Property(string name) { return this.Append(new PropOperator(name)); } #endregion #region Length /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Length property of the object being tested. /// </summary> public ResolvableConstraintExpression Length { get { return Property("Length"); } } #endregion #region Count /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Count property of the object being tested. /// </summary> public ResolvableConstraintExpression Count { get { return Property("Count"); } } #endregion #region Message /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Message property of the object being tested. /// </summary> public ResolvableConstraintExpression Message { get { return Property("Message"); } } #endregion #region InnerException /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the InnerException property of the object being tested. /// </summary> public ResolvableConstraintExpression InnerException { get { return Property("InnerException"); } } #endregion #region Attribute /// <summary> /// Returns a new AttributeConstraint checking for the /// presence of a particular attribute on an object. /// </summary> public ResolvableConstraintExpression Attribute(Type expectedType) { return this.Append(new AttributeOperator(expectedType)); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a new AttributeConstraint checking for the /// presence of a particular attribute on an object. /// </summary> public ResolvableConstraintExpression Attribute<T>() { return Attribute(typeof(T)); } #endif #endregion #region With /// <summary> /// With is currently a NOP - reserved for future use. /// </summary> public ConstraintExpression With { get { return this.Append(new WithOperator()); } } #endregion #region Matches /// <summary> /// Returns the constraint provided as an argument - used to allow custom /// custom constraints to easily participate in the syntax. /// </summary> public Constraint Matches(Constraint constraint) { return this.Append(constraint); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns the constraint provided as an argument - used to allow custom /// custom constraints to easily participate in the syntax. /// </summary> public Constraint Matches<T>(Predicate<T> predicate) { return this.Append(new PredicateConstraint<T>(predicate)); } #endif #endregion #region Null /// <summary> /// Returns a constraint that tests for null /// </summary> public NullConstraint Null { get { return (NullConstraint)this.Append(new NullConstraint()); } } #endregion #region True /// <summary> /// Returns a constraint that tests for True /// </summary> public TrueConstraint True { get { return (TrueConstraint)this.Append(new TrueConstraint()); } } #endregion #region False /// <summary> /// Returns a constraint that tests for False /// </summary> public FalseConstraint False { get { return (FalseConstraint)this.Append(new FalseConstraint()); } } #endregion #region Positive /// <summary> /// Returns a constraint that tests for a positive value /// </summary> public GreaterThanConstraint Positive { get { return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(0)); } } #endregion #region Negative /// <summary> /// Returns a constraint that tests for a negative value /// </summary> public LessThanConstraint Negative { get { return (LessThanConstraint)this.Append(new LessThanConstraint(0)); } } #endregion #region NaN /// <summary> /// Returns a constraint that tests for NaN /// </summary> public NaNConstraint NaN { get { return (NaNConstraint)this.Append(new NaNConstraint()); } } #endregion #region Empty /// <summary> /// Returns a constraint that tests for empty /// </summary> public EmptyConstraint Empty { get { return (EmptyConstraint)this.Append(new EmptyConstraint()); } } #endregion #region Unique /// <summary> /// Returns a constraint that tests whether a collection /// contains all unique items. /// </summary> public UniqueItemsConstraint Unique { get { return (UniqueItemsConstraint)this.Append(new UniqueItemsConstraint()); } } #endregion #region BinarySerializable #if !NETCF && !SILVERLIGHT /// <summary> /// Returns a constraint that tests whether an object graph is serializable in binary format. /// </summary> public BinarySerializableConstraint BinarySerializable { get { return (BinarySerializableConstraint)this.Append(new BinarySerializableConstraint()); } } #endif #endregion #region XmlSerializable #if !SILVERLIGHT /// <summary> /// Returns a constraint that tests whether an object graph is serializable in xml format. /// </summary> public XmlSerializableConstraint XmlSerializable { get { return (XmlSerializableConstraint)this.Append(new XmlSerializableConstraint()); } } #endif #endregion #region EqualTo /// <summary> /// Returns a constraint that tests two items for equality /// </summary> public EqualConstraint EqualTo(object expected) { return (EqualConstraint)this.Append(new EqualConstraint(expected)); } #endregion #region SameAs /// <summary> /// Returns a constraint that tests that two references are the same object /// </summary> public SameAsConstraint SameAs(object expected) { return (SameAsConstraint)this.Append(new SameAsConstraint(expected)); } #endregion #region GreaterThan /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than the suppled argument /// </summary> public GreaterThanConstraint GreaterThan(object expected) { return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(expected)); } #endregion #region GreaterThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the suppled argument /// </summary> public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected) { return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected)); } /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the suppled argument /// </summary> public GreaterThanOrEqualConstraint AtLeast(object expected) { return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected)); } #endregion #region LessThan /// <summary> /// Returns a constraint that tests whether the /// actual value is less than the suppled argument /// </summary> public LessThanConstraint LessThan(object expected) { return (LessThanConstraint)this.Append(new LessThanConstraint(expected)); } #endregion #region LessThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the suppled argument /// </summary> public LessThanOrEqualConstraint LessThanOrEqualTo(object expected) { return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected)); } /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the suppled argument /// </summary> public LessThanOrEqualConstraint AtMost(object expected) { return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected)); } #endregion #region TypeOf /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public ExactTypeConstraint TypeOf(Type expectedType) { return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(expectedType)); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public ExactTypeConstraint TypeOf<T>() { return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(typeof(T))); } #endif #endregion #region InstanceOf /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public InstanceOfTypeConstraint InstanceOf(Type expectedType) { return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(expectedType)); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public InstanceOfTypeConstraint InstanceOf<T>() { return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(typeof(T))); } #endif #endregion #region AssignableFrom /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableFromConstraint AssignableFrom(Type expectedType) { return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(expectedType)); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableFromConstraint AssignableFrom<T>() { return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(typeof(T))); } #endif #endregion #region AssignableTo /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableToConstraint AssignableTo(Type expectedType) { return (AssignableToConstraint)this.Append(new AssignableToConstraint(expectedType)); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableToConstraint AssignableTo<T>() { return (AssignableToConstraint)this.Append(new AssignableToConstraint(typeof(T))); } #endif #endregion #region EquivalentTo /// <summary> /// Returns a constraint that tests whether the actual value /// is a collection containing the same elements as the /// collection supplied as an argument. /// </summary> public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected) { return (CollectionEquivalentConstraint)this.Append(new CollectionEquivalentConstraint(expected)); } #endregion #region SubsetOf /// <summary> /// Returns a constraint that tests whether the actual value /// is a subset of the collection supplied as an argument. /// </summary> public CollectionSubsetConstraint SubsetOf(IEnumerable expected) { return (CollectionSubsetConstraint)this.Append(new CollectionSubsetConstraint(expected)); } #endregion #region Ordered /// <summary> /// Returns a constraint that tests whether a collection is ordered /// </summary> public CollectionOrderedConstraint Ordered { get { return (CollectionOrderedConstraint)this.Append(new CollectionOrderedConstraint()); } } #endregion #region Member /// <summary> /// Returns a new CollectionContainsConstraint checking for the /// presence of a particular object in the collection. /// </summary> public CollectionContainsConstraint Member(object expected) { return (CollectionContainsConstraint)this.Append(new CollectionContainsConstraint(expected)); } /// <summary> /// Returns a new CollectionContainsConstraint checking for the /// presence of a particular object in the collection. /// </summary> public CollectionContainsConstraint Contains(object expected) { return (CollectionContainsConstraint)this.Append(new CollectionContainsConstraint(expected)); } #endregion #region Contains /// <summary> /// Returns a new ContainsConstraint. This constraint /// will, in turn, make use of the appropriate second-level /// constraint, depending on the type of the actual argument. /// This overload is only used if the item sought is a string, /// since any other type implies that we are looking for a /// collection member. /// </summary> public ContainsConstraint Contains(string expected) { return (ContainsConstraint)this.Append(new ContainsConstraint(expected)); } #endregion #region StringContaining /// <summary> /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// </summary> public SubstringConstraint StringContaining(string expected) { return (SubstringConstraint)this.Append(new SubstringConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// </summary> public SubstringConstraint ContainsSubstring(string expected) { return (SubstringConstraint)this.Append(new SubstringConstraint(expected)); } #endregion #region StartsWith /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public StartsWithConstraint StartsWith(string expected) { return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public StartsWithConstraint StringStarting(string expected) { return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected)); } #endregion #region EndsWith /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public EndsWithConstraint EndsWith(string expected) { return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public EndsWithConstraint StringEnding(string expected) { return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected)); } #endregion #region Matches #if !NETCF /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> public RegexConstraint Matches(string pattern) { return (RegexConstraint)this.Append(new RegexConstraint(pattern)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> public RegexConstraint StringMatching(string pattern) { return (RegexConstraint)this.Append(new RegexConstraint(pattern)); } #endif #endregion #region SamePath /// <summary> /// Returns a constraint that tests whether the path provided /// is the same as an expected path after canonicalization. /// </summary> public SamePathConstraint SamePath(string expected) { return (SamePathConstraint)this.Append(new SamePathConstraint(expected)); } #endregion #region SubPath /// <summary> /// Returns a constraint that tests whether the path provided /// is the same path or under an expected path after canonicalization. /// </summary> public SubPathConstraint SubPath(string expected) { return (SubPathConstraint)this.Append(new SubPathConstraint(expected)); } #endregion #region SamePathOrUnder /// <summary> /// Returns a constraint that tests whether the path provided /// is the same path or under an expected path after canonicalization. /// </summary> public SamePathOrUnderConstraint SamePathOrUnder(string expected) { return (SamePathOrUnderConstraint)this.Append(new SamePathOrUnderConstraint(expected)); } #endregion #region InRange #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual value falls /// within a specified range. /// </summary> public RangeConstraint<T> InRange<T>(T from, T to) where T : IComparable<T> { return (RangeConstraint<T>)this.Append(new RangeConstraint<T>(from, to)); } #else /// <summary> /// Returns a constraint that tests whether the actual value falls /// within a specified range. /// </summary> public RangeConstraint InRange(IComparable from, IComparable to) { return (RangeConstraint)this.Append(new RangeConstraint(from, to)); } #endif #endregion } }
//#define UNITY #define UNSAFE namespace JMath { public static class EXCEPTION{ public static readonly System.Exception NO_IMPLEMENT = new System.Exception("no implementm"); } public static class Mathf{ public static Float Min(Float a,Float b ){ if (a.iVal<b.iVal)return a; return b; } public static Float Min(float a,Float b ){ return Min(new Float(a),b); } public static Float MaxAbs(Float a,Float b){ if (Mathf.Abs(a.iVal)>Mathf.Abs(b.iVal)){ return a; } return b; } public static int CeilToInt(Float f){ if (f.iVal % Float.PRECISION == 0) { return (int)(f.iVal / Float.PRECISION); } return (int)(f.iVal/Float.PRECISION)+1; } public static int Max(int a,int b){ if(a>b)return a; return b; } public static Float Abs(Float a){ if (a.iVal<0){ a.iVal = -a.iVal; } return a; } public static int Abs(int a) { if (a > 0) { return a; } return -a; } public static Float Clamp(Float Val,Float v1,Float v2){ if(v1>v2){ var tmv = v1; v1 = v2; v2 = tmv; } if (v1.iVal<=Val.iVal && Val.iVal<=v2.iVal){ return Val; } if (Val.iVal < v1.iVal) { return v1; } return v2; } public static Float MoveTowards(Float Val, Float to, Float speed) { var newVal = Val + speed; newVal = Clamp(newVal, Val, to); return newVal; } #if UNSAFE public static unsafe Float Sqrt(Float Val) { float x = Val.Val; float xhalf = 0.5f * x; int i = *(int*) &x; i = 0x5f375a86 - (i >> 1); x = *(float*) &i; x = x * (1.5f - xhalf * x * x); x = x * (1.5f - xhalf * x * x); x = x * (1.5f - xhalf * x * x); return 1 / x; } #else public static Float Sqrt(Float Val) { return (Float)System.Math.Sqrt(Val.Val); } #endif } public struct Vector2 { public static readonly Vector2 down = new Vector2(0, -1); public static readonly Vector2 up = new Vector2(0, 1); public static readonly Vector2 left = new Vector2(-1, 0); public static readonly Vector2 right = new Vector2(1, 0); public static readonly Vector2 zero = new Vector2(0, 0); public static readonly Vector2 one = new Vector2(1, 1); public Float x, y; public Float distance { get { return (x * x + y * y).Sqrt(); } } public Vector2 normalized { get { var len = (x * x + y * y).Sqrt(); Vector2 v = this; if (len == 0) return zero; v.x /= len; v.y /= len; return v; } } #if UNITY public UnityEngine.Vector2 Val { get { return new UnityEngine.Vector2(x.Val, y.Val); } } #endif public static Float DistanceSquare(Vector2 a, Vector2 b) { var x = a.x-b.x; var y = a.y - b.y; return x * x + y * y; } public static Float Distance(Vector2 a,Vector2 b){ return DistanceSquare(a, b).Sqrt(); } #if UNITY public Vector2(UnityEngine.Vector2 uv):this(uv.x,uv.y){} #endif public Vector2(float x, float y) : this(new Float(x), new Float(y)) { } public Vector2(Float x, Float y) { this.x = x; this.y = y; } public static Vector2 operator *(float f, Vector2 v) { return v * f; } public static Vector2 operator *(Vector2 v, float f) { var newF = new Float(f); return v * newF; } public static Vector2 operator *(Float f, Vector2 v) { return v * f; } public static Vector2 operator *(Vector2 v, Float f) { v.x *= f; v.y *= f; return v; } public static Vector2 operator *(int i, Vector2 v1) { return v1 * i; } public static Vector2 operator *(Vector2 v1, int i) { var v = v1; v.x = v1.x * i; v.y = v1.y * i; return v; } public static Float operator *(Vector2 f, Vector2 v) { return f.Dot(v); } public static Vector2 operator +(Vector2 v1, Vector2 v2) { var v = v1; v.x = v1.x + v2.x; v.y = v1.y + v2.y; return v; } public static Vector2 operator -(Vector2 v1, Vector2 v2) { var v = v1; v.x = v1.x - v2.x; v.y = v1.y - v2.y; return v; } public static Vector2 operator -(Vector2 v2) { var v1 = zero; var v = v1; v.x = v1.x - v2.x; v.y = v1.y - v2.y; return v; } public static Vector2 operator /(Vector2 v1, Float v2) { var v = v1; v.x /= v2; v.y /= v2; return v; } public static bool operator ==(Vector2 v1, Vector2 v2) { return v1.x.iVal == v2.x.iVal && v1.y.iVal == v2.y.iVal; } public static bool operator !=(Vector2 v1, Vector2 v2) { return !(v1 == v2); } public void Negate() { this.x = -x; this.y = -y; } public Float Dot(Vector2 v) { return Vector2.Dot(this, v); } public static Float Dot(Vector2 v1,Vector2 v2) { return v1.x * v2.x + v1.y * v2.y; } public override string ToString() { return "(" + x + "," + y + ")"; } //Project-- public static Vector2 Project(Vector2 vector, Vector2 onNormal) { var num = Vector2.Dot(onNormal, onNormal); if (num == 0) return Vector2.zero; return onNormal * Vector2.Dot(vector, onNormal) / num; } } /// <summary> /// range abs(val)< int.maxVal/PRECISION -- /// </summary> public struct Float { public const int PRECISION = 1000000; public const float TOLERANCE = 10f/PRECISION; public long iVal; public static Float zero = new Float(0); public float Val { get { return (float)((double)iVal/PRECISION); } } public Float(float a) { iVal = (long)(a * PRECISION); } public Float(int a) : this(a, 1) { } public Float(long a, int b) { this.iVal = PRECISION / b; this.iVal *= a; } public Float(int a, int b) { this.iVal = PRECISION / b; this.iVal *= a; } public static implicit operator Float(float v) { return new Float(v); } public static Float operator +(Float v1, Float v2) { v1.iVal += v2.iVal; return v1; } public static Float operator -(Float v1, Float v2) { v1.iVal -=v2.iVal; return v1; } public Float Sqrt() { Float f = this; return Mathf.Sqrt(f); } static Float Abs(Float f) { if (f.iVal > 0) { return f; } f.iVal = -f.iVal; return f; } public static bool operator <=(Float v1, float v2) { return v1 <= new Float (v2); } public static bool operator <=(Float v1, Float v2) { return v1.iVal <= v2.iVal; } public static bool operator <(Float v1, Float v2) { return v1.iVal < v2.iVal; } public static bool operator >=(Float v1, float v2) { return v1 >= new Float (v2); } public static bool operator >=(Float v1, Float v2) { return v1.iVal >= v2.iVal; } public static bool operator >(Float v1, Float v2) { return v1.iVal > v2.iVal; } public override bool Equals(object obj) { if (obj == null || obj is Float == false) { return false; } return this == (Float)obj; } public override int GetHashCode() { return iVal.GetHashCode(); } public static bool operator ==(Float v1, Float v2) { return v1.iVal == v2.iVal; } public static bool operator !=(Float v1, Float v2) { return v1.iVal != v2.iVal; } public static Float operator -(Float v1) { v1.iVal = -v1.iVal; return v1; } public static Float operator *(Float v1, int v2) { v1.iVal *= v2; if ((v1.iVal > 0 && (v1.iVal) > int.MaxValue) || (v1.iVal < 0 && (-v1.iVal) > int.MaxValue)) { throw new System.Exception("Float overflow " + v1.iVal + " * " + v2); } return v1; } public static Float operator *(Float v1, Float v2) { var d1 = v1.iVal - int.MaxValue; var d2 = v2.iVal - int.MaxValue; if (d1 > 0 || d2 > 0) { throw new System.Exception("Float overflow " + v1.iVal + ">" + int.MaxValue + " " + v2.iVal + " > " + int.MaxValue); } v1.iVal *= v2.iVal; v1.iVal /= PRECISION; return v1; } public static Float operator /(Float v1, Float v2) { if (long.MaxValue / PRECISION < Mathf.Abs(v1.iVal)) { throw new System.Exception("Float overflow: " + v1.iVal); } v1.iVal *= PRECISION; v1.iVal /= v2.iVal; return v1; } public static Float operator /(Float v1, int v2) { v1.iVal /= v2; return v1; } public static bool operator >(Float v1,float f){ return v1 >new Float(f); } public static bool operator <(Float v1,float f){ return v1 <new Float(f); } public override string ToString() { return Val.ToString(); } } }
/// Copyright (C) 2012-2014 Soomla Inc. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. using UnityEngine; using System; using System.Collections.Generic; namespace Soomla.Levelup { /// <summary> /// A <c>Level</c> is a type of <c>World</c>, while a <c>World</c> contains a set of <c>Level</c>s. /// Each <c>Level</c> always has a state that is one of: idle, running, paused, ended, or completed. /// /// Real Game Examples: "Candy Crush" and "Angry Birds" use <c>Level</c>s. /// </summary> public class Level : World { // The state of this Level. Every level must have one of the below states. public enum LevelState { Idle, Running, Paused, Ended, Completed } private const string TAG = "SOOMLA Level"; /// <summary> /// The start time of this <c>Level</c>. /// </summary> private long StartTime; /// <summary> /// The elapsed time this <c>Level</c> is being played. /// </summary> private long Elapsed; /// <summary> /// The state of this level. The initial state is idle, later in the game can be any of: /// running, paused, ended, or completed. /// </summary> public LevelState State = LevelState.Idle; /// <summary> /// Constructor. /// </summary> /// <param name="id">ID.</param> public Level(String id) : base(id) { } /// <summary> /// Constructor. /// </summary> /// <param name="id">ID.</param> /// <param name="gate">Gate to open this <c>Level</c>.</param> /// <param name="scores">Scores of this <c>Level</c>.</param> /// <param name="missions">Missions of this <c>Level</c>.</param> public Level(string id, Gate gate, Dictionary<string, Score> scores, List<Mission> missions) : base(id, gate, new Dictionary<string, World>(), scores, missions) { } /// <summary> /// Constructor. /// </summary> /// <param name="id">ID.</param> /// <param name="gate">Gate to open this <c>Level</c>.</param> /// <param name="innerWorlds">Inner <c>Level</c>s of this <c>Level</c>.</param> /// <param name="scores">Scores of this <c>Level</c>.</param> /// <param name="missions">Missions of this <c>Level</c>.</param> public Level(string id, Gate gate, Dictionary<string, World> innerWorlds, Dictionary<string, Score> scores, List<Mission> missions) : base(id, gate, innerWorlds, scores, missions) { } /// <summary> /// Constructor. /// </summary> /// <param name="jsonObj">Json object.</param> public Level(JSONObject jsonObj) : base(jsonObj) { } /// <summary> /// Converts the given JSON object into a <c>Level</c>. /// </summary> /// <returns>Level constructed.</returns> /// <param name="levelObj">The JSON object to be converted.</param> public new static Level fromJSONObject(JSONObject levelObj) { string className = levelObj[JSONConsts.SOOM_CLASSNAME].str; Level level = (Level) Activator.CreateInstance(Type.GetType("Soomla.Levelup." + className), new object[] { levelObj }); return level; } /// <summary> /// Gets the number of times this <c>Level</c> was started. /// </summary> /// <returns>The number of times started.</returns> public int GetTimesStarted() { return LevelStorage.GetTimesStarted(this); } /// <summary> /// Gets the number of times this <c>Level</c> was played. /// </summary> /// <returns>The number of times played.</returns> public int GetTimesPlayed() { return LevelStorage.GetTimesPlayed(this); } /// <summary> /// Gets the slowest duration in millis that this <c>Level</c> was played. /// </summary> /// <returns>The slowest duration in millis.</returns> public long GetSlowestDurationMillis() { return LevelStorage.GetSlowestDurationMillis(this); } /// <summary> /// Gets the fastest duration in millis that this <c>Level</c> was played. /// </summary> /// <returns>The fastest duration in millis.</returns> public long GetFastestDurationMillis() { return LevelStorage.GetFastestDurationMillis(this); } /// <summary> /// Gets the play duration of this <c>Level</c> in millis. /// </summary> /// <returns>The play duration in millis.</returns> public long GetPlayDurationMillis() { long now = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; long duration = Elapsed; if (StartTime != 0) { duration += now - StartTime; } return duration; } /// <summary> /// Starts this <c>Level</c>. /// </summary> public bool Start() { if (State == LevelState.Running) { SoomlaUtils.LogError(TAG, "Can't start a level that is already running. state=" + State); return false; } SoomlaUtils.LogDebug(TAG, "Starting level with world id: " + _id); if (!CanStart()) { return false; } if (State != LevelState.Paused) { Elapsed = 0; LevelStorage.IncTimesStarted(this); } StartTime = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; State = LevelState.Running; return true; } /// <summary> /// Pauses this <c>Level</c>. /// </summary> public void Pause() { if (State != LevelState.Running) { SoomlaUtils.LogError(TAG, "Can't pause a level that is not running. state=" + State); return; } long now = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; Elapsed += now - StartTime; StartTime = 0; State = LevelState.Paused; } /// <summary> /// Ends this <c>Level</c>. /// </summary> /// <param name="completed">If set to <c>true</c> completed.</param> public void End(bool completed) { // check end() called without matching start(), // i.e, the level is not running nor paused if(State != LevelState.Running && State != LevelState.Paused) { SoomlaUtils.LogError(TAG, "end() called without prior start()! ignoring."); return; } State = LevelState.Ended; // Count number of times this level was played LevelStorage.IncTimesPlayed(this); if (completed) { long duration = GetPlayDurationMillis(); // Calculate the slowest \ fastest durations of level play if (duration > GetSlowestDurationMillis()) { LevelStorage.SetSlowestDurationMillis(this, duration); } // We assume that levels' duration is never 0 long fastest = GetFastestDurationMillis(); if (fastest == 0 || duration < GetFastestDurationMillis()) { LevelStorage.SetFastestDurationMillis(this, duration); } foreach (Score score in Scores.Values) { score.Reset(true); // resetting scores } SetCompleted(true); } } /// <summary> /// Restarts this <c>Level</c>. /// </summary> /// <param name="completed">If set to <c>true</c> completed.</param> public void Restart(bool completed) { if (State == LevelState.Running || State == LevelState.Paused) { End(completed); } Start(); } /// <summary> /// Sets this <c>Level</c> as completed. /// </summary> /// <param name="completed">If set to <c>true</c> completed.</param> public override void SetCompleted(bool completed) { if (completed) { State = LevelState.Completed; LevelStorage.IncTimesCompleted(this); } else { State = LevelState.Idle; } base.SetCompleted(completed); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Text { // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, // sequential blocks of characters are converted into blocks of bytes through // calls to the GetBytes method. The encoder maintains state between the // conversions, allowing it to correctly encode character sequences that span // adjacent blocks. // // Instances of specific implementations of the Encoder abstract base // class are typically obtained through calls to the GetEncoder method // of Encoding objects. // internal class EncoderNLS : Encoder { // Need a place for the last left over character, most of our encodings use this internal char _charLeftOver; private readonly Encoding _encoding; private bool _mustFlush; internal bool _throwOnOverflow; internal int _charsUsed; internal EncoderNLS(Encoding encoding) { _encoding = encoding; _fallback = _encoding.EncoderFallback; this.Reset(); } public override void Reset() { _charLeftOver = (char)0; if (_fallbackBuffer != null) _fallbackBuffer.Reset(); } public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush) { // Validate input parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // Just call the pointer version int result = -1; fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) { result = GetByteCount(pChars + index, count, flush); } return result; } public override unsafe int GetByteCount(char* chars, int count, bool flush) { // Validate input parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); _mustFlush = flush; _throwOnOverflow = true; Debug.Assert(_encoding != null); return _encoding.GetByteCount(chars, count, this); } public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; // Just call pointer version fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) // Remember that charCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush); } public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); _mustFlush = flush; _throwOnOverflow = true; Debug.Assert(_encoding != null); return _encoding.GetBytes(chars, charCount, bytes, byteCount, this); } // This method is used when your output buffer might not be large enough for the entire result. // Just call the pointer version. (This gets bytes) public override unsafe void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Just call the pointer version (can't do this for non-msft encoders) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) { fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) { Convert(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); } } } // This is the version that uses pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting bytes public override unsafe void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate input parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // We don't want to throw _mustFlush = flush; _throwOnOverflow = false; _charsUsed = 0; // Do conversion Debug.Assert(_encoding != null); bytesUsed = _encoding.GetBytes(chars, charCount, bytes, byteCount, this); charsUsed = _charsUsed; // Per MSDN, "The completed output parameter indicates whether all the data in the input // buffer was converted and stored in the output buffer." That means we've successfully // consumed all the input _and_ there's no pending state or fallback data remaining to be output. completed = (charsUsed == charCount) && !this.HasState && (_fallbackBuffer is null || _fallbackBuffer.Remaining == 0); } public Encoding Encoding { get { Debug.Assert(_encoding != null); return _encoding; } } public bool MustFlush => _mustFlush; /// <summary> /// States whether a call to <see cref="Encoding.GetBytes(char*, int, byte*, int, EncoderNLS)"/> must first drain data on this <see cref="EncoderNLS"/> instance. /// </summary> internal bool HasLeftoverData => _charLeftOver != default || (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0); // Anything left in our encoder? internal virtual bool HasState => _charLeftOver != (char)0; // Allow encoding to clear our must flush instead of throwing (in ThrowBytesOverflow) internal void ClearMustFlush() { _mustFlush = false; } internal int DrainLeftoverDataForGetByteCount(ReadOnlySpan<char> chars, out int charsConsumed) { // Quick check: we _should not_ have leftover fallback data from a previous invocation, // as we'd end up consuming any such data and would corrupt whatever Convert call happens // to be in progress. if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) { throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, Encoding.EncodingName, _fallbackBuffer.GetType())); } // If we have a leftover high surrogate from a previous operation, consume it now. // We won't clear the _charLeftOver field since GetByteCount is supposed to be // a non-mutating operation, and we need the field to retain its value for the // next call to Convert. charsConsumed = 0; // could be incorrect, will fix up later in the method if (_charLeftOver == default) { return 0; // no leftover high surrogate char - short-circuit and finish } else { char secondChar = default; if (chars.IsEmpty) { // If the input buffer is empty and we're not being asked to flush, no-op and return // success to our caller. If we're being asked to flush, the leftover high surrogate from // the previous operation will go through the fallback mechanism by itself. if (!MustFlush) { return 0; // no-op = success } } else { secondChar = chars[0]; } // If we have to fallback the chars we're reading immediately below, populate the // fallback buffer with the invalid data. We'll just fall through to the "consume // fallback buffer" logic at the end of the method. bool didFallback; if (Rune.TryCreate(_charLeftOver, secondChar, out Rune rune)) { charsConsumed = 1; // consumed the leftover high surrogate + the first char in the input buffer Debug.Assert(_encoding != null); if (_encoding.TryGetByteCount(rune, out int byteCount)) { Debug.Assert(byteCount >= 0, "Encoding shouldn't have returned a negative byte count."); return byteCount; } else { // The fallback mechanism relies on a negative index to convey "the start of the invalid // sequence was some number of chars back before the current buffer." In this block and // in the block immediately thereafter, we know we have a single leftover high surrogate // character from a previous operation, so we provide an index of -1 to convey that the // char immediately before the current buffer was the start of the invalid sequence. didFallback = FallbackBuffer.Fallback(_charLeftOver, secondChar, index: -1); } } else { didFallback = FallbackBuffer.Fallback(_charLeftOver, index: -1); } // Now tally the number of bytes that would've been emitted as part of fallback. Debug.Assert(_fallbackBuffer != null); return _fallbackBuffer.DrainRemainingDataForGetByteCount(); } } internal bool TryDrainLeftoverDataForGetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsConsumed, out int bytesWritten) { // We may have a leftover high surrogate data from a previous invocation, or we may have leftover // data in the fallback buffer, or we may have neither, but we will never have both. Check for these // conditions and handle them now. charsConsumed = 0; // could be incorrect, will fix up later in the method bytesWritten = 0; // could be incorrect, will fix up later in the method if (_charLeftOver != default) { char secondChar = default; if (chars.IsEmpty) { // If the input buffer is empty and we're not being asked to flush, no-op and return // success to our caller. If we're being asked to flush, the leftover high surrogate from // the previous operation will go through the fallback mechanism by itself. if (!MustFlush) { charsConsumed = 0; bytesWritten = 0; return true; // no-op = success } } else { secondChar = chars[0]; } // If we have to fallback the chars we're reading immediately below, populate the // fallback buffer with the invalid data. We'll just fall through to the "consume // fallback buffer" logic at the end of the method. if (Rune.TryCreate(_charLeftOver, secondChar, out Rune rune)) { charsConsumed = 1; // at the very least, we consumed 1 char from the input Debug.Assert(_encoding != null); switch (_encoding.EncodeRune(rune, bytes, out bytesWritten)) { case OperationStatus.Done: _charLeftOver = default; // we just consumed this char return true; // that's all - we've handled the leftover data case OperationStatus.DestinationTooSmall: _charLeftOver = default; // we just consumed this char _encoding.ThrowBytesOverflow(this, nothingEncoded: true); // will throw break; case OperationStatus.InvalidData: FallbackBuffer.Fallback(_charLeftOver, secondChar, index: -1); // see comment in DrainLeftoverDataForGetByteCount break; default: Debug.Fail("Unknown return value."); break; } } else { FallbackBuffer.Fallback(_charLeftOver, index: -1); // see comment in DrainLeftoverDataForGetByteCount } } // Now check the fallback buffer for any remaining data. if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) { return _fallbackBuffer.TryDrainRemainingDataForGetBytes(bytes, out bytesWritten); } // And we're done! return true; // success } } }
using System; using System.Text; using System.Web; using Nop.Core; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Orders; using Nop.Core.Html; using Nop.Services.Directory; using Nop.Services.Localization; using Nop.Services.Media; using Nop.Services.Tax; namespace Nop.Services.Catalog { /// <summary> /// Product attribute formatter /// </summary> public partial class ProductAttributeFormatter : IProductAttributeFormatter { private readonly IWorkContext _workContext; private readonly IProductAttributeService _productAttributeService; private readonly IProductAttributeParser _productAttributeParser; private readonly ICurrencyService _currencyService; private readonly ILocalizationService _localizationService; private readonly ITaxService _taxService; private readonly IPriceFormatter _priceFormatter; private readonly IDownloadService _downloadService; private readonly IWebHelper _webHelper; private readonly IPriceCalculationService _priceCalculationService; private readonly ShoppingCartSettings _shoppingCartSettings; public ProductAttributeFormatter(IWorkContext workContext, IProductAttributeService productAttributeService, IProductAttributeParser productAttributeParser, ICurrencyService currencyService, ILocalizationService localizationService, ITaxService taxService, IPriceFormatter priceFormatter, IDownloadService downloadService, IWebHelper webHelper, IPriceCalculationService priceCalculationService, ShoppingCartSettings shoppingCartSettings) { this._workContext = workContext; this._productAttributeService = productAttributeService; this._productAttributeParser = productAttributeParser; this._currencyService = currencyService; this._localizationService = localizationService; this._taxService = taxService; this._priceFormatter = priceFormatter; this._downloadService = downloadService; this._webHelper = webHelper; this._priceCalculationService = priceCalculationService; this._shoppingCartSettings = shoppingCartSettings; } /// <summary> /// Formats attributes /// </summary> /// <param name="product">Product</param> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Attributes</returns> public virtual string FormatAttributes(Product product, string attributesXml) { var customer = _workContext.CurrentCustomer; return FormatAttributes(product, attributesXml, customer); } /// <summary> /// Formats attributes /// </summary> /// <param name="product">Product</param> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="customer">Customer</param> /// <param name="serapator">Serapator</param> /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param> /// <param name="renderPrices">A value indicating whether to render prices</param> /// <param name="renderProductAttributes">A value indicating whether to render product attributes</param> /// <param name="renderGiftCardAttributes">A value indicating whether to render gift card attributes</param> /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param> /// <returns>Attributes</returns> public virtual string FormatAttributes(Product product, string attributesXml, Customer customer, string serapator = "<br />", bool htmlEncode = true, bool renderPrices = true, bool renderProductAttributes = true, bool renderGiftCardAttributes = true, bool allowHyperlinks = true) { var result = new StringBuilder(); //attributes if (renderProductAttributes) { var attributes = _productAttributeParser.ParseProductAttributeMappings(attributesXml); for (int i = 0; i < attributes.Count; i++) { var attribute = attributes[i]; var valuesStr = _productAttributeParser.ParseValues(attributesXml, attribute.Id); for (int j = 0; j < valuesStr.Count; j++) { string valueStr = valuesStr[j]; string formattedAttribute = string.Empty; if (!attribute.ShouldHaveValues()) { //no values if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox) { //multiline textbox var attributeName = attribute.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id); //encode (if required) if (htmlEncode) attributeName = HttpUtility.HtmlEncode(attributeName); formattedAttribute = string.Format("{0}: {1}", attributeName, HtmlHelper.FormatText(valueStr, false, true, false, false, false, false)); //we never encode multiline textbox input } else if (attribute.AttributeControlType == AttributeControlType.FileUpload) { //file upload Guid downloadGuid; Guid.TryParse(valueStr, out downloadGuid); var download = _downloadService.GetDownloadByGuid(downloadGuid); if (download != null) { //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) string attributeText; var fileName = string.Format("{0}{1}", download.Filename ?? download.DownloadGuid.ToString(), download.Extension); //encode (if required) if (htmlEncode) fileName = HttpUtility.HtmlEncode(fileName); if (allowHyperlinks) { //hyperlinks are allowed var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid); attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName); } else { //hyperlinks aren't allowed attributeText = fileName; } var attributeName = attribute.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id); //encode (if required) if (htmlEncode) attributeName = HttpUtility.HtmlEncode(attributeName); formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText); } } else { //other attributes (textbox, datepicker) formattedAttribute = string.Format("{0}: {1}", attribute.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), valueStr); //encode (if required) if (htmlEncode) formattedAttribute = HttpUtility.HtmlEncode(formattedAttribute); } } else { //attributes with values int attributeValueId; if (int.TryParse(valueStr, out attributeValueId)) { var attributeValue = _productAttributeService.GetProductAttributeValueById(attributeValueId); if (attributeValue != null) { formattedAttribute = string.Format("{0}: {1}", attribute.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), attributeValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id)); if (renderPrices) { decimal taxRate; decimal attributeValuePriceAdjustment = _priceCalculationService.GetProductAttributeValuePriceAdjustment(attributeValue); decimal priceAdjustmentBase = _taxService.GetProductPrice(product, attributeValuePriceAdjustment, customer, out taxRate); decimal priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency); if (priceAdjustmentBase > 0) { string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment, false, false); formattedAttribute += string.Format(" [+{0}]", priceAdjustmentStr); } else if (priceAdjustmentBase < decimal.Zero) { string priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustment, false, false); formattedAttribute += string.Format(" [-{0}]", priceAdjustmentStr); } } //display quantity if (_shoppingCartSettings.RenderAssociatedAttributeValueQuantity && attributeValue.AttributeValueType == AttributeValueType.AssociatedToProduct) { //render only when more than 1 if (attributeValue.Quantity > 1) { //TODO localize resource formattedAttribute += string.Format(" - qty {0}", attributeValue.Quantity); } } } //encode (if required) if (htmlEncode) formattedAttribute = HttpUtility.HtmlEncode(formattedAttribute); } } if (!String.IsNullOrEmpty(formattedAttribute)) { if (i != 0 || j != 0) result.Append(serapator); result.Append(formattedAttribute); } } } } //gift cards if (renderGiftCardAttributes) { if (product.IsGiftCard) { string giftCardRecipientName; string giftCardRecipientEmail; string giftCardSenderName; string giftCardSenderEmail; string giftCardMessage; _productAttributeParser.GetGiftCardAttribute(attributesXml, out giftCardRecipientName, out giftCardRecipientEmail, out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage); //sender var giftCardFrom = product.GiftCardType == GiftCardType.Virtual ? string.Format(_localizationService.GetResource("GiftCardAttribute.From.Virtual"), giftCardSenderName, giftCardSenderEmail) : string.Format(_localizationService.GetResource("GiftCardAttribute.From.Physical"), giftCardSenderName); //recipient var giftCardFor = product.GiftCardType == GiftCardType.Virtual ? string.Format(_localizationService.GetResource("GiftCardAttribute.For.Virtual"), giftCardRecipientName, giftCardRecipientEmail) : string.Format(_localizationService.GetResource("GiftCardAttribute.For.Physical"), giftCardRecipientName); //encode (if required) if (htmlEncode) { giftCardFrom = HttpUtility.HtmlEncode(giftCardFrom); giftCardFor = HttpUtility.HtmlEncode(giftCardFor); } if (!String.IsNullOrEmpty(result.ToString())) { result.Append(serapator); } result.Append(giftCardFrom); result.Append(serapator); result.Append(giftCardFor); } } return result.ToString(); } } }
using System.Collections.Generic; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.SceneManagement; public enum SpLink_Scene { None, This, All } public class SpLink_Wizard : ScriptableWizard { private SpAtlas atlas; private SpLink_Scene inScenes = SpLink_Scene.All; private bool inPrefabs = true; private bool inScriptableObjects = true; private bool inAnimationClips = true; private Sprite[] sourceSprites; private Sprite[] packedSprites; private Vector2 scrollPosition; public static SpLink_Wizard Open(SpAtlas atlas) { if (atlas != null) { var path = AssetDatabase.GUIDToAssetPath(atlas.Identifier); var texture = AssetDatabase.LoadMainAssetAtPath(path) as Texture2D; if (texture != null) { var allSourceSprites = new List<Sprite>(); var allPackedSprites = new List<Sprite>(); for (var i = 0; i < atlas.Sources.Count; i++) { var source = atlas.Sources[i]; var sourceSprites = source.Sprites; if (sourceSprites.Count > 0) { allSourceSprites.AddRange(sourceSprites); allPackedSprites.AddRange(source.FindSprites(atlas.Sprites, sourceSprites)); } } if (allSourceSprites.Count > 0) { var linker = ScriptableWizard.DisplayWizard<SpLink_Wizard>("Sprite Linker", "Link", "Cancel"); linker.atlas = atlas; linker.sourceSprites = allSourceSprites.ToArray(); linker.packedSprites = allPackedSprites.ToArray(); return linker; } } } return null; } public void OnGUI() { if (atlas != null) { EditorGUILayout.HelpBox("This tool will replace all your non-atlas sprites with these atlas sprites (e.g. in your prefabs & scripts)", MessageType.Info); EditorGUILayout.Separator(); inScenes = (SpLink_Scene)EditorGUILayout.EnumPopup("In Scenes", inScenes); inPrefabs = EditorGUILayout.Toggle("In Prefabs", inPrefabs); inScriptableObjects = EditorGUILayout.Toggle("In Scriptable Objects", inScriptableObjects); inAnimationClips = EditorGUILayout.Toggle("In Animation Clips", inAnimationClips); EditorGUILayout.Separator(); EditorGUILayout.LabelField("Replace", EditorStyles.boldLabel); scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition); { for (var i = 0; i < sourceSprites.Length; i++) { var rect = SpHelper.Reserve(); var rect0 = rect; rect0.xMax = rect0.center.x - 20; var rect1 = rect; rect1.xMin = rect1.center.x + 20; var rect2 = rect; rect2.xMin = rect2.center.x - 20; rect2.xMax = rect2.center.x + 20; if (sourceSprites[i] == null) { GUI.Box(rect0, "", SpHelper.RedBox); } sourceSprites[i] = (Sprite)EditorGUI.ObjectField(rect0, sourceSprites[i], typeof(Sprite), true); packedSprites[i] = (Sprite)EditorGUI.ObjectField(rect1, packedSprites[i], typeof(Sprite), true); EditorGUI.LabelField(rect2, "With"); } } EditorGUILayout.EndScrollView(); EditorGUILayout.Separator(); DrawButtons(); } else { Close(); } } private Scene currentScene = SceneManager.GetActiveScene(); private void DrawButtons() { var rect = SpHelper.Reserve(); var rect0 = rect; rect0.xMax = rect0.center.x - 1; var rect1 = rect; rect1.xMin = rect1.center.x + 1; if (GUI.Button(rect0, "Link Sprites") == true) { switch (inScenes) { case SpLink_Scene.This: { LinkInScene(); } break; case SpLink_Scene.All: { if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { currentScene = SceneManager.GetActiveScene(); var sceneGuids = AssetDatabase.FindAssets("t:scene"); foreach (var sceneGuid in sceneGuids) { var scenePath = AssetDatabase.GUIDToAssetPath(sceneGuid); if (EditorSceneManager.OpenScene(scenePath) != default(Scene)) { LinkInScene(); EditorSceneManager.SaveOpenScenes(); } } EditorSceneManager.OpenScene(currentScene.name); } } break; } if (inPrefabs == true) { LinkInPrefabs(); } if (inScriptableObjects == true) { LinkInScriptableObjects(); } if (inAnimationClips == true) { LinkInAnimationClips(); } EditorSceneManager.MarkSceneDirty(currentScene); } if (GUI.Button(rect1, "Cancel") == true) { Close(); } } private void LinkInScene() { var gameObjects = Object.FindObjectsOfType<GameObject>(); foreach (var gameObject in gameObjects) { var transform = gameObject.transform; if (transform.parent == null) { LinkInTransform(transform); } } } private void LinkInPrefabs() { var guids = AssetDatabase.FindAssets("t:prefab"); foreach (var guid in guids) { var path = AssetDatabase.GUIDToAssetPath(guid); var prefab = AssetDatabase.LoadMainAssetAtPath(path) as GameObject; if (prefab != null) { LinkInTransform(prefab.transform); } } } private void LinkInScriptableObjects() { var guids = AssetDatabase.FindAssets("t:scriptableobject"); foreach (var guid in guids) { var path = AssetDatabase.GUIDToAssetPath(guid); var scriptableObject = AssetDatabase.LoadMainAssetAtPath(path) as ScriptableObject; if (scriptableObject != null) { if (LinkInObject(scriptableObject) == true) { EditorUtility.SetDirty(scriptableObject); } } } } private void LinkInAnimationClips() { var guids = AssetDatabase.FindAssets("t:animationclip"); foreach (var guid in guids) { var path = AssetDatabase.GUIDToAssetPath(guid); var animationClip = AssetDatabase.LoadMainAssetAtPath(path) as AnimationClip; if (animationClip != null) { var bindings = AnimationUtility.GetObjectReferenceCurveBindings(animationClip); foreach (var binding in bindings) { var keys = AnimationUtility.GetObjectReferenceCurve(animationClip, binding); var dirty = false; for (var i = 0; i < keys.Length; i++) { var key = keys[i]; var sprite = key.value as Sprite; if (Link(ref sprite) == true) { key.value = sprite; keys[i] = key; dirty = true; } } if (dirty == true) { AnimationUtility.SetObjectReferenceCurve(animationClip, binding, keys); EditorUtility.SetDirty(animationClip); } } } } } private void LinkInTransform(Transform t) { var components = t.GetComponents<Component>(); foreach (var component in components) { LinkInComponent(component); } for (var i = 0; i < t.childCount; i++) { LinkInTransform(t.GetChild(i)); } } private void LinkInComponent(Component c) { // Sprite renderers don't store the sprite in a field, so manually replace it var spriteRenderer = c as SpriteRenderer; if (spriteRenderer != null) { var sprite = spriteRenderer.sprite; if (Link(ref sprite) == true) { spriteRenderer.sprite = sprite; EditorUtility.SetDirty(spriteRenderer); } return; } // Images don't store the sprite in a field, so manually replace it var image = c as UnityEngine.UI.Image; if (image != null) { var sprite = image.sprite; if (Link(ref sprite) == true) { image.sprite = sprite; EditorUtility.SetDirty(image); } return; } if (LinkInObject(c) == true) { EditorUtility.SetDirty(c); } } private bool LinkInObject(Object o) { var dirty = false; if (o != null) { var fields = o.GetType().GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public); foreach (var field in fields) { var type = field.FieldType; if (type == typeof(Sprite)) { var sprite = (Sprite)field.GetValue(o); if (Link(ref sprite) == true) { field.SetValue(o, sprite); dirty = true; } } } } return dirty; } private bool Link(ref Sprite sprite) { if (sprite != null) { var index = System.Array.IndexOf(sourceSprites, sprite); if (index != -1) { sprite = packedSprites[index]; if (sprite != null) { return true; } } } return false; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Reflection; namespace System.ServiceModel.Description { [DebuggerDisplay("Name={_name}, IsInitiating={_isInitiating}")] public class OperationDescription { internal const string SessionOpenedAction = Channels.WebSocketTransportSettings.ConnectionOpenedAction; private XmlName _name; private bool _isInitiating; private bool _isSessionOpenNotificationEnabled; private ContractDescription _declaringContract; private FaultDescriptionCollection _faults; private MessageDescriptionCollection _messages; private KeyedByTypeCollection<IOperationBehavior> _behaviors; private Collection<Type> _knownTypes; private MethodInfo _beginMethod; private MethodInfo _endMethod; private MethodInfo _syncMethod; private MethodInfo _taskMethod; private bool _validateRpcWrapperName = true; private bool _hasNoDisposableParameters; public OperationDescription(string name, ContractDescription declaringContract) { if (name == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name"); } if (name.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("name", SR.SFxOperationDescriptionNameCannotBeEmpty)); } _name = new XmlName(name, true /*isEncoded*/); if (declaringContract == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("declaringContract"); } _declaringContract = declaringContract; _isInitiating = true; _faults = new FaultDescriptionCollection(); _messages = new MessageDescriptionCollection(); _behaviors = new KeyedByTypeCollection<IOperationBehavior>(); _knownTypes = new Collection<Type>(); } internal OperationDescription(string name, ContractDescription declaringContract, bool validateRpcWrapperName) : this(name, declaringContract) { _validateRpcWrapperName = validateRpcWrapperName; } public KeyedCollection<Type, IOperationBehavior> OperationBehaviors { get { return this.Behaviors; } } [EditorBrowsable(EditorBrowsableState.Never)] public KeyedByTypeCollection<IOperationBehavior> Behaviors { get { return _behaviors; } } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime public MethodInfo TaskMethod { get { return _taskMethod; } set { _taskMethod = value; } } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime public MethodInfo SyncMethod { get { return _syncMethod; } set { _syncMethod = value; } } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime public MethodInfo BeginMethod { get { return _beginMethod; } set { _beginMethod = value; } } internal MethodInfo OperationMethod { get { if (this.SyncMethod == null) { return this.TaskMethod ?? this.BeginMethod; } else { return this.SyncMethod; } } } internal bool HasNoDisposableParameters { get { return _hasNoDisposableParameters; } set { _hasNoDisposableParameters = value; } } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime public MethodInfo EndMethod { get { return _endMethod; } set { _endMethod = value; } } public ContractDescription DeclaringContract { get { return _declaringContract; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("DeclaringContract"); } else { _declaringContract = value; } } } public FaultDescriptionCollection Faults { get { return _faults; } } public bool IsOneWay { get { return this.Messages.Count == 1; } } public bool IsInitiating { get { return _isInitiating; } set { _isInitiating = value; } } internal bool IsServerInitiated() { EnsureInvariants(); return Messages[0].Direction == MessageDirection.Output; } public Collection<Type> KnownTypes { get { return _knownTypes; } } // Messages[0] is the 'request' (first of MEP), and for non-oneway MEPs, Messages[1] is the 'response' (second of MEP) public MessageDescriptionCollection Messages { get { return _messages; } } internal XmlName XmlName { get { return _name; } } internal string CodeName { get { return _name.DecodedName; } } public string Name { get { return _name.EncodedName; } } internal bool IsValidateRpcWrapperName { get { return _validateRpcWrapperName; } } internal Type TaskTResult { get; set; } internal bool HasOutputParameters { get { // For non-oneway operations, Messages[1] is the 'response' return (this.Messages.Count > 1) && (this.Messages[1].Body.Parts.Count > 0); } } internal bool IsSessionOpenNotificationEnabled { get { return _isSessionOpenNotificationEnabled; } set { _isSessionOpenNotificationEnabled = value; } } internal void EnsureInvariants() { if (this.Messages.Count != 1 && this.Messages.Count != 2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new System.InvalidOperationException(SR.Format(SR.SFxOperationMustHaveOneOrTwoMessages, this.Name))); } } } }